package alignment

import (
	"time"

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

// ProjectGoal represents a high-level project objective
type ProjectGoal struct {
	ID            string              `json:"id"`             // Unique identifier
	Name          string              `json:"name"`           // Goal name
	Description   string              `json:"description"`    // Detailed description
	Keywords      []string            `json:"keywords"`       // Associated keywords
	Priority      int                 `json:"priority"`       // Priority level (1=highest)
	Phase         string              `json:"phase"`          // Project phase
	Category      string              `json:"category"`       // Goal category
	Owner         string              `json:"owner"`          // Goal owner
	Status        GoalStatus          `json:"status"`         // Current status
	
	// Success criteria
	Metrics       []string            `json:"metrics"`        // Success metrics
	SuccessCriteria []*SuccessCriterion `json:"success_criteria"` // Detailed success criteria
	AcceptanceCriteria []string        `json:"acceptance_criteria"` // Acceptance criteria
	
	// Timeline
	StartDate     *time.Time          `json:"start_date,omitempty"`  // Goal start date
	TargetDate    *time.Time          `json:"target_date,omitempty"` // Target completion date
	ActualDate    *time.Time          `json:"actual_date,omitempty"` // Actual completion date
	
	// Relationships
	ParentGoalID  *string             `json:"parent_goal_id,omitempty"` // Parent goal
	ChildGoalIDs  []string            `json:"child_goal_ids"`           // Child goals
	Dependencies  []string            `json:"dependencies"`             // Goal dependencies
	
	// Configuration
	Weights       *GoalWeights        `json:"weights"`        // Assessment weights
	ThresholdScore float64            `json:"threshold_score"` // Minimum alignment score
	
	// Metadata
	CreatedAt     time.Time           `json:"created_at"`     // When created
	UpdatedAt     time.Time           `json:"updated_at"`     // When last updated
	CreatedBy     string              `json:"created_by"`     // Who created it
	Tags          []string            `json:"tags"`           // Goal tags
	Metadata      map[string]interface{} `json:"metadata"`   // Additional metadata
}

// GoalStatus represents the current status of a goal
type GoalStatus string

const (
	GoalStatusDraft       GoalStatus = "draft"       // Goal is in draft state
	GoalStatusActive      GoalStatus = "active"      // Goal is active
	GoalStatusOnHold      GoalStatus = "on_hold"     // Goal is on hold
	GoalStatusCompleted   GoalStatus = "completed"   // Goal is completed
	GoalStatusCancelled   GoalStatus = "cancelled"   // Goal is cancelled
	GoalStatusArchived    GoalStatus = "archived"    // Goal is archived
)

// SuccessCriterion represents a specific success criterion for a goal
type SuccessCriterion struct {
	ID            string              `json:"id"`             // Criterion ID
	Description   string              `json:"description"`    // Criterion description
	MetricName    string              `json:"metric_name"`    // Associated metric
	TargetValue   interface{}         `json:"target_value"`   // Target value
	CurrentValue  interface{}         `json:"current_value"`  // Current value
	Unit          string              `json:"unit"`           // Value unit
	ComparisonOp  string              `json:"comparison_op"`  // Comparison operator (>=, <=, ==, etc.)
	Weight        float64             `json:"weight"`         // Criterion weight
	Achieved      bool                `json:"achieved"`       // Whether achieved
	AchievedAt    *time.Time          `json:"achieved_at,omitempty"` // When achieved
}

// GoalWeights represents weights for different aspects of goal alignment assessment
type GoalWeights struct {
	KeywordMatch      float64 `json:"keyword_match"`       // Weight for keyword matching
	SemanticAlignment float64 `json:"semantic_alignment"`  // Weight for semantic alignment
	PurposeAlignment  float64 `json:"purpose_alignment"`   // Weight for purpose alignment
	TechnologyMatch   float64 `json:"technology_match"`    // Weight for technology matching
	QualityScore      float64 `json:"quality_score"`       // Weight for context quality
	RecentActivity    float64 `json:"recent_activity"`     // Weight for recent activity
	ImportanceScore   float64 `json:"importance_score"`    // Weight for component importance
}

// AlignmentAssessment represents overall alignment assessment for a context
type AlignmentAssessment struct {
	Address           ucxl.Address        `json:"address"`            // Context address
	OverallScore      float64             `json:"overall_score"`      // Overall alignment score (0-1)
	GoalAlignments    []*GoalAlignment    `json:"goal_alignments"`    // Individual goal alignments
	StrengthAreas     []string            `json:"strength_areas"`     // Areas of strong alignment
	WeaknessAreas     []string            `json:"weakness_areas"`     // Areas of weak alignment
	Recommendations   []*AlignmentRecommendation `json:"recommendations"` // Improvement recommendations
	AssessedAt        time.Time           `json:"assessed_at"`        // When assessment was performed
	AssessmentVersion string              `json:"assessment_version"` // Assessment algorithm version
	Confidence        float64             `json:"confidence"`         // Assessment confidence (0-1)
	Metadata          map[string]interface{} `json:"metadata"`        // Additional metadata
}

// GoalAlignment represents alignment assessment for a specific goal
type GoalAlignment struct {
	GoalID            string              `json:"goal_id"`            // Goal identifier
	GoalName          string              `json:"goal_name"`          // Goal name
	AlignmentScore    float64             `json:"alignment_score"`    // Alignment score (0-1)
	ComponentScores   *AlignmentScores    `json:"component_scores"`   // Component-wise scores
	MatchedKeywords   []string            `json:"matched_keywords"`   // Keywords that matched
	MatchedCriteria   []string            `json:"matched_criteria"`   // Criteria that matched
	Explanation       string              `json:"explanation"`        // Alignment explanation
	ConfidenceLevel   float64             `json:"confidence_level"`   // Confidence in assessment
	ImprovementAreas  []string            `json:"improvement_areas"`  // Areas for improvement
	Strengths         []string            `json:"strengths"`          // Alignment strengths
}

// AlignmentScores represents component scores for alignment assessment
type AlignmentScores struct {
	KeywordScore      float64 `json:"keyword_score"`       // Keyword matching score
	SemanticScore     float64 `json:"semantic_score"`      // Semantic alignment score
	PurposeScore      float64 `json:"purpose_score"`       // Purpose alignment score
	TechnologyScore   float64 `json:"technology_score"`    // Technology alignment score
	QualityScore      float64 `json:"quality_score"`       // Context quality score
	ActivityScore     float64 `json:"activity_score"`      // Recent activity score
	ImportanceScore   float64 `json:"importance_score"`    // Component importance score
}

// AlignmentRecommendation represents a recommendation for improving alignment
type AlignmentRecommendation struct {
	ID                string              `json:"id"`                 // Recommendation ID
	Type              RecommendationType  `json:"type"`               // Recommendation type
	Priority          int                 `json:"priority"`           // Priority (1=highest)
	Title             string              `json:"title"`              // Recommendation title
	Description       string              `json:"description"`        // Detailed description
	GoalID            *string             `json:"goal_id,omitempty"`  // Related goal
	Address           ucxl.Address        `json:"address"`            // Context address
	
	// Implementation details
	ActionItems       []string            `json:"action_items"`       // Specific actions
	EstimatedEffort   EffortLevel         `json:"estimated_effort"`   // Estimated effort
	ExpectedImpact    ImpactLevel         `json:"expected_impact"`    // Expected impact
	RequiredRoles     []string            `json:"required_roles"`     // Required roles
	Prerequisites     []string            `json:"prerequisites"`      // Prerequisites
	
	// Status tracking
	Status            RecommendationStatus `json:"status"`            // Implementation status
	AssignedTo        []string            `json:"assigned_to"`        // Assigned team members
	CreatedAt         time.Time           `json:"created_at"`         // When created
	DueDate           *time.Time          `json:"due_date,omitempty"` // Implementation due date
	CompletedAt       *time.Time          `json:"completed_at,omitempty"` // When completed
	
	// Metadata
	Tags              []string            `json:"tags"`               // Recommendation tags
	Metadata          map[string]interface{} `json:"metadata"`        // Additional metadata
}

// RecommendationType represents types of alignment recommendations
type RecommendationType string

const (
	RecommendationKeywordImprovement RecommendationType = "keyword_improvement"    // Improve keyword matching
	RecommendationPurposeAlignment   RecommendationType = "purpose_alignment"     // Align purpose better
	RecommendationTechnologyUpdate   RecommendationType = "technology_update"     // Update technology usage
	RecommendationQualityImprovement RecommendationType = "quality_improvement"   // Improve context quality
	RecommendationDocumentation      RecommendationType = "documentation"         // Add/improve documentation
	RecommendationRefactoring        RecommendationType = "refactoring"           // Code refactoring
	RecommendationArchitectural      RecommendationType = "architectural"         // Architectural changes
	RecommendationTesting            RecommendationType = "testing"               // Testing improvements
	RecommendationPerformance        RecommendationType = "performance"           // Performance optimization
	RecommendationSecurity           RecommendationType = "security"              // Security enhancements
)

// EffortLevel represents estimated effort levels
type EffortLevel string

const (
	EffortLow     EffortLevel = "low"     // Low effort (1-2 hours)
	EffortMedium  EffortLevel = "medium"  // Medium effort (1-2 days)
	EffortHigh    EffortLevel = "high"    // High effort (1-2 weeks)
	EffortVeryHigh EffortLevel = "very_high" // Very high effort (>2 weeks)
)

// ImpactLevel represents expected impact levels
type ImpactLevel string

const (
	ImpactLow     ImpactLevel = "low"     // Low impact
	ImpactMedium  ImpactLevel = "medium"  // Medium impact
	ImpactHigh    ImpactLevel = "high"    // High impact
	ImpactCritical ImpactLevel = "critical" // Critical impact
)

// RecommendationStatus represents implementation status of recommendations
type RecommendationStatus string

const (
	RecommendationStatusNew        RecommendationStatus = "new"         // New recommendation
	RecommendationStatusAssigned   RecommendationStatus = "assigned"    // Assigned to team member
	RecommendationStatusInProgress RecommendationStatus = "in_progress" // Implementation in progress
	RecommendationStatusCompleted  RecommendationStatus = "completed"   // Implementation completed
	RecommendationStatusRejected   RecommendationStatus = "rejected"    // Recommendation rejected
	RecommendationStatusDeferred   RecommendationStatus = "deferred"    // Implementation deferred
)

// GoalProgress represents progress toward goal achievement
type GoalProgress struct {
	GoalID                string              `json:"goal_id"`                 // Goal identifier
	CompletionPercentage  float64             `json:"completion_percentage"`   // Completion percentage (0-100)
	CriteriaProgress      []*CriterionProgress `json:"criteria_progress"`      // Progress for each criterion
	Milestones            []*MilestoneProgress `json:"milestones"`             // Milestone progress
	Velocity              float64             `json:"velocity"`               // Progress velocity (% per day)
	EstimatedCompletion   *time.Time          `json:"estimated_completion,omitempty"` // Estimated completion date
	RiskFactors           []string            `json:"risk_factors"`           // Identified risk factors
	Blockers              []string            `json:"blockers"`               // Current blockers
	LastUpdated           time.Time           `json:"last_updated"`           // When last updated
	UpdatedBy             string              `json:"updated_by"`             // Who last updated
}

// CriterionProgress represents progress for a specific success criterion
type CriterionProgress struct {
	CriterionID       string      `json:"criterion_id"`        // Criterion ID
	CurrentValue      interface{} `json:"current_value"`       // Current value
	TargetValue       interface{} `json:"target_value"`        // Target value
	ProgressPercentage float64    `json:"progress_percentage"` // Progress percentage
	Achieved          bool        `json:"achieved"`            // Whether achieved
	AchievedAt        *time.Time  `json:"achieved_at,omitempty"` // When achieved
	Notes             string      `json:"notes"`               // Progress notes
}

// MilestoneProgress represents progress for a goal milestone
type MilestoneProgress struct {
	MilestoneID       string             `json:"milestone_id"`        // Milestone ID
	Name              string             `json:"name"`                // Milestone name
	Status            MilestoneStatus    `json:"status"`              // Current status
	CompletionPercentage float64         `json:"completion_percentage"` // Completion percentage
	PlannedDate       time.Time          `json:"planned_date"`        // Planned completion date
	ActualDate        *time.Time         `json:"actual_date,omitempty"` // Actual completion date
	DelayReason       string             `json:"delay_reason"`        // Reason for delay if applicable
}

// MilestoneStatus represents status of a milestone
type MilestoneStatus string

const (
	MilestoneStatusNotStarted MilestoneStatus = "not_started" // Not started
	MilestoneStatusInProgress MilestoneStatus = "in_progress" // In progress
	MilestoneStatusCompleted  MilestoneStatus = "completed"   // Completed
	MilestoneStatusDelayed    MilestoneStatus = "delayed"     // Delayed
	MilestoneStatusCancelled  MilestoneStatus = "cancelled"   // Cancelled
)

// AlignmentDrift represents detected alignment drift
type AlignmentDrift struct {
	Address           ucxl.Address        `json:"address"`            // Context address
	DriftType         DriftType           `json:"drift_type"`         // Type of drift
	Severity          DriftSeverity       `json:"severity"`           // Drift severity
	CurrentScore      float64             `json:"current_score"`      // Current alignment score
	PreviousScore     float64             `json:"previous_score"`     // Previous alignment score
	ScoreDelta        float64             `json:"score_delta"`        // Change in score
	AffectedGoals     []string            `json:"affected_goals"`     // Goals affected by drift
	DetectedAt        time.Time           `json:"detected_at"`        // When drift was detected
	DriftReason       []string            `json:"drift_reason"`       // Reasons for drift
	RecommendedActions []string           `json:"recommended_actions"` // Recommended actions
	Priority          DriftPriority       `json:"priority"`           // Priority for addressing
}

// DriftType represents types of alignment drift
type DriftType string

const (
	DriftTypeGradual      DriftType = "gradual"       // Gradual drift over time
	DriftTypeSudden       DriftType = "sudden"        // Sudden drift
	DriftTypeOscillating  DriftType = "oscillating"   // Oscillating drift pattern
	DriftTypeGoalChange   DriftType = "goal_change"   // Due to goal changes
	DriftTypeContextChange DriftType = "context_change" // Due to context changes
)

// DriftSeverity represents severity of alignment drift
type DriftSeverity string

const (
	DriftSeverityLow      DriftSeverity = "low"      // Low severity
	DriftSeverityMedium   DriftSeverity = "medium"   // Medium severity
	DriftSeverityHigh     DriftSeverity = "high"     // High severity
	DriftSeverityCritical DriftSeverity = "critical" // Critical severity
)

// DriftPriority represents priority for addressing drift
type DriftPriority string

const (
	DriftPriorityLow      DriftPriority = "low"      // Low priority
	DriftPriorityMedium   DriftPriority = "medium"   // Medium priority
	DriftPriorityHigh     DriftPriority = "high"     // High priority
	DriftPriorityUrgent   DriftPriority = "urgent"   // Urgent priority
)

// AlignmentTrends represents alignment trends over time
type AlignmentTrends struct {
	Address           ucxl.Address        `json:"address"`            // Context address
	TimeRange         time.Duration       `json:"time_range"`         // Analyzed time range
	DataPoints        []*TrendDataPoint   `json:"data_points"`        // Trend data points
	OverallTrend      TrendDirection      `json:"overall_trend"`      // Overall trend direction
	TrendStrength     float64             `json:"trend_strength"`     // Trend strength (0-1)
	Volatility        float64             `json:"volatility"`         // Score volatility
	SeasonalPatterns  []*SeasonalPattern  `json:"seasonal_patterns"`  // Detected seasonal patterns
	AnomalousPoints   []*AnomalousPoint   `json:"anomalous_points"`   // Anomalous data points
	Predictions       []*TrendPrediction  `json:"predictions"`        // Future trend predictions
	AnalyzedAt        time.Time           `json:"analyzed_at"`        // When analysis was performed
}

// TrendDataPoint represents a single data point in alignment trends
type TrendDataPoint struct {
	Timestamp     time.Time `json:"timestamp"`      // Data point timestamp
	AlignmentScore float64  `json:"alignment_score"` // Alignment score at this time
	GoalScores    map[string]float64 `json:"goal_scores"` // Individual goal scores
	Events        []string  `json:"events"`         // Events that occurred around this time
}

// TrendDirection represents direction of alignment trends
type TrendDirection string

const (
	TrendDirectionImproving  TrendDirection = "improving"  // Improving trend
	TrendDirectionDeclining  TrendDirection = "declining"  // Declining trend
	TrendDirectionStable     TrendDirection = "stable"     // Stable trend
	TrendDirectionVolatile   TrendDirection = "volatile"   // Volatile trend
)

// SeasonalPattern represents a detected seasonal pattern in alignment
type SeasonalPattern struct {
	PatternType   string        `json:"pattern_type"`    // Type of pattern (weekly, monthly, etc.)
	Period        time.Duration `json:"period"`          // Pattern period
	Amplitude     float64       `json:"amplitude"`       // Pattern amplitude
	Confidence    float64       `json:"confidence"`      // Pattern confidence
	Description   string        `json:"description"`     // Pattern description
}

// AnomalousPoint represents an anomalous data point
type AnomalousPoint struct {
	Timestamp     time.Time `json:"timestamp"`      // When anomaly occurred
	ExpectedScore float64   `json:"expected_score"` // Expected alignment score
	ActualScore   float64   `json:"actual_score"`   // Actual alignment score
	AnomalyScore  float64   `json:"anomaly_score"`  // Anomaly score
	PossibleCauses []string `json:"possible_causes"` // Possible causes
}

// TrendPrediction represents a prediction of future alignment trends
type TrendPrediction struct {
	Timestamp         time.Time `json:"timestamp"`          // Predicted timestamp
	PredictedScore    float64   `json:"predicted_score"`    // Predicted alignment score
	ConfidenceInterval *ConfidenceInterval `json:"confidence_interval"` // Confidence interval
	Probability       float64   `json:"probability"`        // Prediction probability
}

// ConfidenceInterval represents a confidence interval for predictions
type ConfidenceInterval struct {
	LowerBound float64 `json:"lower_bound"` // Lower bound
	UpperBound float64 `json:"upper_bound"` // Upper bound
	Confidence float64 `json:"confidence"`  // Confidence level (0.95 for 95% CI)
}

// AlignmentWeights represents weights for alignment calculation
type AlignmentWeights struct {
	GoalWeights       map[string]float64 `json:"goal_weights"`        // Weights by goal ID
	CategoryWeights   map[string]float64 `json:"category_weights"`    // Weights by goal category
	PriorityWeights   map[int]float64    `json:"priority_weights"`    // Weights by priority level
	PhaseWeights      map[string]float64 `json:"phase_weights"`       // Weights by project phase
	RoleWeights       map[string]float64 `json:"role_weights"`        // Weights by role
	ComponentWeights  *AlignmentScores   `json:"component_weights"`   // Weights for score components
	TemporalWeights   *TemporalWeights   `json:"temporal_weights"`    // Temporal weighting factors
}

// TemporalWeights represents temporal weighting factors
type TemporalWeights struct {
	RecentWeight      float64 `json:"recent_weight"`       // Weight for recent changes
	DecayFactor       float64 `json:"decay_factor"`        // Score decay factor over time
	RecencyWindow     time.Duration `json:"recency_window"` // Window for considering recent activity
	HistoricalWeight  float64 `json:"historical_weight"`   // Weight for historical alignment
}

// GoalFilter represents filtering criteria for goal listing
type GoalFilter struct {
	Status       []GoalStatus `json:"status,omitempty"`        // Filter by status
	Priority     *int         `json:"priority,omitempty"`      // Filter by priority
	Phase        []string     `json:"phase,omitempty"`         // Filter by phase
	Category     []string     `json:"category,omitempty"`      // Filter by category
	Owner        []string     `json:"owner,omitempty"`         // Filter by owner
	Tags         []string     `json:"tags,omitempty"`          // Filter by tags
	CreatedAfter *time.Time   `json:"created_after,omitempty"` // Created after date
	DueBy        *time.Time   `json:"due_by,omitempty"`        // Due by date
	SearchText   string       `json:"search_text,omitempty"`   // Text search
	Limit        int          `json:"limit,omitempty"`         // Result limit
	Offset       int          `json:"offset,omitempty"`        // Result offset
}

// GoalHierarchy represents the hierarchical structure of goals
type GoalHierarchy struct {
	RootGoals     []*GoalNode `json:"root_goals"`      // Root level goals
	MaxDepth      int         `json:"max_depth"`       // Maximum hierarchy depth
	TotalGoals    int         `json:"total_goals"`     // Total number of goals
	GeneratedAt   time.Time   `json:"generated_at"`    // When hierarchy was generated
}

// GoalNode represents a node in the goal hierarchy
type GoalNode struct {
	Goal         *ProjectGoal `json:"goal"`          // Goal information
	Children     []*GoalNode  `json:"children"`      // Child goals
	Depth        int          `json:"depth"`         // Depth in hierarchy
	Path         []string     `json:"path"`          // Path from root
}

// GoalValidation represents validation results for a goal
type GoalValidation struct {
	Valid        bool             `json:"valid"`         // Whether goal is valid
	Issues       []*ValidationIssue `json:"issues"`      // Validation issues
	Warnings     []*ValidationWarning `json:"warnings"`  // Validation warnings
	ValidatedAt  time.Time        `json:"validated_at"`  // When validated
}

// ValidationIssue represents a validation issue
type ValidationIssue struct {
	Field       string `json:"field"`        // Affected field
	Code        string `json:"code"`         // Issue code
	Message     string `json:"message"`      // Issue message
	Severity    string `json:"severity"`     // Issue severity
	Suggestion  string `json:"suggestion"`   // Suggested fix
}

// ValidationWarning represents a validation warning
type ValidationWarning struct {
	Field       string `json:"field"`        // Affected field
	Code        string `json:"code"`         // Warning code
	Message     string `json:"message"`      // Warning message
	Suggestion  string `json:"suggestion"`   // Suggested improvement
}

// GoalMilestone represents a milestone for goal tracking
type GoalMilestone struct {
	ID            string      `json:"id"`             // Milestone ID
	Name          string      `json:"name"`           // Milestone name
	Description   string      `json:"description"`    // Milestone description
	PlannedDate   time.Time   `json:"planned_date"`   // Planned completion date
	Weight        float64     `json:"weight"`         // Milestone weight
	Criteria      []string    `json:"criteria"`       // Completion criteria
	Dependencies  []string    `json:"dependencies"`   // Milestone dependencies
	CreatedAt     time.Time   `json:"created_at"`     // When created
}

// MilestoneStatus represents status of a milestone (duplicate removed)
// Already defined above

// ProgressUpdate represents an update to goal progress
type ProgressUpdate struct {
	UpdateType        ProgressUpdateType `json:"update_type"`         // Type of update
	CompletionDelta   float64           `json:"completion_delta"`    // Change in completion percentage
	CriteriaUpdates   []*CriterionUpdate `json:"criteria_updates"`   // Updates to criteria
	MilestoneUpdates  []*MilestoneUpdate `json:"milestone_updates"`  // Updates to milestones
	Notes             string            `json:"notes"`               // Update notes
	UpdatedBy         string            `json:"updated_by"`          // Who made the update
	Evidence          []string          `json:"evidence"`            // Evidence for progress
	RiskFactors       []string          `json:"risk_factors"`        // New risk factors
	Blockers          []string          `json:"blockers"`            // New blockers
}

// ProgressUpdateType represents types of progress updates
type ProgressUpdateType string

const (
	ProgressUpdateTypeIncrement   ProgressUpdateType = "increment"   // Incremental progress
	ProgressUpdateTypeAbsolute    ProgressUpdateType = "absolute"    // Absolute progress value
	ProgressUpdateTypeMilestone   ProgressUpdateType = "milestone"   // Milestone completion
	ProgressUpdateTypeCriterion   ProgressUpdateType = "criterion"   // Criterion achievement
)

// CriterionUpdate represents an update to a success criterion
type CriterionUpdate struct {
	CriterionID   string      `json:"criterion_id"`    // Criterion ID
	NewValue      interface{} `json:"new_value"`       // New current value
	Achieved      bool        `json:"achieved"`        // Whether now achieved
	Notes         string      `json:"notes"`           // Update notes
}

// MilestoneUpdate represents an update to a milestone
type MilestoneUpdate struct {
	MilestoneID   string          `json:"milestone_id"`    // Milestone ID
	NewStatus     MilestoneStatus `json:"new_status"`      // New status
	CompletedDate *time.Time      `json:"completed_date,omitempty"` // Completion date if completed
	Notes         string          `json:"notes"`           // Update notes
}