package intelligence

import (
	"time"
)

// FileMetadata represents metadata extracted from file system
type FileMetadata struct {
	Path         string    `json:"path"`          // File path
	Size         int64     `json:"size"`          // File size in bytes
	ModTime      time.Time `json:"mod_time"`      // Last modification time
	Mode         uint32    `json:"mode"`          // File mode
	IsDir        bool      `json:"is_dir"`        // Whether it's a directory
	Extension    string    `json:"extension"`     // File extension
	MimeType     string    `json:"mime_type"`     // MIME type
	Hash         string    `json:"hash"`          // Content hash
	Permissions  string    `json:"permissions"`   // File permissions
}

// StructureAnalysis represents analysis of code structure
type StructureAnalysis struct {
	Architecture    string            `json:"architecture"`     // Architectural pattern
	Patterns        []string          `json:"patterns"`         // Design patterns used
	Components      []*Component      `json:"components"`       // Code components
	Relationships   []*Relationship   `json:"relationships"`    // Component relationships
	Complexity      *ComplexityMetrics `json:"complexity"`      // Complexity metrics
	QualityMetrics  *QualityMetrics   `json:"quality_metrics"` // Code quality metrics
	TestCoverage    float64           `json:"test_coverage"`    // Test coverage percentage
	Documentation   *DocMetrics       `json:"documentation"`    // Documentation metrics
	AnalyzedAt      time.Time         `json:"analyzed_at"`      // When analysis was performed
}

// Component represents a code component
type Component struct {
	Name        string            `json:"name"`         // Component name
	Type        string            `json:"type"`         // Component type (class, function, etc.)
	Purpose     string            `json:"purpose"`      // Component purpose
	Visibility  string            `json:"visibility"`   // Visibility (public, private, etc.)
	Lines       int               `json:"lines"`        // Lines of code
	Complexity  int               `json:"complexity"`   // Cyclomatic complexity
	Dependencies []string         `json:"dependencies"` // Dependencies
	Metadata    map[string]interface{} `json:"metadata"` // Additional metadata
}

// Relationship represents a relationship between components
type Relationship struct {
	From        string  `json:"from"`         // Source component
	To          string  `json:"to"`           // Target component
	Type        string  `json:"type"`         // Relationship type
	Strength    float64 `json:"strength"`     // Relationship strength (0-1)
	Direction   string  `json:"direction"`    // Direction (unidirectional, bidirectional)
	Description string  `json:"description"`  // Relationship description
}

// ComplexityMetrics represents code complexity metrics
type ComplexityMetrics struct {
	Cyclomatic      float64 `json:"cyclomatic"`       // Cyclomatic complexity
	Cognitive       float64 `json:"cognitive"`        // Cognitive complexity
	Halstead        float64 `json:"halstead"`         // Halstead complexity
	Maintainability float64 `json:"maintainability"`  // Maintainability index
	TechnicalDebt   float64 `json:"technical_debt"`   // Technical debt estimate
}

// QualityMetrics represents code quality metrics
type QualityMetrics struct {
	Readability     float64 `json:"readability"`      // Readability score
	Testability     float64 `json:"testability"`      // Testability score
	Reusability     float64 `json:"reusability"`      // Reusability score
	Reliability     float64 `json:"reliability"`      // Reliability score
	Security        float64 `json:"security"`         // Security score
	Performance     float64 `json:"performance"`      // Performance score
	Duplication     float64 `json:"duplication"`      // Code duplication percentage
	Consistency     float64 `json:"consistency"`      // Code consistency score
}

// DocMetrics represents documentation metrics
type DocMetrics struct {
	Coverage        float64 `json:"coverage"`         // Documentation coverage
	Quality         float64 `json:"quality"`          // Documentation quality
	CommentRatio    float64 `json:"comment_ratio"`    // Comment to code ratio
	APIDocCoverage  float64 `json:"api_doc_coverage"` // API documentation coverage
	ExampleCount    int     `json:"example_count"`    // Number of examples
	TODOCount       int     `json:"todo_count"`       // Number of TODO comments
	FIXMECount      int     `json:"fixme_count"`      // Number of FIXME comments
}

