package alignment

import (
	"context"
	"time"

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

// GoalManager handles definition and management of project goals
//
// This is the primary interface for creating, updating, and managing
// project goals that serve as the reference for alignment assessment
// throughout the system.
type GoalManager interface {
	// CreateGoal creates a new project goal
	CreateGoal(ctx context.Context, goal *ProjectGoal) error
	
	// UpdateGoal updates an existing project goal
	UpdateGoal(ctx context.Context, goal *ProjectGoal) error
	
	// DeleteGoal removes a project goal
	DeleteGoal(ctx context.Context, goalID string) error
	
	// GetGoal retrieves a specific project goal
	GetGoal(ctx context.Context, goalID string) (*ProjectGoal, error)
	
	// ListGoals lists all project goals with optional filtering
	ListGoals(ctx context.Context, filter *GoalFilter) ([]*ProjectGoal, error)
	
	// SetGoalPriority updates goal priority
	SetGoalPriority(ctx context.Context, goalID string, priority int) error
	
	// SetGoalStatus updates goal status
	SetGoalStatus(ctx context.Context, goalID string, status GoalStatus) error
	
	// CreateGoalHierarchy establishes parent-child relationships between goals
	CreateGoalHierarchy(ctx context.Context, parentID, childID string) error
	
	// GetGoalHierarchy gets the goal hierarchy tree
	GetGoalHierarchy(ctx context.Context) (*GoalHierarchy, error)
	
	// ValidateGoal validates goal definition and constraints
	ValidateGoal(ctx context.Context, goal *ProjectGoal) (*GoalValidation, error)
	
	// GetGoalStats returns goal management statistics
	GetGoalStats(ctx context.Context) (*GoalStatistics, error)
}

// AlignmentAnalyzer assesses how well context aligns with project goals
//
// Provides comprehensive analysis of context-goal alignment using multiple
// assessment dimensions and generates actionable recommendations for
// improving alignment with project objectives.
type AlignmentAnalyzer interface {
	// AssessAlignment assesses overall alignment of context with all relevant goals
	AssessAlignment(ctx context.Context, node *slurpContext.ContextNode) (*AlignmentAssessment, error)
	
	// AssessGoalAlignment assesses alignment with a specific goal
	AssessGoalAlignment(ctx context.Context, node *slurpContext.ContextNode, goalID string) (*GoalAlignment, error)
	
	// BatchAssessAlignment assesses alignment for multiple contexts efficiently
	BatchAssessAlignment(ctx context.Context, nodes []*slurpContext.ContextNode) (map[string]*AlignmentAssessment, error)
	
	// GetRecommendations generates alignment improvement recommendations
	GetRecommendations(ctx context.Context, node *slurpContext.ContextNode) ([]*AlignmentRecommendation, error)
	
	// AnalyzeAlignmentGaps identifies gaps between current and desired alignment
	AnalyzeAlignmentGaps(ctx context.Context, address ucxl.Address) (*AlignmentGapAnalysis, error)
	
	// CompareAlignment compares alignment between different contexts
	CompareAlignment(ctx context.Context, node1, node2 *slurpContext.ContextNode) (*AlignmentComparison, error)
	
	// GetAlignmentTrends gets alignment trends over time
	GetAlignmentTrends(ctx context.Context, address ucxl.Address, timeRange time.Duration) (*AlignmentTrends, error)
	
	// SetAlignmentWeights configures weights for alignment calculation
	SetAlignmentWeights(weights *AlignmentWeights) error
	
	// GetAlignmentStats returns alignment analysis statistics
	GetAlignmentStats() (*AlignmentStatistics, error)
}

// ProgressTracker tracks progress toward goal achievement
//
// Monitors and reports on progress toward project goals using various
// metrics and indicators, providing visibility into goal achievement
// and timeline adherence.
type ProgressTracker interface {
	// GetGoalProgress gets current progress for a specific goal
	GetGoalProgress(ctx context.Context, goalID string) (*GoalProgress, error)
	
	// UpdateProgress updates progress for a goal
	UpdateProgress(ctx context.Context, goalID string, progress *ProgressUpdate) error
	
	// GetAllProgress gets progress for all active goals
	GetAllProgress(ctx context.Context) (map[string]*GoalProgress, error)
	
	// GetProgressHistory gets historical progress data
	GetProgressHistory(ctx context.Context, goalID string, timeRange time.Duration) (*ProgressHistory, error)
	
	// SetGoalMilestones defines milestones for goal tracking
	SetGoalMilestones(ctx context.Context, goalID string, milestones []*GoalMilestone) error
	
	// GetMilestoneStatus gets status of goal milestones
	GetMilestoneStatus(ctx context.Context, goalID string) ([]*MilestoneStatus, error)
	
	// PredictCompletion predicts goal completion timeline
	PredictCompletion(ctx context.Context, goalID string) (*CompletionPrediction, error)
	
	// GenerateProgressReport generates comprehensive progress report
	GenerateProgressReport(ctx context.Context, format string) ([]byte, error)
	
	// GetProgressStats returns progress tracking statistics
	GetProgressStats() (*ProgressStatistics, error)
}

// DriftDetector detects alignment drift and degradation over time
//
// Monitors changes in alignment scores and patterns to identify when
// contexts are drifting away from project goals, enabling proactive
// corrective action.
type DriftDetector interface {
	// DetectDrift detects alignment drift for a specific context
	DetectDrift(ctx context.Context, address ucxl.Address) (*AlignmentDrift, error)
	
	// DetectSystemWideDrift detects drift across the entire system
	DetectSystemWideDrift(ctx context.Context) ([]*AlignmentDrift, error)
	
	// GetDriftHistory gets historical drift data
	GetDriftHistory(ctx context.Context, address ucxl.Address) (*DriftHistory, error)
	
	// SetDriftThresholds configures thresholds for drift detection
	SetDriftThresholds(thresholds *DriftThresholds) error
	
	// AnalyzeDriftPatterns analyzes patterns in alignment drift
	AnalyzeDriftPatterns(ctx context.Context) (*DriftPatternAnalysis, error)
	
	// PredictDrift predicts future alignment drift
	PredictDrift(ctx context.Context, address ucxl.Address, horizon time.Duration) (*DriftPrediction, error)
	
	// GetDriftAlerts gets active drift alerts
	GetDriftAlerts(ctx context.Context) ([]*DriftAlert, error)
	
	// AcknowledgeDriftAlert acknowledges a drift alert
	AcknowledgeDriftAlert(ctx context.Context, alertID string, acknowledgedBy string) error
}

// RecommendationEngine generates strategic alignment recommendations
//
// Analyzes context and goal relationships to generate actionable
// recommendations for improving alignment and achieving project
// objectives more effectively.
type RecommendationEngine interface {
	// GenerateRecommendations generates alignment recommendations for context
	GenerateRecommendations(ctx context.Context, node *slurpContext.ContextNode) ([]*AlignmentRecommendation, error)
	
	// GenerateGoalRecommendations generates recommendations for a specific goal
	GenerateGoalRecommendations(ctx context.Context, goalID string) ([]*GoalRecommendation, error)
	
	// GenerateStrategicRecommendations generates high-level strategic recommendations
	GenerateStrategicRecommendations(ctx context.Context) ([]*StrategicRecommendation, error)
	
	// PrioritizeRecommendations prioritizes recommendations by impact and effort
	PrioritizeRecommendations(ctx context.Context, recommendations []*AlignmentRecommendation) ([]*PrioritizedRecommendation, error)
	
	// GetRecommendationHistory gets history of generated recommendations
	GetRecommendationHistory(ctx context.Context, address ucxl.Address) ([]*RecommendationHistory, error)
	
	// TrackRecommendationImplementation tracks implementation of recommendations
	TrackRecommendationImplementation(ctx context.Context, recommendationID string, status ImplementationStatus) error
	
	// AnalyzeRecommendationEffectiveness analyzes effectiveness of past recommendations
	AnalyzeRecommendationEffectiveness(ctx context.Context) (*RecommendationEffectiveness, error)
	
	// GetRecommendationStats returns recommendation generation statistics
	GetRecommendationStats() (*RecommendationStatistics, error)
}

// MetricsCollector collects and analyzes alignment metrics
//
// Gathers comprehensive metrics on goal alignment, progress, and
// effectiveness to provide insights into project strategic health
// and alignment performance.
type MetricsCollector interface {
	// CollectAlignmentMetrics collects comprehensive alignment metrics
	CollectAlignmentMetrics(ctx context.Context) (*AlignmentMetrics, error)
	
	// CollectGoalMetrics collects goal-specific metrics
	CollectGoalMetrics(ctx context.Context, goalID string) (*GoalMetrics, error)
	
	// CollectProgressMetrics collects progress tracking metrics
	CollectProgressMetrics(ctx context.Context) (*ProgressMetrics, error)
	
	// GetMetricsTrends gets trends for alignment metrics
	GetMetricsTrends(ctx context.Context, metricType string, timeRange time.Duration) (*MetricsTrends, error)
	
	// GenerateMetricsReport generates comprehensive metrics report
	GenerateMetricsReport(ctx context.Context, reportType string) (*MetricsReport, error)
	
	// SetMetricsConfiguration configures metrics collection parameters
	SetMetricsConfiguration(config *MetricsConfiguration) error
	
	// GetMetricsConfiguration gets current metrics configuration
	GetMetricsConfiguration() (*MetricsConfiguration, error)
	
	// ExportMetrics exports metrics data in various formats
	ExportMetrics(ctx context.Context, format string, timeRange time.Duration) ([]byte, error)
}

// GoalSynchronizer synchronizes with external project management systems
type GoalSynchronizer interface {
	// SyncWithExternal synchronizes goals with external systems
	SyncWithExternal(ctx context.Context, systemType string) (*SyncResult, error)
	
	// ImportGoals imports goals from external systems
	ImportGoals(ctx context.Context, source string, data []byte) (*ImportResult, error)
	
	// ExportGoals exports goals to external systems
	ExportGoals(ctx context.Context, format string) ([]byte, error)
	
	// ConfigureSyncSettings configures synchronization settings
	ConfigureSyncSettings(settings *SyncSettings) error
	
	// GetSyncStatus gets current synchronization status
	GetSyncStatus(ctx context.Context) (*SyncStatus, error)
}

// AlignmentValidator validates alignment assessments and configurations
type AlignmentValidator interface {
	// ValidateAssessment validates an alignment assessment
	ValidateAssessment(ctx context.Context, assessment *AlignmentAssessment) (*AssessmentValidation, error)
	
	// ValidateGoalConfiguration validates goal configuration
	ValidateGoalConfiguration(ctx context.Context, goal *ProjectGoal) (*ConfigurationValidation, error)
	
	// ValidateAlignmentWeights validates alignment weight configuration
	ValidateAlignmentWeights(weights *AlignmentWeights) (*WeightsValidation, error)
	
	// CheckConsistency checks consistency across goals and assessments
	CheckConsistency(ctx context.Context) ([]*ConsistencyIssue, error)
	
	// PerformHealthCheck performs overall alignment system health check
	PerformHealthCheck(ctx context.Context) (*AlignmentHealthCheck, error)
}

// NotificationManager handles alignment-related notifications and alerts
type NotificationManager interface {
	// SendDriftAlert sends alert for detected alignment drift
	SendDriftAlert(ctx context.Context, drift *AlignmentDrift, recipients []string) error
	
	// SendProgressUpdate sends goal progress update notification
	SendProgressUpdate(ctx context.Context, goalID string, progress *GoalProgress, recipients []string) error
	
	// SendRecommendationNotification sends notification about new recommendations
	SendRecommendationNotification(ctx context.Context, recommendations []*AlignmentRecommendation, recipients []string) error
	
	// ConfigureNotificationRules configures notification rules and preferences
	ConfigureNotificationRules(rules *NotificationRules) error
	
	// GetNotificationHistory gets history of sent notifications
	GetNotificationHistory(ctx context.Context, timeRange time.Duration) ([]*NotificationRecord, error)
	
	// SubscribeToAlerts subscribes to specific types of alignment alerts
	SubscribeToAlerts(ctx context.Context, subscriberID string, alertTypes []string) error
	
	// UnsubscribeFromAlerts unsubscribes from alignment alerts
	UnsubscribeFromAlerts(ctx context.Context, subscriberID string, alertTypes []string) error
}