package temporal

import (
	"time"

	"chorus.services/bzzz/pkg/ucxl"
	slurpContext "chorus.services/bzzz/pkg/slurp/context"
)

// ChangeReason represents why a context changed at a decision point
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
)

// 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  ucxl.Address `json:"ucxl_address"`  // Associated UCXL address
	Version      int          `json:"version"`       // Version number (monotonic)
	
	// Context snapshot
	Context      *slurpContext.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   []ucxl.Address `json:"influences"`    // UCXL addresses this influences
	InfluencedBy []ucxl.Address `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  []ucxl.Address `json:"propagated_to"`  // Addresses that received impact
	
	// Custom temporal metadata
	Metadata      map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// DecisionMetadata captures information 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
}

// DecisionPath represents a path between two decision points in the temporal graph
type DecisionPath struct {
	From       ucxl.Address      `json:"from"`        // Starting UCXL address
	To         ucxl.Address      `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      ucxl.Address   `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   ucxl.Address              `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        ucxl.Address  `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
}

// StaleContext represents a potentially outdated context
type StaleContext struct {
	UCXLAddress    ucxl.Address   `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
	RelatedChanges []ucxl.Address `json:"related_changes"` // Related contexts that changed
	Priority       StalePriority  `json:"priority"`        // Priority for refresh
}

// StalePriority represents priority levels for stale context refresh
type StalePriority string

const (
	PriorityLow      StalePriority = "low"      // Low priority
	PriorityMedium   StalePriority = "medium"   // Medium priority
	PriorityHigh     StalePriority = "high"     // High priority
	PriorityCritical StalePriority = "critical" // Critical priority
)

// InfluenceNetworkAnalysis represents analysis of the decision influence network
type InfluenceNetworkAnalysis struct {
	TotalNodes        int                    `json:"total_nodes"`         // Total nodes in network
	TotalEdges        int                    `json:"total_edges"`         // Total influence relationships
	NetworkDensity    float64                `json:"network_density"`     // Network density (0-1)
	ClusteringCoeff   float64                `json:"clustering_coeff"`    // Clustering coefficient
	AveragePathLength float64                `json:"average_path_length"` // Average path length
	CentralNodes      []CentralNode          `json:"central_nodes"`       // Most central nodes
	Communities       []Community            `json:"communities"`         // Detected communities
	AnalyzedAt        time.Time              `json:"analyzed_at"`         // When analysis was performed
}

// CentralNode represents a central node in the influence network
type CentralNode struct {
	Address           ucxl.Address `json:"address"`            // Node address
	BetweennessCentrality float64  `json:"betweenness_centrality"` // Betweenness centrality
	ClosenessCentrality   float64  `json:"closeness_centrality"`   // Closeness centrality
	DegreeCentrality      float64  `json:"degree_centrality"`      // Degree centrality
	PageRank              float64  `json:"page_rank"`              // PageRank score
	InfluenceScore        float64  `json:"influence_score"`        // Overall influence score
}

// Community represents a community in the influence network
type Community struct {
	ID            string         `json:"id"`             // Community ID
	Nodes         []ucxl.Address `json:"nodes"`          // Nodes in community
	Modularity    float64        `json:"modularity"`     // Community modularity
	Density       float64        `json:"density"`        // Community density
	Description   string         `json:"description"`    // Community description
	Tags          []string       `json:"tags"`           // Community tags
}

// InfluentialDecision represents a highly influential decision
type InfluentialDecision struct {
	Address           ucxl.Address      `json:"address"`            // Decision address
	DecisionHop       int               `json:"decision_hop"`       // Decision hop number
	InfluenceScore    float64           `json:"influence_score"`    // Influence score
	AffectedContexts  []ucxl.Address    `json:"affected_contexts"`  // Contexts affected
	DecisionMetadata  *DecisionMetadata `json:"decision_metadata"`  // Decision details
	ImpactAnalysis    *DecisionImpact   `json:"impact_analysis"`    // Impact analysis
	InfluenceReasons  []string          `json:"influence_reasons"`  // Why influential
}

