package slurp

import (
	"time"

	"chorus.services/bzzz/pkg/crypto"
)

// Core data types for the SLURP contextual intelligence system.
// These types define the structure for hierarchical context resolution,
// temporal evolution tracking, and distributed storage operations.

// ContextNode represents a single context entry in the hierarchy.
//
// Context nodes form a tree structure where child nodes inherit and
// override properties from their parents. This enables efficient
// cascading context resolution with bounded depth traversal.
type ContextNode struct {
	// Identity and addressing
	ID           string `json:"id"`                 // Unique identifier
	UCXLAddress  string `json:"ucxl_address"`       // Associated UCXL address
	Path         string `json:"path"`               // Filesystem path
	
	// Core context information
	Summary      string   `json:"summary"`          // Brief description
	Purpose      string   `json:"purpose"`          // What this component does
	Technologies []string `json:"technologies"`     // Technologies used
	Tags         []string `json:"tags"`             // Categorization tags
	Insights     []string `json:"insights"`         // Analytical insights
	
	// Hierarchy relationships
	Parent       *string  `json:"parent,omitempty"` // Parent context ID
	Children     []string `json:"children"`         // Child context IDs
	Specificity  int      `json:"specificity"`      // Specificity level (higher = more specific)
	
	// File metadata
	FileType     string     `json:"file_type"`                  // File extension or type
	Language     *string    `json:"language,omitempty"`         // Programming language
	Size         *int64     `json:"size,omitempty"`             // File size in bytes
	LastModified *time.Time `json:"last_modified,omitempty"`    // Last modification time
	ContentHash  *string    `json:"content_hash,omitempty"`     // Content hash for change detection
	
	// Resolution metadata
	CreatedBy    string    `json:"created_by"`       // Who/what created this context
	CreatedAt    time.Time `json:"created_at"`       // When created
	UpdatedAt    time.Time `json:"updated_at"`       // When last updated
	Confidence   float64   `json:"confidence"`       // Confidence in accuracy (0-1)
	
	// Cascading behavior rules
	AppliesTo    ContextScope `json:"applies_to"`     // Scope of application
	Overrides    bool         `json:"overrides"`      // Whether this overrides parent context
	
	// Security and access control
	EncryptedFor []string             `json:"encrypted_for"`  // Roles that can access
	AccessLevel  crypto.AccessLevel   `json:"access_level"`   // Access level required
	
	// Custom metadata
	Metadata     map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// ResolvedContext represents the final resolved context for a UCXL address.
//
// This is the primary output of the context resolution process, combining
// information from multiple hierarchy levels and applying global contexts.
type ResolvedContext struct {
	// Resolved context data
	UCXLAddress  string   `json:"ucxl_address"`   // Original UCXL address
	Summary      string   `json:"summary"`        // Resolved summary
	Purpose      string   `json:"purpose"`        // Resolved purpose
	Technologies []string `json:"technologies"`   // Merged technologies
	Tags         []string `json:"tags"`           // Merged tags
	Insights     []string `json:"insights"`       // Merged insights
	
	// File information
	FileType     string     `json:"file_type"`                // File type
	Language     *string    `json:"language,omitempty"`       // Programming language
	Size         *int64     `json:"size,omitempty"`           // File size
	LastModified *time.Time `json:"last_modified,omitempty"`  // Last modification
	ContentHash  *string    `json:"content_hash,omitempty"`   // Content hash
	
	// Resolution metadata
	SourcePath       string    `json:"source_path"`        // Primary source context path
	InheritanceChain []string  `json:"inheritance_chain"`  // Context inheritance chain
	Confidence       float64   `json:"confidence"`         // Overall confidence (0-1)
	BoundedDepth     int       `json:"bounded_depth"`      // Actual traversal depth used
	GlobalApplied    bool      `json:"global_applied"`     // Whether global contexts were applied
	ResolvedAt       time.Time `json:"resolved_at"`        // When resolution occurred
	
	// Temporal information
	Version          int       `json:"version"`           // Current version number
	LastUpdated      time.Time `json:"last_updated"`      // When context was last updated
	EvolutionHistory []string  `json:"evolution_history"` // Brief evolution history
	
	// Access control
	AccessibleBy     []string `json:"accessible_by"`     // Roles that can access this
	EncryptionKeys   []string `json:"encryption_keys"`   // Keys used for encryption
	
	// Performance metadata
	ResolutionTime   time.Duration `json:"resolution_time"`   // Time taken to resolve
	CacheHit         bool          `json:"cache_hit"`         // Whether result was cached
	NodesTraversed   int           `json:"nodes_traversed"`   // Number of hierarchy nodes traversed
}

// ContextScope defines the scope of a context node's application
type ContextScope string

const (
	ScopeLocal    ContextScope = "local"    // Only applies to this specific file/directory
	ScopeChildren ContextScope = "children" // Applies to this and all child directories
	ScopeGlobal   ContextScope = "global"   // Applies to the entire project
)

// TemporalNode represents context at a specific decision point in time.
//
// Temporal nodes track how context evolves through different decisions
// and changes, providing decision-hop based analysis rather than
// simple chronological progression.
type TemporalNode struct {
	// Node identity
	ID           string `json:"id"`            // Unique temporal node ID
	UCXLAddress  string `json:"ucxl_address"`  // Associated UCXL address
	Version      int    `json:"version"`       // Version number (monotonic)
	
	// Context snapshot
	Context      ContextNode `json:"context"`   // Context data at this point
	
	// Temporal metadata
	Timestamp    time.Time    `json:"timestamp"`     // When this version was created
	DecisionID   string       `json:"decision_id"`   // Associated decision identifier
	ChangeReason ChangeReason `json:"change_reason"` // Why context changed
	ParentNode   *string      `json:"parent_node,omitempty"` // Previous version ID
	
	// Evolution tracking
	ContextHash  string  `json:"context_hash"` // Hash of context content
	Confidence   float64 `json:"confidence"`   // Confidence in this version (0-1)
	Staleness    float64 `json:"staleness"`    // Staleness indicator (0-1)
	
	// Decision graph relationships
	Influences   []string `json:"influences"`    // UCXL addresses this influences
	InfluencedBy []string `json:"influenced_by"` // UCXL addresses that influence this
	
	// Validation metadata
	ValidatedBy   []string  `json:"validated_by"`   // Who/what validated this
	LastValidated time.Time `json:"last_validated"` // When last validated
	
	// Change impact analysis
	ImpactScope   ImpactScope `json:"impact_scope"`   // Scope of change impact
	PropagatedTo  []string    `json:"propagated_to"`  // Addresses that received impact
	
	// Custom temporal metadata
	Metadata      map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// DecisionMetadata represents metadata about a decision that changed context.
//
// Decisions are the fundamental unit of temporal analysis in SLURP,
// representing why and how context evolved rather than just when.
type DecisionMetadata struct {
	// Decision identity
	ID               string `json:"id"`               // Unique decision identifier
	Maker            string `json:"maker"`            // Who/what made the decision
	Rationale        string `json:"rationale"`        // Why the decision was made
	
	// Impact and scope
	Scope            ImpactScope `json:"scope"`             // Scope of impact
	ConfidenceLevel  float64     `json:"confidence_level"`  // Confidence in decision (0-1)
	
	// External references
	ExternalRefs     []string `json:"external_refs"`       // External references (URLs, docs)
	GitCommit        *string  `json:"git_commit,omitempty"` // Associated git commit
	IssueNumber      *int     `json:"issue_number,omitempty"` // Associated issue number
	PullRequestNumber *int    `json:"pull_request,omitempty"` // Associated PR number
	
	// Timing information
	CreatedAt        time.Time  `json:"created_at"`                // When decision was made
	EffectiveAt      *time.Time `json:"effective_at,omitempty"`   // When decision takes effect
	ExpiresAt        *time.Time `json:"expires_at,omitempty"`     // When decision expires
	
	// Decision quality
	ReviewedBy       []string   `json:"reviewed_by,omitempty"`    // Who reviewed this decision
	ApprovedBy       []string   `json:"approved_by,omitempty"`    // Who approved this decision
	
	// Implementation tracking
	ImplementationStatus string `json:"implementation_status"`     // Status: planned, active, complete, cancelled
	ImplementationNotes  string `json:"implementation_notes"`     // Implementation details
	
	// Custom metadata
	Metadata         map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// ChangeReason represents why context changed
type ChangeReason string

const (
	ReasonInitialCreation    ChangeReason = "initial_creation"    // First time context creation
	ReasonCodeChange         ChangeReason = "code_change"         // Code modification
	ReasonDesignDecision     ChangeReason = "design_decision"     // Design/architecture decision
	ReasonRefactoring        ChangeReason = "refactoring"         // Code refactoring
	ReasonArchitectureChange ChangeReason = "architecture_change" // Major architecture change
	ReasonRequirementsChange ChangeReason = "requirements_change" // Requirements modification
	ReasonLearningEvolution  ChangeReason = "learning_evolution"  // Improved understanding
	ReasonRAGEnhancement     ChangeReason = "rag_enhancement"     // RAG system enhancement
	ReasonTeamInput          ChangeReason = "team_input"          // Team member input
	ReasonBugDiscovery       ChangeReason = "bug_discovery"       // Bug found that changes understanding
	ReasonPerformanceInsight ChangeReason = "performance_insight" // Performance analysis insight
	ReasonSecurityReview     ChangeReason = "security_review"     // Security analysis
	ReasonDependencyChange   ChangeReason = "dependency_change"   // Dependency update
	ReasonEnvironmentChange  ChangeReason = "environment_change"  // Environment configuration change
	ReasonToolingUpdate      ChangeReason = "tooling_update"      // Development tooling update
	ReasonDocumentationUpdate ChangeReason = "documentation_update" // Documentation improvement
)

// ImpactScope represents the scope of a decision's impact
type ImpactScope string

const (
	ImpactLocal   ImpactScope = "local"   // Affects only local context
	ImpactModule  ImpactScope = "module"  // Affects current module
	ImpactProject ImpactScope = "project" // Affects entire project
	ImpactSystem  ImpactScope = "system"  // Affects entire system/ecosystem
)

// DecisionPath represents a path between two decision points in the temporal graph
type DecisionPath struct {
	From       string          `json:"from"`        // Starting UCXL address
	To         string          `json:"to"`          // Ending UCXL address
	Steps      []*DecisionStep `json:"steps"`       // Path steps
	TotalHops  int             `json:"total_hops"`  // Total decision hops
	PathType   string          `json:"path_type"`   // Type of path (direct, influence, etc.)
}

// DecisionStep represents a single step in a decision path
type DecisionStep struct {
	Address      string        `json:"address"`       // UCXL address at this step
	TemporalNode *TemporalNode `json:"temporal_node"` // Temporal node at this step
	HopDistance  int           `json:"hop_distance"`  // Hops from start
	Relationship string        `json:"relationship"`  // Type of relationship to next step
}

// DecisionTimeline represents the decision evolution timeline for a context
type DecisionTimeline struct {
	PrimaryAddress   string                    `json:"primary_address"`   // Main UCXL address
	DecisionSequence []*DecisionTimelineEntry `json:"decision_sequence"` // Ordered by decision hops
	RelatedDecisions []*RelatedDecision       `json:"related_decisions"` // Related decisions within hop limit
	TotalDecisions   int                      `json:"total_decisions"`   // Total decisions in timeline
	TimeSpan         time.Duration            `json:"time_span"`         // Time span from first to last
	AnalysisMetadata *TimelineAnalysis        `json:"analysis_metadata"` // Analysis metadata
}

// DecisionTimelineEntry represents an entry in the decision timeline
type DecisionTimelineEntry struct {
	Version            int              `json:"version"`             // Version number
	DecisionHop        int              `json:"decision_hop"`        // Decision distance from initial
	ChangeReason       ChangeReason     `json:"change_reason"`       // Why it changed
	DecisionMaker      string           `json:"decision_maker"`      // Who made the decision
	DecisionRationale  string           `json:"decision_rationale"`  // Rationale for decision
	ConfidenceEvolution float64         `json:"confidence_evolution"` // Confidence at this point
	Timestamp          time.Time        `json:"timestamp"`           // When decision occurred
	InfluencesCount    int              `json:"influences_count"`    // Number of influenced addresses
	InfluencedByCount  int              `json:"influenced_by_count"` // Number of influencing addresses
	ImpactScope        ImpactScope      `json:"impact_scope"`        // Scope of this decision
	Metadata           map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// RelatedDecision represents a decision related through the influence graph
type RelatedDecision struct {
	Address        string        `json:"address"`         // UCXL address
	DecisionHops   int           `json:"decision_hops"`   // Hops from primary address
	LatestVersion  int           `json:"latest_version"`  // Latest version number
	ChangeReason   ChangeReason  `json:"change_reason"`   // Latest change reason
	DecisionMaker  string        `json:"decision_maker"`  // Latest decision maker
	Confidence     float64       `json:"confidence"`      // Current confidence
	LastDecisionTimestamp time.Time `json:"last_decision_timestamp"` // When last decision occurred
	RelationshipType string       `json:"relationship_type"` // Type of relationship (influences, influenced_by)
}

// TimelineAnalysis contains analysis metadata for decision timelines
type TimelineAnalysis struct {
	ChangeVelocity        float64               `json:"change_velocity"`        // Changes per unit time
	ConfidenceTrend       string                `json:"confidence_trend"`       // increasing, decreasing, stable
	DominantChangeReasons []ChangeReason       `json:"dominant_change_reasons"` // Most common reasons
	DecisionMakers        map[string]int        `json:"decision_makers"`        // Decision maker frequency
	ImpactScopeDistribution map[ImpactScope]int `json:"impact_scope_distribution"` // Distribution of impact scopes
	InfluenceNetworkSize  int                  `json:"influence_network_size"`  // Size of influence network
	AnalyzedAt            time.Time            `json:"analyzed_at"`            // When analysis was performed
}

// NavigationDirection represents direction for temporal navigation
type NavigationDirection string

const (
	NavigationForward  NavigationDirection = "forward"  // Toward newer decisions
	NavigationBackward NavigationDirection = "backward" // Toward older decisions
)

// StaleContext represents a potentially outdated context
type StaleContext struct {
	UCXLAddress    string    `json:"ucxl_address"`    // Address of stale context
	TemporalNode   *TemporalNode `json:"temporal_node"`   // Latest temporal node
	StalenessScore float64   `json:"staleness_score"` // Staleness score (0-1)
	LastUpdated    time.Time `json:"last_updated"`    // When last updated
	Reasons        []string  `json:"reasons"`         // Reasons why considered stale
	SuggestedActions []string `json:"suggested_actions"` // Suggested remediation actions
}

// GenerationOptions configures context generation behavior
type GenerationOptions struct {
	// Analysis options
	AnalyzeContent    bool     `json:"analyze_content"`    // Analyze file content
	AnalyzeStructure  bool     `json:"analyze_structure"`  // Analyze directory structure
	AnalyzeHistory    bool     `json:"analyze_history"`    // Analyze git history
	AnalyzeDependencies bool   `json:"analyze_dependencies"` // Analyze dependencies
	
	// Generation scope
	MaxDepth          int      `json:"max_depth"`          // Maximum directory depth
	IncludePatterns   []string `json:"include_patterns"`   // File patterns to include
	ExcludePatterns   []string `json:"exclude_patterns"`   // File patterns to exclude
	
	// Quality settings
	MinConfidence     float64  `json:"min_confidence"`     // Minimum confidence threshold
	RequireValidation bool     `json:"require_validation"` // Require human validation
	
	// External integration
	UseRAG            bool     `json:"use_rag"`            // Use RAG for enhancement
	RAGEndpoint       string   `json:"rag_endpoint"`       // RAG service endpoint
	
	// Output options
	EncryptForRoles   []string `json:"encrypt_for_roles"`  // Roles to encrypt for
	
	// Performance limits
	Timeout           time.Duration `json:"timeout"`        // Generation timeout
	MaxFileSize       int64    `json:"max_file_size"`      // Maximum file size to analyze
	
	// Custom options
	CustomOptions     map[string]interface{} `json:"custom_options,omitempty"` // Additional options
}

// HierarchyStats represents statistics about hierarchy generation
type HierarchyStats struct {
	NodesCreated      int           `json:"nodes_created"`      // Number of nodes created
	NodesUpdated      int           `json:"nodes_updated"`      // Number of nodes updated
	FilesAnalyzed     int           `json:"files_analyzed"`     // Number of files analyzed
	DirectoriesScanned int          `json:"directories_scanned"` // Number of directories scanned
	GenerationTime    time.Duration `json:"generation_time"`    // Time taken for generation
	AverageConfidence float64       `json:"average_confidence"` // Average confidence score
	TotalSize         int64         `json:"total_size"`         // Total size of analyzed content
	SkippedFiles      int           `json:"skipped_files"`      // Number of files skipped
	Errors            []string      `json:"errors"`             // Generation errors
}

// ValidationResult represents the result of context validation
type ValidationResult struct {
	Valid             bool              `json:"valid"`              // Whether context is valid
	ConfidenceScore   float64           `json:"confidence_score"`   // Overall confidence (0-1)
	QualityScore      float64           `json:"quality_score"`      // Quality assessment (0-1)
	Issues            []*ValidationIssue `json:"issues"`            // Validation issues found
	Suggestions       []*ValidationSuggestion `json:"suggestions"` // Improvement suggestions
	ValidatedAt       time.Time         `json:"validated_at"`      // When validation occurred
	ValidatedBy       string            `json:"validated_by"`      // Who/what performed validation
}

// ValidationIssue represents an issue found during validation
type ValidationIssue struct {
	Severity    string `json:"severity"`    // error, warning, info
	Message     string `json:"message"`     // Issue description
	Field       string `json:"field"`       // Affected field
	Suggestion  string `json:"suggestion"`  // How to fix
	
}

// ValidationSuggestion represents a suggestion for context improvement
type ValidationSuggestion struct {
	Type        string  `json:"type"`        // Type of suggestion
	Description string  `json:"description"` // Suggestion description
	Confidence  float64 `json:"confidence"`  // Confidence in suggestion (0-1)
	Priority    int     `json:"priority"`    // Priority (1=high, 3=low)
}

// CostEstimate represents estimated resource cost for operations
type CostEstimate struct {
	CPUCost       float64       `json:"cpu_cost"`       // Estimated CPU cost
	MemoryCost    float64       `json:"memory_cost"`    // Estimated memory cost
	StorageCost   float64       `json:"storage_cost"`   // Estimated storage cost
	TimeCost      time.Duration `json:"time_cost"`      // Estimated time cost
	TotalCost     float64       `json:"total_cost"`     // Total normalized cost
	CostBreakdown map[string]float64 `json:"cost_breakdown"` // Detailed cost breakdown
}

// AnalysisResult represents the result of context analysis
type AnalysisResult struct {
	QualityScore      float64             `json:"quality_score"`      // Overall quality (0-1)
	ConsistencyScore  float64             `json:"consistency_score"`  // Consistency with hierarchy
	CompletenessScore float64             `json:"completeness_score"` // Completeness assessment
	AccuracyScore     float64             `json:"accuracy_score"`     // Accuracy assessment
	Issues            []*AnalysisIssue    `json:"issues"`             // Issues found
	Strengths         []string            `json:"strengths"`          // Context strengths
	Improvements      []*Suggestion       `json:"improvements"`       // Improvement suggestions
	AnalyzedAt        time.Time           `json:"analyzed_at"`        // When analysis occurred
}

// AnalysisIssue represents an issue found during analysis
type AnalysisIssue struct {
	Type        string  `json:"type"`        // Type of issue
	Severity    string  `json:"severity"`    // Severity level
	Description string  `json:"description"` // Issue description
	Field       string  `json:"field"`       // Affected field
	Impact      float64 `json:"impact"`      // Impact score (0-1)
}

// Suggestion represents a suggestion for improvement
type Suggestion struct {
	Type        string  `json:"type"`        // Type of suggestion
	Description string  `json:"description"` // Suggestion description
	Confidence  float64 `json:"confidence"`  // Confidence in suggestion
	Priority    int     `json:"priority"`    // Priority level
	Action      string  `json:"action"`      // Recommended action
}

// Pattern represents a detected context pattern
type Pattern struct {
	ID           string    `json:"id"`           // Pattern identifier
	Name         string    `json:"name"`         // Pattern name
	Description  string    `json:"description"`  // Pattern description
	MatchCriteria map[string]interface{} `json:"match_criteria"` // Criteria for matching
	Confidence   float64   `json:"confidence"`   // Pattern confidence (0-1)
	Frequency    int       `json:"frequency"`    // How often pattern appears
	Examples     []string  `json:"examples"`     // Example contexts that match
	CreatedAt    time.Time `json:"created_at"`   // When pattern was detected
}

// PatternMatch represents a match between context and pattern
type PatternMatch struct {
	PatternID    string  `json:"pattern_id"`    // ID of matched pattern
	MatchScore   float64 `json:"match_score"`   // How well it matches (0-1)
	MatchedFields []string `json:"matched_fields"` // Which fields matched
	Confidence   float64 `json:"confidence"`    // Confidence in match
}

// ContextPattern represents a registered context pattern template
type ContextPattern struct {
	ID           string    `json:"id"`           // Pattern identifier
	Name         string    `json:"name"`         // Human-readable name
	Description  string    `json:"description"`  // Pattern description
	Template     *ContextNode `json:"template"`  // Template for matching
	Criteria     map[string]interface{} `json:"criteria"` // Matching criteria
	Priority     int       `json:"priority"`     // Pattern priority
	CreatedBy    string    `json:"created_by"`   // Who created pattern
	CreatedAt    time.Time `json:"created_at"`   // When created
	UpdatedAt    time.Time `json:"updated_at"`   // When last updated
	UsageCount   int       `json:"usage_count"`  // How often used
}

// Inconsistency represents a detected inconsistency in the context hierarchy
type Inconsistency struct {
	Type        string    `json:"type"`        // Type of inconsistency
	Description string    `json:"description"` // Description of the issue
	AffectedNodes []string `json:"affected_nodes"` // Nodes involved
	Severity    string    `json:"severity"`    // Severity level
	Suggestion  string    `json:"suggestion"`  // How to resolve
	DetectedAt  time.Time `json:"detected_at"` // When detected
}

// SearchQuery represents a context search query
type SearchQuery struct {
	// Query terms
	Query          string   `json:"query"`           // Main search query
	Tags           []string `json:"tags"`            // Required tags
	Technologies   []string `json:"technologies"`    // Required technologies
	FileTypes      []string `json:"file_types"`      // File types to include
	
	// Filters
	MinConfidence  float64  `json:"min_confidence"`  // Minimum confidence
	MaxAge         *time.Duration `json:"max_age"`   // Maximum age
	Roles          []string `json:"roles"`           // Required access roles
	
	// Scope
	Scope          []string `json:"scope"`           // Paths to search within
	ExcludeScope   []string `json:"exclude_scope"`   // Paths to exclude
	
	// Result options
	Limit          int      `json:"limit"`           // Maximum results
	Offset         int      `json:"offset"`          // Result offset
	SortBy         string   `json:"sort_by"`         // Sort field
	SortOrder      string   `json:"sort_order"`      // asc, desc
	
	// Advanced options
	FuzzyMatch     bool     `json:"fuzzy_match"`     // Enable fuzzy matching
	IncludeStale   bool     `json:"include_stale"`   // Include stale contexts
	TemporalFilter *TemporalFilter `json:"temporal_filter"` // Temporal filtering
}

// TemporalFilter represents temporal filtering options
type TemporalFilter struct {
	FromTime       *time.Time `json:"from_time"`       // Start time
	ToTime         *time.Time `json:"to_time"`         // End time
	VersionRange   *VersionRange `json:"version_range"` // Version range
	ChangeReasons  []ChangeReason `json:"change_reasons"` // Specific change reasons
	DecisionMakers []string   `json:"decision_makers"` // Specific decision makers
	MinDecisionHops int       `json:"min_decision_hops"` // Minimum decision hops
	MaxDecisionHops int       `json:"max_decision_hops"` // Maximum decision hops
}

// VersionRange represents a range of versions
type VersionRange struct {
	MinVersion int `json:"min_version"` // Minimum version (inclusive)
	MaxVersion int `json:"max_version"` // Maximum version (inclusive)
}

// SearchResult represents a single search result
type SearchResult struct {
	Context       *ResolvedContext `json:"context"`        // Resolved context
	TemporalNode  *TemporalNode   `json:"temporal_node"`   // Associated temporal node
	MatchScore    float64         `json:"match_score"`     // How well it matches query (0-1)
	MatchedFields []string        `json:"matched_fields"`  // Which fields matched
	Snippet       string          `json:"snippet"`         // Text snippet showing match
	Rank          int             `json:"rank"`            // Result rank
}

// IndexMetadata represents metadata for context indexing
type IndexMetadata struct {
	IndexType     string            `json:"index_type"`     // Type of index
	IndexedFields []string          `json:"indexed_fields"` // Fields that are indexed
	IndexedAt     time.Time         `json:"indexed_at"`     // When indexed
	IndexVersion  string            `json:"index_version"`  // Index version
	Metadata      map[string]interface{} `json:"metadata"` // Additional metadata
}

// DecisionAnalysis represents analysis of decision patterns
type DecisionAnalysis struct {
	TotalDecisions        int                      `json:"total_decisions"`         // Total decisions analyzed
	DecisionMakers        map[string]int           `json:"decision_makers"`         // Decision maker frequency
	ChangeReasons         map[ChangeReason]int     `json:"change_reasons"`          // Change reason frequency
	ImpactScopes          map[ImpactScope]int      `json:"impact_scopes"`           // Impact scope distribution
	ConfidenceTrends      map[string]float64       `json:"confidence_trends"`       // Confidence trends over time
	DecisionFrequency     map[string]int           `json:"decision_frequency"`      // Decisions per time period
	InfluenceNetworkStats *InfluenceNetworkStats   `json:"influence_network_stats"` // Network statistics
	Patterns              []*DecisionPattern       `json:"patterns"`                // Detected decision patterns
	AnalyzedAt            time.Time                `json:"analyzed_at"`             // When analysis was performed
	AnalysisTimeSpan      time.Duration            `json:"analysis_time_span"`      // Time span analyzed
}

// InfluenceNetworkStats represents statistics about the influence network
type InfluenceNetworkStats struct {
	TotalNodes        int     `json:"total_nodes"`         // Total nodes in network
	TotalEdges        int     `json:"total_edges"`         // Total influence relationships
	AverageConnections float64 `json:"average_connections"` // Average connections per node
	MaxConnections    int     `json:"max_connections"`     // Maximum connections for any node
	NetworkDensity    float64 `json:"network_density"`     // Network density (0-1)
	ClusteringCoeff   float64 `json:"clustering_coeff"`    // Clustering coefficient
	MaxPathLength     int     `json:"max_path_length"`     // Maximum path length in network
	CentralNodes      []string `json:"central_nodes"`      // Most central nodes
}

// DecisionPattern represents a detected pattern in decision-making
type DecisionPattern struct {
	ID              string        `json:"id"`               // Pattern identifier
	Name            string        `json:"name"`             // Pattern name
	Description     string        `json:"description"`      // Pattern description
	Frequency       int           `json:"frequency"`        // How often this pattern occurs
	Confidence      float64       `json:"confidence"`       // Confidence in pattern (0-1)
	ExampleDecisions []string     `json:"example_decisions"` // Example decisions that match
	Characteristics  map[string]interface{} `json:"characteristics"` // Pattern characteristics
	DetectedAt      time.Time     `json:"detected_at"`      // When pattern was detected
}

// ResolverStatistics represents statistics about context resolution operations
type ResolverStatistics struct {
	TotalResolutions      int64         `json:"total_resolutions"`       // Total resolution attempts
	SuccessfulResolutions int64         `json:"successful_resolutions"`  // Successful resolutions
	FailedResolutions     int64         `json:"failed_resolutions"`      // Failed resolutions
	AverageResolutionTime time.Duration `json:"average_resolution_time"` // Average time per resolution
	CacheHitRate          float64       `json:"cache_hit_rate"`          // Cache hit rate (0-1)
	AverageDepthTraversed float64       `json:"average_depth_traversed"` // Average hierarchy depth
	MaxDepthTraversed     int           `json:"max_depth_traversed"`     // Maximum depth ever traversed
	UniqueAddresses       int64         `json:"unique_addresses"`        // Unique addresses resolved
	CurrentCacheSize      int64         `json:"current_cache_size"`      // Current cache size
	MaxCacheSize          int64         `json:"max_cache_size"`          // Maximum cache size
	CacheEvictions        int64         `json:"cache_evictions"`         // Number of cache evictions
	LastResetAt           time.Time     `json:"last_reset_at"`           // When statistics were last reset
}