package leader

import (
	"time"

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

// Priority represents priority levels for context generation requests
type Priority int

const (
	PriorityLow      Priority = iota // Low priority
	PriorityNormal                   // Normal priority
	PriorityHigh                     // High priority
	PriorityCritical                 // Critical priority
	PriorityUrgent                   // Urgent priority
)

// JobStatus represents status of context generation jobs
type JobStatus string

const (
	JobStatusPending   JobStatus = "pending"   // Job is pending
	JobStatusRunning   JobStatus = "running"   // Job is running
	JobStatusCompleted JobStatus = "completed" // Job completed successfully
	JobStatusFailed    JobStatus = "failed"    // Job failed
	JobStatusCancelled JobStatus = "cancelled" // Job was cancelled
	JobStatusTimeout   JobStatus = "timeout"   // Job timed out
)

// ContextGenerationRequest represents a request for context generation
type ContextGenerationRequest struct {
	ID          string       `json:"id"`           // Request ID
	UCXLAddress ucxl.Address `json:"ucxl_address"` // UCXL address for context
	FilePath    string       `json:"file_path"`    // File path to analyze
	Priority    Priority     `json:"priority"`     // Request priority
	RequestedBy string       `json:"requested_by"` // Who requested this
	Role        string       `json:"role"`         // Role context is for
	Options     *GenerationOptions `json:"options,omitempty"` // Generation options
	CreatedAt   time.Time    `json:"created_at"`   // When request was created
	Deadline    *time.Time   `json:"deadline,omitempty"` // Request deadline
	Metadata    map[string]interface{} `json:"metadata,omitempty"` // Additional metadata
}

// GenerationOptions represents options for context generation
type GenerationOptions struct {
	AnalyzeContent    bool     `json:"analyze_content"`     // Analyze file content
	AnalyzeStructure  bool     `json:"analyze_structure"`   // Analyze directory structure
	AnalyzeHistory    bool     `json:"analyze_history"`     // Analyze git history
	AnalyzeDependencies bool   `json:"analyze_dependencies"` // Analyze dependencies
	UseRAG            bool     `json:"use_rag"`             // Use RAG enhancement
	MaxDepth          int      `json:"max_depth"`           // Maximum analysis depth
	IncludePatterns   []string `json:"include_patterns"`    // File patterns to include
	ExcludePatterns   []string `json:"exclude_patterns"`    // File patterns to exclude
	MinConfidence     float64  `json:"min_confidence"`      // Minimum confidence threshold
	Timeout           time.Duration `json:"timeout"`        // Generation timeout
}

// ContextGenerationJob represents an active or completed context generation job
type ContextGenerationJob struct {
	ID          string                    `json:"id"`           // Job ID
	Request     *ContextGenerationRequest `json:"request"`      // Original request
	Status      JobStatus                 `json:"status"`       // Current status
	StartedAt   time.Time                 `json:"started_at"`   // When job started
	CompletedAt *time.Time                `json:"completed_at,omitempty"` // When job completed
	Result      *slurpContext.ContextNode `json:"result,omitempty"` // Generated context
	Error       error                     `json:"error,omitempty"` // Error if failed
	Progress    float64                   `json:"progress"`     // Job progress (0-1)
	NodeID      string                    `json:"node_id"`      // Node processing the job
	ResourcesUsed *ResourceUsage          `json:"resources_used,omitempty"` // Resources used
	Metrics     *JobMetrics              `json:"metrics,omitempty"` // Job metrics
}

// ContextGenerationResult represents result of context generation request
type ContextGenerationResult struct {
	RequestID   string                    `json:"request_id"`    // Original request ID
	Success     bool                      `json:"success"`       // Whether generation succeeded
	Context     *slurpContext.ContextNode `json:"context,omitempty"` // Generated context
	Error       string                    `json:"error,omitempty"` // Error message if failed
	GeneratedAt time.Time                 `json:"generated_at"`  // When context was generated
	GeneratedBy string                    `json:"generated_by"`  // Node that generated context
	Metrics     *GenerationMetrics        `json:"metrics,omitempty"` // Generation metrics
}

// GenerationStatus represents status of context generation operations
type GenerationStatus struct {
	ActiveTasks         int        `json:"active_tasks"`          // Number of active tasks
	QueuedTasks         int        `json:"queued_tasks"`          // Number of queued tasks
	CompletedTasks      int        `json:"completed_tasks"`       // Number of completed tasks
	FailedTasks         int        `json:"failed_tasks"`          // Number of failed tasks
	EstimatedCompletion time.Time  `json:"estimated_completion"`  // Estimated completion time
	CurrentTask         *ContextGenerationJob `json:"current_task,omitempty"` // Current task
	IsLeader            bool       `json:"is_leader"`             // Whether this node is leader
	LeaderID            string     `json:"leader_id"`             // Current leader node ID
	LastUpdate          time.Time  `json:"last_update"`           // When status was last updated
}

// QueueStatus represents status of the generation queue
type QueueStatus struct {
	QueueLength         int                        `json:"queue_length"`          // Current queue length
	MaxQueueSize        int                        `json:"max_queue_size"`        // Maximum queue size
	QueuedRequests      []*ContextGenerationRequest `json:"queued_requests"`     // Queued requests
	PriorityDistribution map[Priority]int          `json:"priority_distribution"` // Distribution by priority
	AverageWaitTime     time.Duration              `json:"average_wait_time"`     // Average wait time
	OldestRequest       *time.Time                 `json:"oldest_request,omitempty"` // Oldest request time
}

// LeaderInfo represents information about current leader
type LeaderInfo struct {
	NodeID              string    `json:"node_id"`               // Leader node ID
	Address             string    `json:"address"`               // Leader network address
	ElectedAt           time.Time `json:"elected_at"`            // When elected as leader
	Term                int64     `json:"term"`                  // Leadership term
	ActiveSince         time.Duration `json:"active_since"`      // How long active as leader
	GenerationCapacity  int       `json:"generation_capacity"`  // Generation capacity
	CurrentLoad         float64   `json:"current_load"`         // Current load (0-1)
	HealthStatus        string    `json:"health_status"`        // Health status
	Version             string    `json:"version"`              // Software version
}

// CoordinationResult represents result of generation coordination
type CoordinationResult struct {
	TaskID              string                 `json:"task_id"`               // Assigned task ID
	AssignedNode        string                 `json:"assigned_node"`         // Node assigned to task
	EstimatedCompletion time.Time              `json:"estimated_completion"`  // Estimated completion
	CoordinatedAt       time.Time              `json:"coordinated_at"`        // When coordination occurred
	ResourcesAllocated  *ResourceAllocation    `json:"resources_allocated"`   // Resources allocated
	Dependencies        []string               `json:"dependencies"`          // Task dependencies
}

// GenerationTask represents a distributed generation task
type GenerationTask struct {
	ID          string                    `json:"id"`           // Task ID
	Request     *ContextGenerationRequest `json:"request"`      // Generation request
	NodeID      string                    `json:"node_id"`      // Assigned node ID
	Priority    Priority                  `json:"priority"`     // Task priority
	Dependencies []string                 `json:"dependencies"` // Task dependencies
	Resources   *ResourceAllocation       `json:"resources"`    // Allocated resources
	CreatedAt   time.Time                 `json:"created_at"`   // When task was created
	StartedAt   *time.Time                `json:"started_at,omitempty"` // When task started
	Deadline    *time.Time                `json:"deadline,omitempty"` // Task deadline
	Metadata    map[string]interface{}    `json:"metadata,omitempty"` // Additional metadata
}

// GenerationResults represents results from distributed generation
type GenerationResults struct {
	TaskID      string                   `json:"task_id"`       // Task ID
	Results     []*GenerationResult      `json:"results"`       // Individual results
	Aggregated  *slurpContext.ContextNode `json:"aggregated"`   // Aggregated context
	Success     bool                     `json:"success"`       // Whether overall successful
	CompletedAt time.Time                `json:"completed_at"`  // When completed
	Duration    time.Duration            `json:"duration"`      // Total duration
	Errors      []string                 `json:"errors,omitempty"` // Any errors
}

// GenerationResult represents result from single node generation
type GenerationResult struct {
	NodeID      string                    `json:"node_id"`       // Node that generated
	Context     *slurpContext.ContextNode `json:"context"`       // Generated context
	Success     bool                      `json:"success"`       // Whether successful
	Error       string                    `json:"error,omitempty"` // Error if failed
	Duration    time.Duration             `json:"duration"`      // Generation duration
	Resources   *ResourceUsage            `json:"resources"`     // Resources used
	Confidence  float64                   `json:"confidence"`    // Result confidence
}

// TaskStatus represents status of distributed task
type TaskStatus struct {
	TaskID      string                 `json:"task_id"`       // Task ID
	Status      JobStatus              `json:"status"`        // Current status
	NodeID      string                 `json:"node_id"`       // Assigned node
	Progress    float64                `json:"progress"`      // Progress (0-1)
	StartedAt   *time.Time             `json:"started_at,omitempty"` // When started
	UpdatedAt   time.Time              `json:"updated_at"`    // When status updated
	Metadata    map[string]interface{} `json:"metadata,omitempty"` // Status metadata
}

// ClusterCapacity represents cluster generation capacity
type ClusterCapacity struct {
	TotalNodes          int                    `json:"total_nodes"`           // Total nodes in cluster
	ActiveNodes         int                    `json:"active_nodes"`          // Active nodes
	TotalCapacity       int                    `json:"total_capacity"`        // Total generation capacity
	AvailableCapacity   int                    `json:"available_capacity"`    // Available capacity
	NodeCapacities      map[string]*NodeCapacity `json:"node_capacities"`     // Per-node capacities
	LoadDistribution    map[string]float64     `json:"load_distribution"`     // Load distribution
	BottleneckNodes     []string               `json:"bottleneck_nodes"`      // Bottleneck nodes
	UnderutilizedNodes  []string               `json:"underutilized_nodes"`   // Underutilized nodes
	LastUpdated         time.Time              `json:"last_updated"`          // When last updated
}

// NodeCapacity represents capacity of individual node
type NodeCapacity struct {
	NodeID              string    `json:"node_id"`               // Node ID
	MaxConcurrentTasks  int       `json:"max_concurrent_tasks"`  // Maximum concurrent tasks
	CurrentTasks        int       `json:"current_tasks"`         // Current active tasks
	AvailableCapacity   int       `json:"available_capacity"`    // Available capacity
	AverageTaskTime     time.Duration `json:"average_task_time"` // Average task completion time
	SuccessRate         float64   `json:"success_rate"`          // Task success rate
	LoadAverage         float64   `json:"load_average"`          // System load average
	HealthScore         float64   `json:"health_score"`          // Node health score
	LastHeartbeat       time.Time `json:"last_heartbeat"`        // Last heartbeat
}

// RebalanceResult represents result of load rebalancing
type RebalanceResult struct {
	TasksMoved          int                    `json:"tasks_moved"`           // Number of tasks moved
	NodesAffected       []string               `json:"nodes_affected"`        // Nodes affected by rebalance
	LoadImprovement     float64                `json:"load_improvement"`      // Load distribution improvement
	RebalanceTime       time.Duration          `json:"rebalance_time"`        // Time taken for rebalance
	BeforeDistribution  map[string]float64     `json:"before_distribution"`   // Load before rebalance
	AfterDistribution   map[string]float64     `json:"after_distribution"`    // Load after rebalance
	RebalancedAt        time.Time              `json:"rebalanced_at"`         // When rebalance occurred
}

// GenerationPolicy represents policy for generation coordination
type GenerationPolicy struct {
	MaxConcurrentTasks  int           `json:"max_concurrent_tasks"`  // Max concurrent tasks per node
	LoadBalancingStrategy string      `json:"load_balancing_strategy"` // Load balancing strategy
	RebalanceThreshold  float64       `json:"rebalance_threshold"`   // Threshold for rebalancing
	RebalanceInterval   time.Duration `json:"rebalance_interval"`    // Rebalancing interval
	FailoverTimeout     time.Duration `json:"failover_timeout"`      // Node failover timeout
	RetryPolicy         *RetryPolicy  `json:"retry_policy"`          // Task retry policy
	PriorityWeights     map[Priority]float64 `json:"priority_weights"` // Priority weights
	ResourceLimits      *ResourceLimits `json:"resource_limits"`     // Resource usage limits
}

// RetryPolicy represents policy for retrying failed tasks
type RetryPolicy struct {
	MaxRetries      int           `json:"max_retries"`       // Maximum retry attempts
	InitialDelay    time.Duration `json:"initial_delay"`     // Initial delay before retry
	BackoffFactor   float64       `json:"backoff_factor"`    // Exponential backoff factor
	MaxDelay        time.Duration `json:"max_delay"`         // Maximum delay between retries
	RetryableErrors []string      `json:"retryable_errors"`  // Error codes that can be retried
}

// QueuePolicy represents policy for queue management
type QueuePolicy struct {
	MaxQueueSize        int           `json:"max_queue_size"`        // Maximum queue size
	PriorityScheduling  bool          `json:"priority_scheduling"`   // Enable priority scheduling
	FairScheduling      bool          `json:"fair_scheduling"`       // Enable fair scheduling
	MaxWaitTime         time.Duration `json:"max_wait_time"`         // Maximum wait time
	DeadlineScheduling  bool          `json:"deadline_scheduling"`   // Enable deadline scheduling
	DrainTimeout        time.Duration `json:"drain_timeout"`         // Timeout for draining queue
}

// FailoverState represents state to transfer during failover
type FailoverState struct {
	LeaderID            string                      `json:"leader_id"`             // Previous leader ID
	Term                int64                       `json:"term"`                  // Leadership term
	QueuedRequests      []*ContextGenerationRequest `json:"queued_requests"`       // Queued requests
	ActiveJobs          map[string]*ContextGenerationJob `json:"active_jobs"`      // Active jobs
	ClusterState        *ClusterState               `json:"cluster_state"`         // Cluster state
	ResourceAllocations map[string]*ResourceAllocation `json:"resource_allocations"` // Resource allocations
	LastActivity        time.Time                   `json:"last_activity"`         // Last activity time
	StateVersion        int64                       `json:"state_version"`         // State version
	Checksum            string                      `json:"checksum"`              // State checksum
	CreatedAt           time.Time                   `json:"created_at"`            // When state was created
}

// StateValidation represents result of failover state validation
type StateValidation struct {
	Valid               bool      `json:"valid"`                // Whether state is valid
	Issues              []string  `json:"issues,omitempty"`     // Validation issues
	ChecksumValid       bool      `json:"checksum_valid"`       // Whether checksum is valid
	VersionConsistent   bool      `json:"version_consistent"`   // Whether version is consistent
	TimestampValid      bool      `json:"timestamp_valid"`      // Whether timestamps are valid
	ValidatedAt         time.Time `json:"validated_at"`         // When validation occurred
}

// RecoveryResult represents result of failover recovery
type RecoveryResult struct {
	RecoveredRequests   int       `json:"recovered_requests"`    // Number of recovered requests
	RecoveredJobs       int       `json:"recovered_jobs"`        // Number of recovered jobs
	LostRequests        int       `json:"lost_requests"`         // Number of lost requests
	LostJobs            int       `json:"lost_jobs"`             // Number of lost jobs
	RecoveryTime        time.Duration `json:"recovery_time"`     // Time taken for recovery
	RecoveredAt         time.Time `json:"recovered_at"`          // When recovery completed
	Issues              []string  `json:"issues,omitempty"`      // Recovery issues
}

// FailoverEvent represents a failover event
type FailoverEvent struct {
	EventID             string    `json:"event_id"`              // Event ID
	EventType           string    `json:"event_type"`            // Type of failover event
	OldLeaderID         string    `json:"old_leader_id"`         // Previous leader
	NewLeaderID         string    `json:"new_leader_id"`         // New leader
	Term                int64     `json:"term"`                  // Leadership term
	Reason              string    `json:"reason"`                // Reason for failover
	Duration            time.Duration `json:"duration"`          // Failover duration
	StateTransferred    bool      `json:"state_transferred"`     // Whether state was transferred
	OccurredAt          time.Time `json:"occurred_at"`           // When failover occurred
	Impact              string    `json:"impact"`                // Impact assessment
}

// ClusterState represents current state of the cluster
type ClusterState struct {
	ClusterID           string                 `json:"cluster_id"`            // Cluster ID
	LeaderID            string                 `json:"leader_id"`             // Current leader
	Term                int64                  `json:"term"`                  // Current term
	TotalNodes          int                    `json:"total_nodes"`           // Total nodes
	ActiveNodes         []string               `json:"active_nodes"`          // Active nodes
	InactiveNodes       []string               `json:"inactive_nodes"`        // Inactive nodes
	NodeStates          map[string]*NodeState  `json:"node_states"`           // Individual node states
	ClusterHealth       float64                `json:"cluster_health"`        // Overall cluster health
	LastElection        time.Time              `json:"last_election"`         // Last election time
	LastStateChange     time.Time              `json:"last_state_change"`     // Last state change
	StateVersion        int64                  `json:"state_version"`         // State version
}

// NodeState represents state of individual node
type NodeState struct {
	NodeID              string    `json:"node_id"`               // Node ID
	Status              string    `json:"status"`                // Node status
	Address             string    `json:"address"`               // Network address
	Role                string    `json:"role"`                  // Node role
	LastHeartbeat       time.Time `json:"last_heartbeat"`        // Last heartbeat
	Version             string    `json:"version"`               // Software version
	LoadAverage         float64   `json:"load_average"`          // Load average
	ActiveTasks         int       `json:"active_tasks"`          // Active tasks
	HealthScore         float64   `json:"health_score"`          // Health score
	JoinedAt            time.Time `json:"joined_at"`             // When node joined
}

// NodeHealth represents health status of a node
type NodeHealth struct {
	NodeID              string                 `json:"node_id"`               // Node ID
	Status              string                 `json:"status"`                // Health status
	Score               float64                `json:"score"`                 // Health score (0-1)
	Issues              []*HealthIssue         `json:"issues,omitempty"`      // Health issues
	Metrics             *NodeMetrics           `json:"metrics"`               // Node metrics
	LastCheck           time.Time              `json:"last_check"`            // Last health check
	Uptime              time.Duration          `json:"uptime"`                // Node uptime
	ResponseTime        time.Duration          `json:"response_time"`         // Response time
}

// HealthIssue represents a health issue
type HealthIssue struct {
	Type        string    `json:"type"`         // Issue type
	Severity    string    `json:"severity"`     // Issue severity
	Message     string    `json:"message"`      // Issue message
	DetectedAt  time.Time `json:"detected_at"`  // When detected
	Count       int       `json:"count"`        // Issue occurrence count
}

// NodeMetrics represents metrics for a node
type NodeMetrics struct {
	CPUUsage            float64   `json:"cpu_usage"`             // CPU usage percentage
	MemoryUsage         float64   `json:"memory_usage"`          // Memory usage percentage
	DiskUsage           float64   `json:"disk_usage"`            // Disk usage percentage
	NetworkLatency      time.Duration `json:"network_latency"`   // Network latency
	ActiveConnections   int       `json:"active_connections"`    // Active connections
	TaskThroughput      float64   `json:"task_throughput"`       // Tasks per second
	ErrorRate           float64   `json:"error_rate"`            // Error rate
	CollectedAt         time.Time `json:"collected_at"`          // When metrics were collected
}

// ClusterMessage represents a message broadcast to cluster
type ClusterMessage struct {
	MessageID           string                 `json:"message_id"`            // Message ID
	Type                string                 `json:"type"`                  // Message type
	From                string                 `json:"from"`                  // Sender node ID
	To                  []string               `json:"to"`                    // Target nodes (empty for broadcast)
	Payload             map[string]interface{} `json:"payload"`               // Message payload
	Priority            Priority               `json:"priority"`              // Message priority
	CreatedAt           time.Time              `json:"created_at"`            // When message was created
	ExpiresAt           *time.Time             `json:"expires_at,omitempty"`  // When message expires
	ReplyRequired       bool                   `json:"reply_required"`        // Whether reply is required
	ReplyTimeout        *time.Duration         `json:"reply_timeout,omitempty"` // Reply timeout
}

// SyncResult represents result of cluster synchronization
type SyncResult struct {
	SyncedNodes         []string      `json:"synced_nodes"`          // Successfully synced nodes
	FailedNodes         []string      `json:"failed_nodes"`          // Failed to sync nodes
	SyncTime            time.Duration `json:"sync_time"`             // Time taken for sync
	DataSynced          int64         `json:"data_synced"`           // Amount of data synced
	ConflictsResolved   int           `json:"conflicts_resolved"`    // Number of conflicts resolved
	SyncedAt            time.Time     `json:"synced_at"`             // When sync occurred
	Errors              []string      `json:"errors,omitempty"`      // Sync errors
}

// NodeInfo represents information about a cluster node
type NodeInfo struct {
	NodeID              string                 `json:"node_id"`               // Node ID
	Address             string                 `json:"address"`               // Network address
	Role                string                 `json:"role"`                  // Node role
	Capabilities        []string               `json:"capabilities"`          // Node capabilities
	Version             string                 `json:"version"`               // Software version
	Metadata            map[string]interface{} `json:"metadata"`              // Additional metadata
	JoinedAt            time.Time              `json:"joined_at"`             // When node joined
}

// ResourceRequest represents a request for resource allocation
type ResourceRequest struct {
	RequestID           string                 `json:"request_id"`            // Request ID
	RequestedBy         string                 `json:"requested_by"`          // Who requested resources
	CPU                 float64                `json:"cpu"`                   // Requested CPU cores
	Memory              int64                  `json:"memory"`                // Requested memory in bytes
	Storage             int64                  `json:"storage"`               // Requested storage in bytes
	NetworkBandwidth    int64                  `json:"network_bandwidth"`     // Requested network bandwidth
	Duration            *time.Duration         `json:"duration,omitempty"`    // Expected usage duration
	Priority            Priority               `json:"priority"`              // Request priority
	Requirements        map[string]interface{} `json:"requirements"`          // Additional requirements
	CreatedAt           time.Time              `json:"created_at"`            // When request was created
}

// ResourceAllocation represents allocated resources
type ResourceAllocation struct {
	AllocationID        string                 `json:"allocation_id"`         // Allocation ID
	RequestID           string                 `json:"request_id"`            // Original request ID
	NodeID              string                 `json:"node_id"`               // Allocated node
	AllocatedCPU        float64                `json:"allocated_cpu"`         // Allocated CPU cores
	AllocatedMemory     int64                  `json:"allocated_memory"`      // Allocated memory
	AllocatedStorage    int64                  `json:"allocated_storage"`     // Allocated storage
	AllocatedBandwidth  int64                  `json:"allocated_bandwidth"`   // Allocated bandwidth
	AllocationTime      time.Duration          `json:"allocation_time"`       // How long allocated for
	AllocatedAt         time.Time              `json:"allocated_at"`          // When resources were allocated
	ExpiresAt           *time.Time             `json:"expires_at,omitempty"`  // When allocation expires
	Status              string                 `json:"status"`                // Allocation status
}

// AvailableResources represents currently available resources
type AvailableResources struct {
	TotalNodes          int                    `json:"total_nodes"`           // Total nodes
	AvailableNodes      int                    `json:"available_nodes"`       // Available nodes
	TotalCPU            float64                `json:"total_cpu"`             // Total CPU cores
	AvailableCPU        float64                `json:"available_cpu"`         // Available CPU cores
	TotalMemory         int64                  `json:"total_memory"`          // Total memory
	AvailableMemory     int64                  `json:"available_memory"`      // Available memory
	TotalStorage        int64                  `json:"total_storage"`         // Total storage
	AvailableStorage    int64                  `json:"available_storage"`     // Available storage
	TotalBandwidth      int64                  `json:"total_bandwidth"`       // Total bandwidth
	AvailableBandwidth  int64                  `json:"available_bandwidth"`   // Available bandwidth
	NodeResources       map[string]*NodeResources `json:"node_resources"`     // Per-node resources
	LastUpdated         time.Time              `json:"last_updated"`          // When last updated
}

// NodeResources represents resources for a specific node
type NodeResources struct {
	NodeID              string    `json:"node_id"`               // Node ID
	TotalCPU            float64   `json:"total_cpu"`             // Total CPU cores
	AvailableCPU        float64   `json:"available_cpu"`         // Available CPU cores
	TotalMemory         int64     `json:"total_memory"`          // Total memory
	AvailableMemory     int64     `json:"available_memory"`      // Available memory
	TotalStorage        int64     `json:"total_storage"`         // Total storage
	AvailableStorage    int64     `json:"available_storage"`     // Available storage
	TotalBandwidth      int64     `json:"total_bandwidth"`       // Total bandwidth
	AvailableBandwidth  int64     `json:"available_bandwidth"`   // Available bandwidth
	LoadAverage         float64   `json:"load_average"`          // System load average
	LastUpdated         time.Time `json:"last_updated"`          // When last updated
}

// ResourceLimits represents limits for resource usage
type ResourceLimits struct {
	MaxCPUPerTask       float64   `json:"max_cpu_per_task"`      // Max CPU per task
	MaxMemoryPerTask    int64     `json:"max_memory_per_task"`   // Max memory per task
	MaxStoragePerTask   int64     `json:"max_storage_per_task"`  // Max storage per task
	MaxBandwidthPerTask int64     `json:"max_bandwidth_per_task"` // Max bandwidth per task
	MaxTasksPerNode     int       `json:"max_tasks_per_node"`    // Max tasks per node
	MaxTotalTasks       int       `json:"max_total_tasks"`       // Max total cluster tasks
	ResourceQuotas      map[string]*ResourceQuota `json:"resource_quotas"` // Per-user quotas
	LastUpdated         time.Time `json:"last_updated"`          // When limits were updated
}

// ResourceQuota represents resource quota for user/role
type ResourceQuota struct {
	UserID              string    `json:"user_id"`               // User ID
	Role                string    `json:"role"`                  // Role
	MaxConcurrentTasks  int       `json:"max_concurrent_tasks"`  // Max concurrent tasks
	MaxCPU              float64   `json:"max_cpu"`               // Max CPU cores
	MaxMemory           int64     `json:"max_memory"`            // Max memory
	MaxStorage          int64     `json:"max_storage"`           // Max storage
	MaxBandwidth        int64     `json:"max_bandwidth"`         // Max bandwidth
	MaxTasksPerHour     int       `json:"max_tasks_per_hour"`    // Max tasks per hour
	ResetPeriod         time.Duration `json:"reset_period"`      // Quota reset period
	LastReset           time.Time `json:"last_reset"`            // When quota was last reset
}

// ResourceUsage represents current resource usage statistics
type ResourceUsage struct {
	NodeID              string                 `json:"node_id,omitempty"`     // Node ID (if per-node)
	UsedCPU             float64                `json:"used_cpu"`              // Used CPU cores
	UsedMemory          int64                  `json:"used_memory"`           // Used memory
	UsedStorage         int64                  `json:"used_storage"`          // Used storage
	UsedBandwidth       int64                  `json:"used_bandwidth"`        // Used bandwidth
	ActiveTasks         int                    `json:"active_tasks"`          // Active tasks
	TaskDistribution    map[Priority]int       `json:"task_distribution"`     // Tasks by priority
	UserUsage           map[string]*UserUsage  `json:"user_usage"`            // Per-user usage
	LastUpdated         time.Time              `json:"last_updated"`          // When last updated
}

// UserUsage represents resource usage for specific user
type UserUsage struct {
	UserID              string    `json:"user_id"`               // User ID
	UsedCPU             float64   `json:"used_cpu"`              // Used CPU cores
	UsedMemory          int64     `json:"used_memory"`           // Used memory
	UsedStorage         int64     `json:"used_storage"`          // Used storage
	UsedBandwidth       int64     `json:"used_bandwidth"`        // Used bandwidth
	ActiveTasks         int       `json:"active_tasks"`          // Active tasks
	CompletedTasks      int       `json:"completed_tasks"`       // Completed tasks
	FailedTasks         int       `json:"failed_tasks"`          // Failed tasks
	LastActivity        time.Time `json:"last_activity"`         // Last activity
}

// ResourceRebalanceResult represents result of resource rebalancing
type ResourceRebalanceResult struct {
	TasksMoved          int                    `json:"tasks_moved"`           // Number of tasks moved
	NodesAffected       []string               `json:"nodes_affected"`        // Nodes affected
	ResourceFreed       map[string]interface{} `json:"resource_freed"`        // Resources freed up
	LoadImprovement     float64                `json:"load_improvement"`      // Load improvement
	RebalanceTime       time.Duration          `json:"rebalance_time"`        // Time taken
	RebalancedAt        time.Time              `json:"rebalanced_at"`         // When rebalanced
	Issues              []string               `json:"issues,omitempty"`      // Rebalancing issues
}

// ManagerConfig represents configuration for leader context manager
type ManagerConfig struct {
	LeadershipCheckInterval time.Duration `json:"leadership_check_interval"` // Leadership check frequency
	HealthCheckInterval     time.Duration `json:"health_check_interval"`     // Health check frequency
	ClusterSyncInterval     time.Duration `json:"cluster_sync_interval"`     // Cluster sync frequency
	MaxCompletedJobs        int           `json:"max_completed_jobs"`        // Max completed jobs to keep
	QueueSize               int           `json:"queue_size"`                // Generation queue size
	MaxConcurrentJobs       int           `json:"max_concurrent_jobs"`       // Max concurrent jobs
	JobTimeout              time.Duration `json:"job_timeout"`               // Job timeout
	EnableMetrics           bool          `json:"enable_metrics"`            // Enable metrics collection
	MetricsInterval         time.Duration `json:"metrics_interval"`          // Metrics collection interval
}

// ManagerStatistics represents statistics for leader context manager
type ManagerStatistics struct {
	TotalRequests       int64         `json:"total_requests"`        // Total requests received
	CompletedJobs       int64         `json:"completed_jobs"`        // Completed jobs
	FailedJobs          int64         `json:"failed_jobs"`           // Failed jobs
	CancelledJobs       int64         `json:"cancelled_jobs"`        // Cancelled jobs
	DroppedRequests     int64         `json:"dropped_requests"`      // Dropped requests
	AverageJobTime      time.Duration `json:"average_job_time"`      // Average job completion time
	LeadershipChanges   int64         `json:"leadership_changes"`    // Number of leadership changes
	LastBecameLeader    time.Time     `json:"last_became_leader"`    // When last became leader
	LastLostLeadership  time.Time     `json:"last_lost_leadership"`  // When last lost leadership
	CurrentLeaderTerm   int64         `json:"current_leader_term"`   // Current leadership term
	TotalLeaderTime     time.Duration `json:"total_leader_time"`     // Total time as leader
	HighestQueueLength  int           `json:"highest_queue_length"`  // Highest queue length seen
	LastStatsReset      time.Time     `json:"last_stats_reset"`      // When stats were last reset
}

// Additional supporting types

// JobMetrics represents metrics for individual job
type JobMetrics struct {
	AnalysisTime        time.Duration          `json:"analysis_time"`         // Time spent on analysis
	IOTime              time.Duration          `json:"io_time"`               // Time spent on I/O
	NetworkTime         time.Duration          `json:"network_time"`          // Time spent on network ops
	CPUTime             time.Duration          `json:"cpu_time"`              // CPU time used
	MemoryPeak          int64                  `json:"memory_peak"`           // Peak memory usage
	DiskReadBytes       int64                  `json:"disk_read_bytes"`       // Bytes read from disk
	DiskWriteBytes      int64                  `json:"disk_write_bytes"`      // Bytes written to disk
	NetworkBytes        int64                  `json:"network_bytes"`         // Network bytes transferred
	CacheHits           int                    `json:"cache_hits"`            // Cache hits
	CacheMisses         int                    `json:"cache_misses"`          // Cache misses
	AdditionalMetrics   map[string]interface{} `json:"additional_metrics"`    // Additional metrics
}

// GenerationMetrics represents metrics for context generation
type GenerationMetrics struct {
	FilesAnalyzed       int                    `json:"files_analyzed"`        // Number of files analyzed
	LinesAnalyzed       int                    `json:"lines_analyzed"`        // Lines of code analyzed
	TokensGenerated     int                    `json:"tokens_generated"`      // Tokens generated
	ConfidenceScore     float64                `json:"confidence_score"`      // Overall confidence
	QualityScore        float64                `json:"quality_score"`         // Quality score
	RAGQueriesPerformed int                    `json:"rag_queries_performed"` // RAG queries made
	PatternsDetected    int                    `json:"patterns_detected"`     // Patterns detected
	InsightsGenerated   int                    `json:"insights_generated"`    // Insights generated
	ErrorsEncountered   int                    `json:"errors_encountered"`    // Errors encountered
	WarningsGenerated   int                    `json:"warnings_generated"`    // Warnings generated
}

// CoordinationStatistics represents statistics for generation coordination
type CoordinationStatistics struct {
	TotalCoordinations  int64         `json:"total_coordinations"`   // Total coordinations
	SuccessfulCoordinations int64     `json:"successful_coordinations"` // Successful coordinations
	FailedCoordinations int64         `json:"failed_coordinations"`  // Failed coordinations
	AverageCoordinationTime time.Duration `json:"average_coordination_time"` // Average coordination time
	LoadBalanceOperations int64       `json:"load_balance_operations"` // Load balance operations
	TaskMigrations      int64         `json:"task_migrations"`       // Task migrations
	NodesCoordinated    int           `json:"nodes_coordinated"`     // Number of nodes coordinated
	LastCoordination    time.Time     `json:"last_coordination"`     // Last coordination time
}

// QueueStatistics represents statistics for queue management
type QueueStatistics struct {
	TotalEnqueued       int64         `json:"total_enqueued"`        // Total requests enqueued
	TotalDequeued       int64         `json:"total_dequeued"`        // Total requests dequeued
	CurrentQueueLength  int           `json:"current_queue_length"`  // Current queue length
	MaxQueueLength      int           `json:"max_queue_length"`      // Maximum queue length seen
	AverageWaitTime     time.Duration `json:"average_wait_time"`     // Average wait time
	MaxWaitTime         time.Duration `json:"max_wait_time"`         // Maximum wait time
	PriorityDistribution map[Priority]int64 `json:"priority_distribution"` // Enqueued by priority
	QueueOverflows      int64         `json:"queue_overflows"`       // Queue overflow events
	LastQueueOperation  time.Time     `json:"last_queue_operation"`  // Last queue operation
}

// FailoverStatistics represents statistics for failover operations
type FailoverStatistics struct {
	TotalFailovers      int64         `json:"total_failovers"`       // Total failover events
	SuccessfulFailovers int64         `json:"successful_failovers"`  // Successful failovers
	FailedFailovers     int64         `json:"failed_failovers"`      // Failed failovers
	AverageFailoverTime time.Duration `json:"average_failover_time"` // Average failover time
	MaxFailoverTime     time.Duration `json:"max_failover_time"`     // Maximum failover time
	StateTransfers      int64         `json:"state_transfers"`       // State transfers
	StateRecoveries     int64         `json:"state_recoveries"`      // State recoveries
	LastFailover        time.Time     `json:"last_failover"`         // Last failover time
	MeanTimeBetweenFailovers time.Duration `json:"mean_time_between_failovers"` // MTBF
}

// HealthEventHandler is a function type for handling health events
type HealthEventHandler func(event *HealthEvent)

// HealthEvent represents a health-related event
type HealthEvent struct {
	EventID     string                 `json:"event_id"`      // Event ID
	EventType   string                 `json:"event_type"`    // Type of health event
	NodeID      string                 `json:"node_id"`       // Affected node
	Severity    string                 `json:"severity"`      // Event severity
	Message     string                 `json:"message"`       // Event message
	Metadata    map[string]interface{} `json:"metadata"`      // Additional metadata
	OccurredAt  time.Time              `json:"occurred_at"`   // When event occurred
}