// DecisionImpact represents analysis of a decision's impact
type DecisionImpact struct {
	Address           ucxl.Address      `json:"address"`            // Decision address
	DecisionHop       int               `json:"decision_hop"`       // Decision hop number
	DirectImpact      []ucxl.Address    `json:"direct_impact"`      // Direct impact
	IndirectImpact    []ucxl.Address    `json:"indirect_impact"`    // Indirect impact
	ImpactRadius      int               `json:"impact_radius"`      // Radius of impact
	ImpactStrength    float64           `json:"impact_strength"`    // Strength of impact
	PropagationTime   time.Duration     `json:"propagation_time"`   // Time for impact propagation
	ImpactCategories  []string          `json:"impact_categories"`  // Categories of impact
	MitigationActions []string          `json:"mitigation_actions"` // Suggested mitigation actions
}

// PredictedInfluence represents a predicted influence relationship
type PredictedInfluence struct {
	From           ucxl.Address `json:"from"`            // Source address
	To             ucxl.Address `json:"to"`              // Target address
	Probability    float64      `json:"probability"`     // Prediction probability
	Strength       float64      `json:"strength"`        // Predicted strength
	Reasons        []string     `json:"reasons"`         // Reasons for prediction
	Confidence     float64      `json:"confidence"`      // Prediction confidence
	EstimatedDelay time.Duration `json:"estimated_delay"` // Estimated delay
}

// CentralityMetrics represents centrality metrics for the influence network
type CentralityMetrics struct {
	BetweennessCentrality map[string]float64 `json:"betweenness_centrality"` // Betweenness centrality by address
	ClosenessCentrality   map[string]float64 `json:"closeness_centrality"`   // Closeness centrality by address
	DegreeCentrality      map[string]float64 `json:"degree_centrality"`      // Degree centrality by address
	EigenvectorCentrality map[string]float64 `json:"eigenvector_centrality"` // Eigenvector centrality by address
	PageRank              map[string]float64 `json:"page_rank"`              // PageRank by address
	CalculatedAt          time.Time          `json:"calculated_at"`          // When calculated
}

// Additional supporting types for temporal graph operations

// DecisionAnalysis represents comprehensive analysis of decision patterns
type DecisionAnalysis struct {
	TimeRange                time.Duration             `json:"time_range"`                 // Analysis time range
	TotalDecisions           int                       `json:"total_decisions"`            // Total decisions analyzed
	DecisionVelocity         float64                   `json:"decision_velocity"`          // Decisions per unit time
	InfluenceNetworkSize     int                       `json:"influence_network_size"`     // Size of influence network
	AverageInfluenceDistance float64                   `json:"average_influence_distance"` // Average decision hop distance
	MostInfluentialDecisions []*InfluentialDecision    `json:"most_influential_decisions"` // Top influential decisions
	DecisionClusters         []*DecisionCluster        `json:"decision_clusters"`          // Decision clusters
	Patterns                 []*DecisionPattern        `json:"patterns"`                   // Identified patterns
	Anomalies                []*AnomalousDecision      `json:"anomalies"`                  // Anomalous decisions
	AnalyzedAt               time.Time                 `json:"analyzed_at"`                // When analysis was performed
}

// DecisionCluster represents a cluster of related decisions
type DecisionCluster struct {
	ID                string         `json:"id"`                 // Cluster ID
	Decisions         []ucxl.Address `json:"decisions"`          // Decisions in cluster
	CentralDecision   ucxl.Address   `json:"central_decision"`   // Most central decision
	ClusterSize       int            `json:"cluster_size"`       // Number of decisions
	Cohesion          float64        `json:"cohesion"`           // Cluster cohesion score
	Theme             string         `json:"theme"`              // Cluster theme/category
	TimeSpan          time.Duration  `json:"time_span"`          // Time span of cluster
	ImpactRadius      int            `json:"impact_radius"`      // Radius of cluster impact
}