// DirectoryStructure represents analysis of directory organization
type DirectoryStructure struct {
	Path            string              `json:"path"`             // Directory path
	FileCount       int                 `json:"file_count"`       // Number of files
	DirectoryCount  int                 `json:"directory_count"`  // Number of subdirectories
	TotalSize       int64               `json:"total_size"`       // Total size in bytes
	FileTypes       map[string]int      `json:"file_types"`       // File type distribution
	Languages       map[string]int      `json:"languages"`        // Language distribution
	Organization    *OrganizationInfo   `json:"organization"`     // Organization information
	Conventions     *ConventionInfo     `json:"conventions"`      // Convention information
	Dependencies    []string            `json:"dependencies"`     // Directory dependencies
	Purpose         string              `json:"purpose"`          // Directory purpose
	Architecture    string              `json:"architecture"`     // Architectural pattern
	AnalyzedAt      time.Time           `json:"analyzed_at"`      // When analysis was performed
}

// OrganizationInfo represents directory organization information
type OrganizationInfo struct {
	Pattern         string            `json:"pattern"`          // Organization pattern
	Consistency     float64           `json:"consistency"`      // Organization consistency
	Depth           int               `json:"depth"`            // Directory depth
	FanOut          int               `json:"fan_out"`          // Average fan-out
	Modularity      float64           `json:"modularity"`       // Modularity score
	Cohesion        float64           `json:"cohesion"`         // Cohesion score
	Coupling        float64           `json:"coupling"`         // Coupling score
	Metadata        map[string]interface{} `json:"metadata"`   // Additional metadata
}

// ConventionInfo represents naming and organizational conventions
type ConventionInfo struct {
	NamingStyle     string            `json:"naming_style"`     // Naming convention style
	FileNaming      string            `json:"file_naming"`      // File naming pattern
	DirectoryNaming string            `json:"directory_naming"` // Directory naming pattern
	Consistency     float64           `json:"consistency"`      // Convention consistency
	Violations      []*Violation      `json:"violations"`       // Convention violations
	Standards       []string          `json:"standards"`        // Applied standards
}

// Violation represents a convention violation
type Violation struct {
	Type        string  `json:"type"`        // Violation type
	Path        string  `json:"path"`        // Violating path
	Expected    string  `json:"expected"`    // Expected format
	Actual      string  `json:"actual"`      // Actual format
	Severity    string  `json:"severity"`    // Violation severity
	Suggestion  string  `json:"suggestion"`  // Suggested fix
}

// ConventionAnalysis represents analysis of naming and organizational conventions
type ConventionAnalysis struct {
	NamingPatterns      []*NamingPattern      `json:"naming_patterns"`       // Detected naming patterns
	OrganizationalPatterns []*OrganizationalPattern `json:"organizational_patterns"` // Organizational patterns
	Consistency         float64               `json:"consistency"`           // Overall consistency score
	Violations          []*Violation          `json:"violations"`            // Convention violations
	Recommendations     []*Recommendation     `json:"recommendations"`       // Improvement recommendations
	AppliedStandards    []string              `json:"applied_standards"`     // Applied coding standards
	AnalyzedAt          time.Time             `json:"analyzed_at"`           // When analysis was performed
}

// RelationshipAnalysis represents analysis of directory relationships
type RelationshipAnalysis struct {
	Dependencies    []*DirectoryDependency `json:"dependencies"`     // Directory dependencies
	Relationships   []*DirectoryRelation   `json:"relationships"`    // Directory relationships
	CouplingMetrics *CouplingMetrics       `json:"coupling_metrics"` // Coupling metrics
	ModularityScore float64                `json:"modularity_score"` // Modularity score
	ArchitecturalStyle string              `json:"architectural_style"` // Architectural style
	AnalyzedAt      time.Time              `json:"analyzed_at"`      // When analysis was performed
}

// DirectoryDependency represents a dependency between directories
type DirectoryDependency struct {
	From        string  `json:"from"`         // Source directory
	To          string  `json:"to"`           // Target directory
	Type        string  `json:"type"`         // Dependency type
	Strength    float64 `json:"strength"`     // Dependency strength
	Reason      string  `json:"reason"`       // Reason for dependency
	FileCount   int     `json:"file_count"`   // Number of files involved
}

// DirectoryRelation represents a relationship between directories
type DirectoryRelation struct {
	Directory1  string  `json:"directory1"`   // First directory
	Directory2  string  `json:"directory2"`   // Second directory
	Type        string  `json:"type"`         // Relation type
	Strength    float64 `json:"strength"`     // Relation strength
	Description string  `json:"description"`  // Relation description
	Bidirectional bool  `json:"bidirectional"` // Whether relation is bidirectional
}

