// Package election provides election interfaces and types
// This file contains shared interfaces to avoid circular dependencies.

package election

import (
	"context"
	"time"
)

// LeaderInfo represents information about the current leader
type LeaderInfo struct {
	NodeID      string    `json:"node_id"`      // Leader node ID
	Role        string    `json:"role"`         // Leader role
	Term        int64     `json:"term"`         // Election term
	ElectedAt   time.Time `json:"elected_at"`   // When elected
	LastSeen    time.Time `json:"last_seen"`    // Last heartbeat
	Capabilities []string `json:"capabilities"` // Leader capabilities
}

// GenerationStatus represents status of context generation operations
type GenerationStatus struct {
	IsGenerating    bool      `json:"is_generating"`    // Whether generation is active
	ActiveRequests  int       `json:"active_requests"`  // Number of active requests
	QueuedRequests  int       `json:"queued_requests"`  // Number of queued requests
	LastGeneration  time.Time `json:"last_generation"`  // Last generation time
	GenerationCount int64     `json:"generation_count"` // Total generations
	LeaderID        string    `json:"leader_id"`        // Current leader
}

// ContextGenerationRequest represents a request for context generation
type ContextGenerationRequest struct {
	ID          string                 `json:"id"`           // Request ID
	RequesterID string                 `json:"requester_id"` // Node requesting
	Priority    int                    `json:"priority"`     // Request priority
	Context     map[string]interface{} `json:"context"`      // Request context
	CreatedAt   time.Time              `json:"created_at"`   // Request creation time
	Deadline    *time.Time             `json:"deadline"`     // Optional deadline
}

// ContextGenerationResult represents the result of a context generation request
type ContextGenerationResult struct {
	RequestID   string    `json:"request_id"`   // Original request ID
	Success     bool      `json:"success"`      // Whether successful
	Error       string    `json:"error"`        // Error message if failed
	GeneratedAt time.Time `json:"generated_at"` // When generated
	GeneratedBy string    `json:"generated_by"` // Node that generated
	Context     []byte    `json:"context"`      // Generated context data
}

// ContextLeadershipCallbacks defines callbacks for context leadership events
type ContextLeadershipCallbacks struct {
	// OnBecomeContextLeader is called when this node becomes context leader
	OnBecomeContextLeader func(ctx context.Context, term int64) error
	
	// OnLoseContextLeadership is called when this node loses context leadership
	OnLoseContextLeadership func(ctx context.Context, newLeader string) error
	
	// OnContextLeaderChanged is called when any leadership change occurs
	OnContextLeaderChanged func(oldLeader, newLeader string, term int64)
	
	// OnContextGenerationStarted is called when context generation starts
	OnContextGenerationStarted func(leaderID string)
	
	// OnContextGenerationStopped is called when context generation stops
	OnContextGenerationStopped func(leaderID string, reason string)
	
	// OnContextFailover is called when context leadership failover occurs
	OnContextFailover func(oldLeader, newLeader string, duration time.Duration)
	
	// OnContextError is called when context-related errors occur
	OnContextError func(err error, severity ErrorSeverity)
}

// ErrorSeverity represents severity levels for election errors
type ErrorSeverity string

const (
	ErrorSeverityLow      ErrorSeverity = "low"      // Low severity error
	ErrorSeverityMedium   ErrorSeverity = "medium"   // Medium severity error
	ErrorSeverityHigh     ErrorSeverity = "high"     // High severity error
	ErrorSeverityCritical ErrorSeverity = "critical" // Critical error
)

// ContextManager defines interface for managing context generation
type ContextManager interface {
	// Context generation management
	RequestContextGeneration(req *ContextGenerationRequest) error
	GetGenerationStatus() (*GenerationStatus, error)
	StartGeneration(ctx context.Context) error
	StopGeneration(ctx context.Context) error
	
	// Leadership awareness
	IsLeader() bool
	SetLeader(isLeader bool)
	
	// Health and status
	GetHealth() (bool, error)
	GetMetrics() map[string]interface{}
}

// Additional types for context failover (simplified versions)

// ContextGenerationJob represents a context generation job
type ContextGenerationJob struct {
	ID          string                 `json:"id"`           // Job ID
	RequestID   string                 `json:"request_id"`   // Original request ID
	Status      string                 `json:"status"`       // Job status
	CreatedAt   time.Time              `json:"created_at"`   // Creation time
	UpdatedAt   time.Time              `json:"updated_at"`   // Last update
	CompletedAt *time.Time             `json:"completed_at"` // Completion time
	Context     map[string]interface{} `json:"context"`      // Job context
}

// ClusterState represents simplified cluster state
type ClusterState struct {
	Nodes         map[string]interface{} `json:"nodes"`          // Node states
	Leadership    map[string]string      `json:"leadership"`     // Leadership assignments
	LastUpdated   time.Time              `json:"last_updated"`   // Last state update
	StateVersion  int64                  `json:"state_version"`  // State version
}

// ResourceAllocation represents resource allocation
type ResourceAllocation struct {
	NodeID        string                 `json:"node_id"`        // Target node
	Resources     map[string]interface{} `json:"resources"`      // Allocated resources
	AllocatedAt   time.Time              `json:"allocated_at"`   // Allocation time
	ExpiresAt     *time.Time             `json:"expires_at"`     // Expiration time
}

// ManagerConfig represents manager configuration
type ManagerConfig struct {
	MaxConcurrentJobs int                    `json:"max_concurrent_jobs"` // Max concurrent jobs
	QueueSize         int                    `json:"queue_size"`          // Queue size limit
	TimeoutDuration   time.Duration          `json:"timeout_duration"`    // Job timeout
	Settings          map[string]interface{} `json:"settings"`            // Additional settings
}

// GenerationPolicy represents context generation policy
type GenerationPolicy struct {
	Priority     string                 `json:"priority"`      // Priority scheme
	MaxRetries   int                    `json:"max_retries"`   // Maximum retries
	BackoffType  string                 `json:"backoff_type"`  // Backoff strategy
	Settings     map[string]interface{} `json:"settings"`      // Policy settings
}

// QueuePolicy represents queue management policy
type QueuePolicy struct {
	Strategy    string                 `json:"strategy"`     // Queue strategy
	MaxSize     int                    `json:"max_size"`     // Maximum queue size
	DropPolicy  string                 `json:"drop_policy"`  // What to drop when full
	Settings    map[string]interface{} `json:"settings"`     // Queue settings
}

// DefaultManagerConfig returns default manager configuration
func DefaultManagerConfig() *ManagerConfig {
	return &ManagerConfig{
		MaxConcurrentJobs: 10,
		QueueSize:         100,
		TimeoutDuration:   30 * time.Minute,
		Settings:          make(map[string]interface{}),
	}
}