// DecisionPattern represents a pattern in decision-making
type DecisionPattern struct {
	ID               string            `json:"id"`                // Pattern ID
	Name             string            `json:"name"`              // Pattern name
	Description      string            `json:"description"`       // Pattern description
	Type             PatternType       `json:"type"`              // Type of pattern
	Confidence       float64           `json:"confidence"`        // Pattern confidence (0-1)
	Frequency        int               `json:"frequency"`         // How often pattern occurs
	Examples         []ucxl.Address    `json:"examples"`          // Example decisions
	Triggers         []string          `json:"triggers"`          // Pattern triggers
	Predictiveness   float64           `json:"predictiveness"`    // How well pattern predicts outcomes
	Metadata         map[string]interface{} `json:"metadata"`      // Additional metadata
}

// PatternType represents types of decision patterns
type PatternType string

const (
	PatternSequential PatternType = "sequential" // Sequential decision patterns
	PatternCyclical   PatternType = "cyclical"   // Cyclical decision patterns
	PatternCascading  PatternType = "cascading"  // Cascading decision patterns
	PatternParallel   PatternType = "parallel"   // Parallel decision patterns
	PatternConditional PatternType = "conditional" // Conditional decision patterns
)

// EvolutionPattern represents a pattern in context evolution
type EvolutionPattern struct {
	ID               string            `json:"id"`                // Pattern ID
	Name             string            `json:"name"`              // Pattern name
	Description      string            `json:"description"`       // Pattern description
	Type             EvolutionType     `json:"type"`              // Type of evolution
	Confidence       float64           `json:"confidence"`        // Pattern confidence (0-1)
	Contexts         []ucxl.Address    `json:"contexts"`          // Contexts exhibiting pattern
	EvolutionStages  []string          `json:"evolution_stages"`  // Stages of evolution
	TriggerEvents    []string          `json:"trigger_events"`    // Events that trigger evolution
	Predictability   float64           `json:"predictability"`    // How predictable the pattern is
	Metadata         map[string]interface{} `json:"metadata"`      // Additional metadata
}

// EvolutionType represents types of context evolution
type EvolutionType string

const (
	EvolutionIncremental EvolutionType = "incremental" // Gradual incremental changes
	EvolutionRevolutionary EvolutionType = "revolutionary" // Major revolutionary changes
	EvolutionOscillating EvolutionType = "oscillating" // Back-and-forth changes
	EvolutionConverging  EvolutionType = "converging"  // Converging to stable state
	EvolutionDiverging   EvolutionType = "diverging"   // Diverging from original state
)

// AnomalousDecision represents an unusual decision pattern
type AnomalousDecision struct {
	Address          ucxl.Address      `json:"address"`           // Decision address
	DecisionHop      int               `json:"decision_hop"`      // Decision hop number
	AnomalyType      AnomalyType       `json:"anomaly_type"`      // Type of anomaly
	AnomalyScore     float64           `json:"anomaly_score"`     // Anomaly score (0-1)
	Description      string            `json:"description"`       // Anomaly description
	ExpectedPattern  string            `json:"expected_pattern"`  // Expected pattern
	ActualPattern    string            `json:"actual_pattern"`    // Actual pattern observed
	ImpactAssessment *DecisionImpact   `json:"impact_assessment"` // Impact assessment
	Recommendations  []string          `json:"recommendations"`   // Recommendations
	DetectedAt       time.Time         `json:"detected_at"`       // When anomaly was detected
}

// AnomalyType represents types of decision anomalies
type AnomalyType string

const (
	AnomalyUnexpectedTiming    AnomalyType = "unexpected_timing"    // Decision at unexpected time
	AnomalyUnexpectedInfluence AnomalyType = "unexpected_influence" // Unexpected influence pattern
	AnomalyIsolatedDecision    AnomalyType = "isolated_decision"    // Decision without typical connections
	AnomalyRapidChanges        AnomalyType = "rapid_changes"        // Unusually rapid sequence of changes
	AnomalyInconsistentReason  AnomalyType = "inconsistent_reason"  // Reason inconsistent with pattern
)