// CouplingMetrics represents coupling metrics between directories
type CouplingMetrics struct {
	AfferentCoupling  float64 `json:"afferent_coupling"`  // Afferent coupling
	EfferentCoupling  float64 `json:"efferent_coupling"`  // Efferent coupling
	Instability       float64 `json:"instability"`        // Instability metric
	Abstractness      float64 `json:"abstractness"`       // Abstractness metric
	DistanceFromMain  float64 `json:"distance_from_main"` // Distance from main sequence
}

// Pattern represents a detected pattern in code or organization
type Pattern struct {
	ID            string                 `json:"id"`             // Pattern identifier
	Name          string                 `json:"name"`           // Pattern name
	Type          string                 `json:"type"`           // Pattern type
	Description   string                 `json:"description"`    // Pattern description
	Confidence    float64                `json:"confidence"`     // Detection confidence
	Frequency     int                    `json:"frequency"`      // Pattern frequency
	Examples      []string               `json:"examples"`       // Example instances
	Criteria      map[string]interface{} `json:"criteria"`       // Pattern criteria
	Benefits      []string               `json:"benefits"`       // Pattern benefits
	Drawbacks     []string               `json:"drawbacks"`      // Pattern drawbacks
	ApplicableRoles []string             `json:"applicable_roles"` // Roles that benefit from this pattern
	DetectedAt    time.Time              `json:"detected_at"`    // When pattern was detected
}

// CodePattern represents a code-specific pattern
type CodePattern struct {
	Pattern                               // Embedded base pattern
	Language      string                 `json:"language"`       // Programming language
	Framework     string                 `json:"framework"`      // Framework context
	Complexity    float64                `json:"complexity"`     // Pattern complexity
	Usage         *UsagePattern          `json:"usage"`          // Usage pattern
	Performance   *PerformanceInfo       `json:"performance"`    // Performance characteristics
}

// NamingPattern represents a naming convention pattern
type NamingPattern struct {
	Pattern                               // Embedded base pattern
	Convention    string                 `json:"convention"`     // Naming convention
	Scope         string                 `json:"scope"`          // Pattern scope
	Regex         string                 `json:"regex"`          // Regex pattern
	CaseStyle     string                 `json:"case_style"`     // Case style (camelCase, snake_case, etc.)
	Prefix        string                 `json:"prefix"`         // Common prefix
	Suffix        string                 `json:"suffix"`         // Common suffix
}

// OrganizationalPattern represents an organizational pattern
type OrganizationalPattern struct {
	Pattern                               // Embedded base pattern
	Structure     string                 `json:"structure"`      // Organizational structure
	Depth         int                    `json:"depth"`          // Typical depth
	FanOut        int                    `json:"fan_out"`        // Typical fan-out
	Modularity    float64                `json:"modularity"`     // Modularity characteristics
	Scalability   string                 `json:"scalability"`    // Scalability characteristics
}

// UsagePattern represents how a pattern is typically used
type UsagePattern struct {
	Frequency     string                 `json:"frequency"`      // Usage frequency
	Context       []string               `json:"context"`        // Usage contexts
	Prerequisites []string               `json:"prerequisites"`  // Prerequisites
	Alternatives  []string               `json:"alternatives"`   // Alternative patterns
	Compatibility map[string]string      `json:"compatibility"`  // Compatibility with other patterns
}

// PerformanceInfo represents performance characteristics of a pattern
type PerformanceInfo struct {
	TimeComplexity   string  `json:"time_complexity"`   // Time complexity
	SpaceComplexity  string  `json:"space_complexity"`  // Space complexity
	ScalabilityScore float64 `json:"scalability_score"` // Scalability score
	MemoryUsage      string  `json:"memory_usage"`      // Memory usage characteristics
	CPUUsage         string  `json:"cpu_usage"`         // CPU usage characteristics
}

// PatternMatch represents a match between context and a pattern
type PatternMatch struct {
	PatternID     string  `json:"pattern_id"`     // Pattern identifier
	MatchScore    float64 `json:"match_score"`    // Match score (0-1)
	Confidence    float64 `json:"confidence"`     // Match confidence
	MatchedFields []string `json:"matched_fields"` // Fields that matched
	Explanation   string  `json:"explanation"`    // Match explanation
	Suggestions   []string `json:"suggestions"`   // Improvement suggestions
}

