package temporal

import (
	"context"
	"time"

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

// TemporalGraph manages the temporal evolution of context through decision points
//
// This is the main interface for tracking how context evolves through different
// decisions and changes, providing decision-hop based analysis rather than
// simple chronological progression.
type TemporalGraph interface {
	// CreateInitialContext creates the first temporal version of context
	// This establishes the starting point for temporal evolution tracking
	CreateInitialContext(ctx context.Context, address ucxl.Address, 
	                    contextData *slurpContext.ContextNode, creator string) (*TemporalNode, error)
	
	// EvolveContext creates a new temporal version due to a decision
	// Records the decision that caused the change and updates the influence graph
	EvolveContext(ctx context.Context, address ucxl.Address, 
	             newContext *slurpContext.ContextNode, reason ChangeReason, 
	             decision *DecisionMetadata) (*TemporalNode, error)
	
	// GetLatestVersion gets the most recent temporal node for an address
	GetLatestVersion(ctx context.Context, address ucxl.Address) (*TemporalNode, error)
	
	// GetVersionAtDecision gets context as it was at a specific decision hop
	// Navigation based on decision distance, not chronological time
	GetVersionAtDecision(ctx context.Context, address ucxl.Address, 
	                    decisionHop int) (*TemporalNode, error)
	
	// GetEvolutionHistory gets complete evolution history ordered by decisions
	// Returns all temporal versions ordered by decision sequence
	GetEvolutionHistory(ctx context.Context, address ucxl.Address) ([]*TemporalNode, error)
	
	// AddInfluenceRelationship establishes that decisions in one context affect another
	// This creates the decision influence network for hop-based analysis
	AddInfluenceRelationship(ctx context.Context, influencer, influenced ucxl.Address) error
	
	// RemoveInfluenceRelationship removes an influence relationship
	RemoveInfluenceRelationship(ctx context.Context, influencer, influenced ucxl.Address) error
	
	// GetInfluenceRelationships gets all influence relationships for a context
	// Returns both contexts that influence this one and contexts influenced by this one
	GetInfluenceRelationships(ctx context.Context, address ucxl.Address) ([]ucxl.Address, []ucxl.Address, error)
	
	// FindRelatedDecisions finds decisions within N decision hops
	// Explores the decision graph by conceptual distance, not time
	FindRelatedDecisions(ctx context.Context, address ucxl.Address, 
	                    maxHops int) ([]*DecisionPath, error)
	
	// FindDecisionPath finds shortest decision path between two addresses
	// Returns the path of decisions connecting two contexts
	FindDecisionPath(ctx context.Context, from, to ucxl.Address) ([]*DecisionStep, error)
	
	// AnalyzeDecisionPatterns analyzes decision-making patterns over time
	// Identifies patterns in how decisions are made and contexts evolve
	AnalyzeDecisionPatterns(ctx context.Context) (*DecisionAnalysis, error)
	
	// ValidateTemporalIntegrity validates temporal graph integrity
	// Checks for inconsistencies and corruption in temporal data
	ValidateTemporalIntegrity(ctx context.Context) error
	
	// CompactHistory compacts old temporal data to save space
	// Removes detailed history while preserving key decision points
	CompactHistory(ctx context.Context, beforeTime time.Time) error
}

// DecisionNavigator handles decision-hop based navigation through temporal space
//
// Provides navigation through the decision graph based on conceptual
// distance rather than chronological time, enabling exploration of
// related changes and decision sequences.
type DecisionNavigator interface {
	// NavigateDecisionHops navigates by decision distance, not time
	// Moves through the decision graph by the specified number of hops
	NavigateDecisionHops(ctx context.Context, address ucxl.Address, 
	                    hops int, direction NavigationDirection) (*TemporalNode, error)
	
	// GetDecisionTimeline gets timeline ordered by decision sequence
	// Returns decisions in the order they were made, with related decisions
	GetDecisionTimeline(ctx context.Context, address ucxl.Address, 
	                   includeRelated bool, maxHops int) (*DecisionTimeline, error)
	
	// FindStaleContexts finds contexts that may be outdated based on decisions
	// Identifies contexts that haven't been updated despite related changes
	FindStaleContexts(ctx context.Context, stalenessThreshold float64) ([]*StaleContext, error)
	
	// ValidateDecisionPath validates that a decision path is reachable
	// Verifies that a path exists and is traversable
	ValidateDecisionPath(ctx context.Context, path []*DecisionStep) error
	
	// GetNavigationHistory gets navigation history for a session
	GetNavigationHistory(ctx context.Context, sessionID string) ([]*DecisionStep, error)
	
	// ResetNavigation resets navigation state to latest versions
	ResetNavigation(ctx context.Context, address ucxl.Address) error
	
	// BookmarkDecision creates a bookmark for a specific decision point
	BookmarkDecision(ctx context.Context, address ucxl.Address, hop int, name string) error
	
	// ListBookmarks lists all bookmarks for navigation
	ListBookmarks(ctx context.Context) ([]*DecisionBookmark, error)
}

// InfluenceAnalyzer analyzes decision influence relationships and impact
type InfluenceAnalyzer interface {
	// AnalyzeInfluenceNetwork analyzes the structure of decision influence relationships
	AnalyzeInfluenceNetwork(ctx context.Context) (*InfluenceNetworkAnalysis, error)
	
	// GetInfluenceStrength calculates influence strength between contexts
	GetInfluenceStrength(ctx context.Context, influencer, influenced ucxl.Address) (float64, error)
	
	// FindInfluentialDecisions finds the most influential decisions in the system
	FindInfluentialDecisions(ctx context.Context, limit int) ([]*InfluentialDecision, error)
	
	// AnalyzeDecisionImpact analyzes the impact of a specific decision
	AnalyzeDecisionImpact(ctx context.Context, address ucxl.Address, decisionHop int) (*DecisionImpact, error)
	
	// PredictInfluence predicts likely influence relationships
	PredictInfluence(ctx context.Context, address ucxl.Address) ([]*PredictedInfluence, error)
	
	// GetCentralityMetrics calculates centrality metrics for contexts
	GetCentralityMetrics(ctx context.Context) (*CentralityMetrics, error)
}

// StalenessDetector detects and analyzes context staleness based on decisions
type StalenessDetector interface {
	// CalculateStaleness calculates staleness score based on decision relationships
	CalculateStaleness(ctx context.Context, address ucxl.Address) (float64, error)
	
	// DetectStaleContexts detects all stale contexts above threshold
	DetectStaleContexts(ctx context.Context, threshold float64) ([]*StaleContext, error)
	
	// GetStalenessReasons gets reasons why context is considered stale
	GetStalenessReasons(ctx context.Context, address ucxl.Address) ([]string, error)
	
	// SuggestRefreshActions suggests actions to refresh stale context
	SuggestRefreshActions(ctx context.Context, address ucxl.Address) ([]*RefreshAction, error)
	
	// UpdateStalenessWeights updates weights used in staleness calculation
	UpdateStalenessWeights(weights *StalenessWeights) error
	
	// GetStalenessStats returns staleness detection statistics
	GetStalenessStats() (*StalenessStatistics, error)
}

// ConflictDetector detects temporal conflicts and inconsistencies
type ConflictDetector interface {
	// DetectTemporalConflicts detects conflicts in temporal data
	DetectTemporalConflicts(ctx context.Context) ([]*TemporalConflict, error)
	
	// DetectInconsistentDecisions detects inconsistent decision metadata
	DetectInconsistentDecisions(ctx context.Context) ([]*DecisionInconsistency, error)
	
	// ValidateDecisionSequence validates decision sequence for logical consistency
	ValidateDecisionSequence(ctx context.Context, address ucxl.Address) (*SequenceValidation, error)
	
	// ResolveTemporalConflict resolves a specific temporal conflict
	ResolveTemporalConflict(ctx context.Context, conflict *TemporalConflict) (*ConflictResolution, error)
	
	// GetConflictResolutionHistory gets history of resolved conflicts
	GetConflictResolutionHistory(ctx context.Context, address ucxl.Address) ([]*ConflictResolution, error)
}

// PatternAnalyzer analyzes patterns in decision-making and context evolution
type PatternAnalyzer interface {
	// AnalyzeDecisionPatterns identifies patterns in decision-making
	AnalyzeDecisionPatterns(ctx context.Context) ([]*DecisionPattern, error)
	
	// AnalyzeEvolutionPatterns identifies patterns in context evolution
	AnalyzeEvolutionPatterns(ctx context.Context) ([]*EvolutionPattern, error)
	
	// DetectAnomalousDecisions detects unusual decision patterns
	DetectAnomalousDecisions(ctx context.Context) ([]*AnomalousDecision, error)
	
	// PredictNextDecision predicts likely next decisions for a context
	PredictNextDecision(ctx context.Context, address ucxl.Address) ([]*DecisionPrediction, error)
	
	// LearnFromHistory learns patterns from historical decision data
	LearnFromHistory(ctx context.Context, timeRange time.Duration) (*LearningResult, error)
	
	// GetPatternStats returns pattern analysis statistics
	GetPatternStats() (*PatternStatistics, error)
}

// VersionManager manages temporal version operations
type VersionManager interface {
	// CreateVersion creates a new temporal version
	CreateVersion(ctx context.Context, address ucxl.Address, 
	             contextNode *slurpContext.ContextNode, metadata *VersionMetadata) (*TemporalNode, error)
	
	// GetVersion retrieves a specific version
	GetVersion(ctx context.Context, address ucxl.Address, version int) (*TemporalNode, error)
	
	// ListVersions lists all versions for a context
	ListVersions(ctx context.Context, address ucxl.Address) ([]*VersionInfo, error)
	
	// CompareVersions compares two temporal versions
	CompareVersions(ctx context.Context, address ucxl.Address, 
	               version1, version2 int) (*VersionComparison, error)
	
	// MergeVersions merges multiple versions into one
	MergeVersions(ctx context.Context, address ucxl.Address, 
	             versions []int, strategy MergeStrategy) (*TemporalNode, error)
	
	// TagVersion adds tags to a version for easier reference
	TagVersion(ctx context.Context, address ucxl.Address, version int, tags []string) error
	
	// GetVersionTags gets tags for a specific version
	GetVersionTags(ctx context.Context, address ucxl.Address, version int) ([]string, error)
}

// HistoryManager manages temporal history operations
type HistoryManager interface {
	// GetFullHistory gets complete history for a context
	GetFullHistory(ctx context.Context, address ucxl.Address) (*ContextHistory, error)
	
	// GetHistoryRange gets history within a specific range
	GetHistoryRange(ctx context.Context, address ucxl.Address, 
	               startHop, endHop int) (*ContextHistory, error)
	
	// SearchHistory searches history using criteria
	SearchHistory(ctx context.Context, criteria *HistorySearchCriteria) ([]*HistoryMatch, error)
	
	// ExportHistory exports history in various formats
	ExportHistory(ctx context.Context, address ucxl.Address, 
	             format string) ([]byte, error)
	
	// ImportHistory imports history from external sources
	ImportHistory(ctx context.Context, address ucxl.Address, 
	             data []byte, format string) error
	
	// ArchiveHistory archives old history data
	ArchiveHistory(ctx context.Context, beforeTime time.Time) (*ArchiveResult, error)
	
	// RestoreHistory restores archived history data
	RestoreHistory(ctx context.Context, archiveID string) (*RestoreResult, error)
}

// MetricsCollector collects temporal metrics and statistics
type MetricsCollector interface {
	// CollectTemporalMetrics collects comprehensive temporal metrics
	CollectTemporalMetrics(ctx context.Context) (*TemporalMetrics, error)
	
	// GetDecisionVelocity calculates decision-making velocity
	GetDecisionVelocity(ctx context.Context, timeWindow time.Duration) (*VelocityMetrics, error)
	
	// GetEvolutionMetrics gets context evolution metrics
	GetEvolutionMetrics(ctx context.Context) (*EvolutionMetrics, error)
	
	// GetInfluenceMetrics gets influence relationship metrics
	GetInfluenceMetrics(ctx context.Context) (*InfluenceMetrics, error)
	
	// GetQualityMetrics gets temporal data quality metrics
	GetQualityMetrics(ctx context.Context) (*QualityMetrics, error)
	
	// ResetMetrics resets all collected metrics
	ResetMetrics(ctx context.Context) error
}

// Supporting types for temporal operations

// NavigationDirection represents direction for temporal navigation
type NavigationDirection string

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

// MergeStrategy represents strategy for merging temporal versions
type MergeStrategy string

const (
	MergeLatestWins    MergeStrategy = "latest_wins"    // Latest version wins conflicts
	MergeFirstWins     MergeStrategy = "first_wins"     // First version wins conflicts
	MergeSmartMerge    MergeStrategy = "smart_merge"    // Intelligent semantic merging
	MergeManual        MergeStrategy = "manual"         // Require manual resolution
)

// VersionMetadata represents metadata for version creation
type VersionMetadata struct {
	Creator         string                 `json:"creator"`          // Who created the version
	CreatedAt       time.Time              `json:"created_at"`       // When created
	Reason          ChangeReason           `json:"reason"`           // Reason for change
	Decision        *DecisionMetadata      `json:"decision"`         // Associated decision
	Tags            []string               `json:"tags"`             // Version tags
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// DecisionBookmark represents a bookmarked decision point
type DecisionBookmark struct {
	ID              string                 `json:"id"`               // Bookmark ID
	Name            string                 `json:"name"`             // Bookmark name
	Description     string                 `json:"description"`      // Bookmark description
	Address         ucxl.Address           `json:"address"`          // Context address
	DecisionHop     int                    `json:"decision_hop"`     // Decision hop number
	CreatedBy       string                 `json:"created_by"`       // Who created bookmark
	CreatedAt       time.Time              `json:"created_at"`       // When created
	Tags            []string               `json:"tags"`             // Bookmark tags
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}