// DecisionPrediction represents a prediction of future decisions
type DecisionPrediction struct {
	Address          ucxl.Address      `json:"address"`           // Predicted decision address
	PredictedReason  ChangeReason      `json:"predicted_reason"`  // Predicted change reason
	Probability      float64           `json:"probability"`       // Prediction probability (0-1)
	Confidence       float64           `json:"confidence"`        // Prediction confidence (0-1)
	TimeWindow       time.Duration     `json:"time_window"`       // Predicted time window
	TriggerEvents    []string          `json:"trigger_events"`    // Events that would trigger
	InfluencingFactors []string        `json:"influencing_factors"` // Factors influencing prediction
	RiskFactors      []string          `json:"risk_factors"`      // Risk factors
	MitigationSteps  []string          `json:"mitigation_steps"`  // Recommended mitigation
	PredictedAt      time.Time         `json:"predicted_at"`      // When prediction was made
}

// LearningResult represents results from pattern learning
type LearningResult struct {
	TimeRange        time.Duration     `json:"time_range"`         // Learning time range
	PatternsLearned  int               `json:"patterns_learned"`   // Number of patterns learned
	NewPatterns      []*DecisionPattern `json:"new_patterns"`       // Newly discovered patterns
	UpdatedPatterns  []*DecisionPattern `json:"updated_patterns"`   // Updated existing patterns
	ConfidenceImprovement float64       `json:"confidence_improvement"` // Overall confidence improvement
	PredictionAccuracy float64          `json:"prediction_accuracy"` // Prediction accuracy improvement
	LearningMetrics  *LearningMetrics  `json:"learning_metrics"`   // Detailed learning metrics
	LearnedAt        time.Time         `json:"learned_at"`         // When learning occurred
}

// LearningMetrics represents detailed learning metrics
type LearningMetrics struct {
	DataPointsAnalyzed   int                    `json:"data_points_analyzed"`   // Number of data points
	FeatureImportance    map[string]float64     `json:"feature_importance"`     // Feature importance scores
	AccuracyMetrics      map[string]float64     `json:"accuracy_metrics"`       // Various accuracy metrics
	LearningCurve        []float64              `json:"learning_curve"`         // Learning curve data
	CrossValidationScore float64                `json:"cross_validation_score"` // Cross-validation score
	OverfittingRisk      float64                `json:"overfitting_risk"`       // Risk of overfitting
}

// PatternStatistics represents pattern analysis statistics
type PatternStatistics struct {
	TotalPatterns        int                    `json:"total_patterns"`         // Total patterns identified
	PatternsByType       map[PatternType]int    `json:"patterns_by_type"`       // Patterns by type
	AverageConfidence    float64                `json:"average_confidence"`     // Average pattern confidence
	MostFrequentPatterns []*DecisionPattern     `json:"most_frequent_patterns"` // Most frequent patterns
	RecentPatterns       []*DecisionPattern     `json:"recent_patterns"`        // Recently discovered patterns
	PatternStability     float64                `json:"pattern_stability"`      // How stable patterns are
	PredictionAccuracy   float64                `json:"prediction_accuracy"`    // Overall prediction accuracy
	LastAnalysisAt       time.Time              `json:"last_analysis_at"`       // When last analyzed
}

// VersionInfo represents information about a temporal version
type VersionInfo struct {
	Address      ucxl.Address      `json:"address"`       // Context address
	Version      int               `json:"version"`       // Version number
	CreatedAt    time.Time         `json:"created_at"`    // When version was created
	Creator      string            `json:"creator"`       // Who created the version
	ChangeReason ChangeReason      `json:"change_reason"` // Reason for change
	DecisionID   string            `json:"decision_id"`   // Associated decision ID
	Size         int64             `json:"size"`          // Version data size
	Tags         []string          `json:"tags"`          // Version tags
	Checksum     string            `json:"checksum"`      // Version checksum
}