// ValidationResult represents context validation results
type ValidationResult struct {
	Valid           bool               `json:"valid"`            // Whether context is valid
	ConfidenceScore float64            `json:"confidence_score"` // Overall confidence
	QualityScore    float64            `json:"quality_score"`    // Quality assessment
	Issues          []*ValidationIssue `json:"issues"`           // Validation issues
	Suggestions     []*Suggestion      `json:"suggestions"`      // Improvement suggestions
	ValidatedAt     time.Time          `json:"validated_at"`     // When validation occurred
}

// ValidationIssue represents a validation issue
type ValidationIssue struct {
	Type        string  `json:"type"`        // Issue type
	Severity    string  `json:"severity"`    // Issue severity
	Message     string  `json:"message"`     // Issue message
	Field       string  `json:"field"`       // Affected field
	Suggestion  string  `json:"suggestion"`  // Suggested fix
	Impact      float64 `json:"impact"`      // Impact score
}

// Suggestion represents an improvement suggestion
type Suggestion struct {
	Type        string  `json:"type"`        // Suggestion type
	Title       string  `json:"title"`       // Suggestion title
	Description string  `json:"description"` // Detailed description
	Confidence  float64 `json:"confidence"`  // Confidence in suggestion
	Priority    int     `json:"priority"`    // Priority level (1=highest)
	Action      string  `json:"action"`      // Recommended action
	Impact      string  `json:"impact"`      // Expected impact
}

// Recommendation represents an improvement recommendation
type Recommendation struct {
	Type        string            `json:"type"`        // Recommendation type
	Title       string            `json:"title"`       // Recommendation title
	Description string            `json:"description"` // Detailed description
	Priority    int               `json:"priority"`    // Priority level
	Effort      string            `json:"effort"`      // Effort required
	Impact      string            `json:"impact"`      // Expected impact
	Steps       []string          `json:"steps"`       // Implementation steps
	Resources   []string          `json:"resources"`   // Required resources
	Metadata    map[string]interface{} `json:"metadata"` // Additional metadata
}

// RAGResponse represents a response from the RAG system
type RAGResponse struct {
	Query       string            `json:"query"`       // Original query
	Answer      string            `json:"answer"`      // Generated answer
	Sources     []*RAGSource      `json:"sources"`     // Source documents
	Confidence  float64           `json:"confidence"`  // Response confidence
	Context     map[string]interface{} `json:"context"` // Additional context
	ProcessedAt time.Time         `json:"processed_at"` // When processed
}

// RAGSource represents a source document from RAG system
type RAGSource struct {
	ID          string            `json:"id"`          // Source identifier
	Title       string            `json:"title"`       // Source title
	Content     string            `json:"content"`     // Source content excerpt
	Score       float64           `json:"score"`       // Relevance score
	Metadata    map[string]interface{} `json:"metadata"` // Source metadata
	URL         string            `json:"url"`         // Source URL if available
}

// RAGResult represents a result from RAG similarity search
type RAGResult struct {
	ID          string            `json:"id"`          // Result identifier
	Content     string            `json:"content"`     // Content
	Score       float64           `json:"score"`       // Similarity score
	Metadata    map[string]interface{} `json:"metadata"` // Result metadata
	Highlights  []string          `json:"highlights"`  // Content highlights
}

// RAGUpdate represents an update to the RAG index
type RAGUpdate struct {
	ID          string            `json:"id"`          // Document identifier
	Content     string            `json:"content"`     // Document content
	Metadata    map[string]interface{} `json:"metadata"` // Document metadata
	Operation   string            `json:"operation"`   // Operation type (add, update, delete)
}

// RAGStatistics represents RAG system statistics
type RAGStatistics struct {
	TotalDocuments   int64     `json:"total_documents"`   // Total indexed documents
	TotalQueries     int64     `json:"total_queries"`     // Total queries processed
	AverageQueryTime time.Duration `json:"average_query_time"` // Average query time
	IndexSize        int64     `json:"index_size"`        // Index size in bytes
	LastIndexUpdate  time.Time `json:"last_index_update"` // When index was last updated
	ErrorRate        float64   `json:"error_rate"`        // Error rate
}