// VersionComparison represents comparison between two versions
type VersionComparison struct {
	Address     ucxl.Address      `json:"address"`      // Context address
	Version1    int               `json:"version1"`     // First version
	Version2    int               `json:"version2"`     // Second version
	Differences []*VersionDiff    `json:"differences"`  // Differences found
	Similarity  float64           `json:"similarity"`   // Similarity score (0-1)
	ChangedFields []string        `json:"changed_fields"` // Fields that changed
	ComparedAt  time.Time         `json:"compared_at"`  // When comparison was done
}

// VersionDiff represents a difference between versions
type VersionDiff struct {
	Field     string      `json:"field"`      // Field that changed
	OldValue  interface{} `json:"old_value"`  // Old value
	NewValue  interface{} `json:"new_value"`  // New value
	ChangeType string     `json:"change_type"` // Type of change (added, removed, modified)
}

// ContextHistory represents complete history for a context
type ContextHistory struct {
	Address         ucxl.Address       `json:"address"`          // Context address
	Versions        []*TemporalNode    `json:"versions"`         // All versions
	DecisionTimeline *DecisionTimeline `json:"decision_timeline"` // Decision timeline
	EvolutionSummary *EvolutionSummary `json:"evolution_summary"` // Evolution summary
	GeneratedAt     time.Time          `json:"generated_at"`     // When history was generated
}

// EvolutionSummary represents summary of context evolution
type EvolutionSummary struct {
	TotalVersions      int                       `json:"total_versions"`       // Total number of versions
	TotalDecisions     int                       `json:"total_decisions"`      // Total decisions
	EvolutionTimespan  time.Duration             `json:"evolution_timespan"`   // Total evolution time
	MajorChanges       []*MajorChange            `json:"major_changes"`        // Major changes
	ChangeFrequency    float64                   `json:"change_frequency"`     // Changes per unit time
	StabilityPeriods   []*StabilityPeriod        `json:"stability_periods"`    // Periods of stability
	EvolutionPatterns  []*EvolutionPattern       `json:"evolution_patterns"`   // Identified evolution patterns
	QualityTrend       string                    `json:"quality_trend"`        // improving, declining, stable
	ConfidenceTrend    string                    `json:"confidence_trend"`     // improving, declining, stable
}

// MajorChange represents a significant change in context evolution
type MajorChange struct {
	Version         int               `json:"version"`          // Version where change occurred
	ChangeReason    ChangeReason      `json:"change_reason"`    // Reason for change
	ImpactScore     float64           `json:"impact_score"`     // Impact score (0-1)
	Description     string            `json:"description"`      // Change description
	AffectedAreas   []string          `json:"affected_areas"`   // Areas affected by change
	DecisionMaker   string            `json:"decision_maker"`   // Who made the decision
	Timestamp       time.Time         `json:"timestamp"`        // When change occurred
}

// StabilityPeriod represents a period of context stability
type StabilityPeriod struct {
	StartVersion    int           `json:"start_version"`     // Starting version
	EndVersion      int           `json:"end_version"`       // Ending version
	Duration        time.Duration `json:"duration"`          // Duration of stability
	StabilityScore  float64       `json:"stability_score"`   // Stability score (0-1)
	MinorChanges    int           `json:"minor_changes"`     // Number of minor changes
	Description     string        `json:"description"`       // Period description
}

// HistorySearchCriteria represents criteria for searching history
type HistorySearchCriteria struct {
	Addresses       []ucxl.Address    `json:"addresses"`        // Specific addresses to search
	ChangeReasons   []ChangeReason    `json:"change_reasons"`   // Change reasons to filter by
	DecisionMakers  []string          `json:"decision_makers"`  // Decision makers to filter by
	TimeRange       *TimeRange        `json:"time_range"`       // Time range to search
	HopRange        *HopRange         `json:"hop_range"`        // Decision hop range
	MinConfidence   float64           `json:"min_confidence"`   // Minimum confidence threshold
	Tags            []string          `json:"tags"`             // Tags to filter by
	TextQuery       string            `json:"text_query"`       // Free text query
	IncludeMetadata bool              `json:"include_metadata"` // Whether to include metadata
	Limit           int               `json:"limit"`            // Maximum results to return
	Offset          int               `json:"offset"`           // Results offset for pagination
}

// TimeRange represents a time range filter
type TimeRange struct {
	Start time.Time `json:"start"` // Start time
	End   time.Time `json:"end"`   // End time
}

// HopRange represents a decision hop range filter
type HopRange struct {
	Min int `json:"min"` // Minimum hop number
	Max int `json:"max"` // Maximum hop number
}

// HistoryMatch represents a match from history search
type HistoryMatch struct {
	Address      ucxl.Address      `json:"address"`       // Matching address
	Version      int               `json:"version"`       // Matching version
	TemporalNode *TemporalNode     `json:"temporal_node"` // Matching temporal node
	MatchScore   float64           `json:"match_score"`   // Match relevance score (0-1)
	MatchReasons []string          `json:"match_reasons"` // Why this matched
	Highlights   map[string]string `json:"highlights"`    // Highlighted text matches
}

// ArchiveResult represents result of archiving operation
type ArchiveResult struct {
	ArchiveID       string        `json:"archive_id"`        // Archive identifier
	ItemsArchived   int           `json:"items_archived"`    // Number of items archived
	DataSize        int64         `json:"data_size"`         // Size of archived data
	CompressionRatio float64      `json:"compression_ratio"` // Compression ratio achieved
	ArchivedAt      time.Time     `json:"archived_at"`       // When archiving completed
	Location        string        `json:"location"`          // Archive storage location
	Checksum        string        `json:"checksum"`          // Archive checksum
}

// RestoreResult represents result of restore operation
type RestoreResult struct {
	ArchiveID       string    `json:"archive_id"`        // Archive identifier
	ItemsRestored   int       `json:"items_restored"`    // Number of items restored
	DataSize        int64     `json:"data_size"`         // Size of restored data
	RestoredAt      time.Time `json:"restored_at"`       // When restore completed
	Conflicts       []string  `json:"conflicts"`         // Any conflicts encountered
	SkippedItems    []string  `json:"skipped_items"`     // Items that were skipped
}

// Temporal metrics types

// TemporalMetrics represents comprehensive temporal metrics
type TemporalMetrics struct {
	TotalNodes           int                 `json:"total_nodes"`            // Total temporal nodes
	TotalDecisions       int                 `json:"total_decisions"`        // Total decisions
	ActiveContexts       int                 `json:"active_contexts"`        // Currently active contexts
	InfluenceConnections int                 `json:"influence_connections"`  // Total influence connections
	AverageHopDistance   float64             `json:"average_hop_distance"`   // Average hop distance
	DecisionVelocity     *VelocityMetrics    `json:"decision_velocity"`      // Decision velocity metrics
	EvolutionMetrics     *EvolutionMetrics   `json:"evolution_metrics"`      // Evolution metrics
	InfluenceMetrics     *InfluenceMetrics   `json:"influence_metrics"`      // Influence metrics
	QualityMetrics       *QualityMetrics     `json:"quality_metrics"`        // Quality metrics
	CollectedAt          time.Time           `json:"collected_at"`           // When metrics were collected
}

// VelocityMetrics represents decision velocity metrics
type VelocityMetrics struct {
	DecisionsPerHour    float64   `json:"decisions_per_hour"`     // Decisions per hour
	DecisionsPerDay     float64   `json:"decisions_per_day"`      // Decisions per day
	DecisionsPerWeek    float64   `json:"decisions_per_week"`     // Decisions per week
	PeakVelocityTime    time.Time `json:"peak_velocity_time"`     // When peak velocity occurred
	LowestVelocityTime  time.Time `json:"lowest_velocity_time"`   // When lowest velocity occurred
	VelocityTrend       string    `json:"velocity_trend"`         // increasing, decreasing, stable
	VelocityVariance    float64   `json:"velocity_variance"`      // Velocity variance
	TimeWindow          time.Duration `json:"time_window"`        // Time window for calculation
}

// EvolutionMetrics represents context evolution metrics
type EvolutionMetrics struct {
	ContextsEvolved      int     `json:"contexts_evolved"`       // Number of contexts that evolved
	AverageEvolutions    float64 `json:"average_evolutions"`     // Average evolutions per context
	MajorEvolutions      int     `json:"major_evolutions"`       // Number of major evolutions
	MinorEvolutions      int     `json:"minor_evolutions"`       // Number of minor evolutions
	EvolutionStability   float64 `json:"evolution_stability"`    // Evolution stability score
	EvolutionPredictability float64 `json:"evolution_predictability"` // How predictable evolutions are
	EvolutionEfficiency  float64 `json:"evolution_efficiency"`   // Evolution efficiency score
}

// InfluenceMetrics represents influence relationship metrics
type InfluenceMetrics struct {
	TotalRelationships   int     `json:"total_relationships"`    // Total influence relationships
	AverageInfluenceOut  float64 `json:"average_influence_out"`  // Average outgoing influences
	AverageInfluenceIn   float64 `json:"average_influence_in"`   // Average incoming influences
	StrongestInfluences  int     `json:"strongest_influences"`   // Number of strong influences
	WeakestInfluences    int     `json:"weakest_influences"`     // Number of weak influences
	InfluenceSymmetry    float64 `json:"influence_symmetry"`     // Influence relationship symmetry
	InfluenceConcentration float64 `json:"influence_concentration"` // How concentrated influence is
}

// QualityMetrics represents temporal data quality metrics
type QualityMetrics struct {
	DataCompleteness     float64   `json:"data_completeness"`      // Data completeness score (0-1)
	DataConsistency      float64   `json:"data_consistency"`       // Data consistency score (0-1)
	DataAccuracy         float64   `json:"data_accuracy"`          // Data accuracy score (0-1)
	AverageConfidence    float64   `json:"average_confidence"`     // Average confidence score
	ConflictsDetected    int       `json:"conflicts_detected"`     // Number of conflicts detected
	ConflictsResolved    int       `json:"conflicts_resolved"`     // Number of conflicts resolved
	IntegrityViolations  int       `json:"integrity_violations"`   // Number of integrity violations
	LastQualityCheck     time.Time `json:"last_quality_check"`     // When last quality check was done
	QualityTrend         string    `json:"quality_trend"`          // improving, declining, stable
}

// RefreshAction represents an action to refresh stale context
type RefreshAction struct {
	Type         string            `json:"type"`          // Action type
	Description  string            `json:"description"`   // Action description
	Priority     int               `json:"priority"`      // Action priority
	EstimatedEffort string         `json:"estimated_effort"` // Estimated effort
	RequiredRoles []string         `json:"required_roles"`   // Required roles
	Dependencies  []string         `json:"dependencies"`     // Action dependencies
	Metadata      map[string]interface{} `json:"metadata"` // Additional metadata
}

// StalenessWeights represents weights used in staleness calculation
type StalenessWeights struct {
	TimeWeight        float64 `json:"time_weight"`        // Weight for time since last update
	InfluenceWeight   float64 `json:"influence_weight"`   // Weight for influenced contexts
	ActivityWeight    float64 `json:"activity_weight"`    // Weight for related activity
	ImportanceWeight  float64 `json:"importance_weight"`  // Weight for context importance
	ComplexityWeight  float64 `json:"complexity_weight"`  // Weight for context complexity
	DependencyWeight  float64 `json:"dependency_weight"`  // Weight for dependency changes
}

// StalenessStatistics represents staleness detection statistics
type StalenessStatistics struct {
	TotalContexts        int64     `json:"total_contexts"`         // Total contexts analyzed
	StaleContexts        int64     `json:"stale_contexts"`         // Number of stale contexts
	StalenessRate        float64   `json:"staleness_rate"`         // Percentage stale
	AverageStaleness     float64   `json:"average_staleness"`      // Average staleness score
	MaxStaleness         float64   `json:"max_staleness"`          // Maximum staleness score
	LastDetectionRun     time.Time `json:"last_detection_run"`     // When last run
	DetectionDuration    time.Duration `json:"detection_duration"` // Duration of last run
	RefreshRecommendations int64   `json:"refresh_recommendations"` // Number of refresh recommendations
}

// TemporalConflict represents a conflict in temporal data
type TemporalConflict struct {
	ID               string            `json:"id"`                // Conflict ID
	Type             ConflictType      `json:"type"`              // Type of conflict
	Address          ucxl.Address      `json:"address"`           // Affected address
	ConflictingNodes []*TemporalNode   `json:"conflicting_nodes"` // Conflicting temporal nodes
	Description      string            `json:"description"`       // Conflict description
	Severity         ConflictSeverity  `json:"severity"`          // Conflict severity
	DetectedAt       time.Time         `json:"detected_at"`       // When detected
	ResolvedAt       *time.Time        `json:"resolved_at,omitempty"` // When resolved
	ResolutionMethod string            `json:"resolution_method"` // How resolved
	Metadata         map[string]interface{} `json:"metadata"`     // Additional metadata
}

// ConflictType represents types of temporal conflicts
type ConflictType string

const (
	ConflictVersionMismatch     ConflictType = "version_mismatch"     // Version number conflicts
	ConflictTimestampInconsistency ConflictType = "timestamp_inconsistency" // Timestamp inconsistencies
	ConflictInfluenceCycle      ConflictType = "influence_cycle"      // Circular influence relationships
	ConflictOrphanedNode        ConflictType = "orphaned_node"        // Node without parent
	ConflictDuplicateDecision   ConflictType = "duplicate_decision"   // Duplicate decision IDs
	ConflictInconsistentHash    ConflictType = "inconsistent_hash"    // Hash inconsistencies
)

// ConflictSeverity represents conflict severity levels
type ConflictSeverity string

const (
	SeverityLow      ConflictSeverity = "low"      // Low severity
	SeverityMedium   ConflictSeverity = "medium"   // Medium severity
	SeverityHigh     ConflictSeverity = "high"     // High severity
	SeverityCritical ConflictSeverity = "critical" // Critical severity
)

// DecisionInconsistency represents inconsistent decision metadata
type DecisionInconsistency struct {
	DecisionID       string            `json:"decision_id"`        // Decision ID
	Address          ucxl.Address      `json:"address"`            // Affected address
	InconsistencyType string           `json:"inconsistency_type"` // Type of inconsistency
	Description      string            `json:"description"`        // Description
	ExpectedValue    interface{}       `json:"expected_value"`     // Expected value
	ActualValue      interface{}       `json:"actual_value"`       // Actual value
	DetectedAt       time.Time         `json:"detected_at"`        // When detected
	Severity         ConflictSeverity  `json:"severity"`           // Severity level
}

// SequenceValidation represents validation of decision sequence
type SequenceValidation struct {
	Address          ucxl.Address      `json:"address"`            // Context address
	Valid            bool              `json:"valid"`              // Whether sequence is valid
	Issues           []string          `json:"issues"`             // Validation issues
	Warnings         []string          `json:"warnings"`           // Validation warnings
	ValidatedAt      time.Time         `json:"validated_at"`       // When validated
	SequenceLength   int               `json:"sequence_length"`    // Length of sequence
	IntegrityScore   float64           `json:"integrity_score"`    // Integrity score (0-1)
}

// ConflictResolution represents resolution of a temporal conflict
type ConflictResolution struct {
	ConflictID       string            `json:"conflict_id"`        // Conflict ID
	ResolutionMethod string            `json:"resolution_method"`  // Resolution method
	ResolvedBy       string            `json:"resolved_by"`        // Who resolved it
	ResolvedAt       time.Time         `json:"resolved_at"`        // When resolved
	ResultingNode    *TemporalNode     `json:"resulting_node"`     // Resulting temporal node
	Changes          []string          `json:"changes"`            // Changes made
	Confidence       float64           `json:"confidence"`         // Resolution confidence
	RequiresReview   bool              `json:"requires_review"`    // Whether manual review needed
}