package heroic_ops

import (
	"sync"
	"time"
)

// HeroicOPStarter represents a starter chain for heroic opportunities
type HeroicOPStarter struct {
	mu          sync.RWMutex
	ID          int32    `json:"id"`           // Unique identifier for this starter
	StartClass  int8     `json:"start_class"`  // Class that can initiate this starter (0 = any)
	StarterIcon int16    `json:"starter_icon"` // Icon displayed for the starter
	Abilities   [6]int16 `json:"abilities"`    // Array of ability icons in sequence
	Name        string   `json:"name"`         // Display name for this starter
	Description string   `json:"description"`  // Description text
	SaveNeeded  bool     `json:"-"`            // Flag indicating if database save is needed
}

// HeroicOPWheel represents the wheel phase of a heroic opportunity
type HeroicOPWheel struct {
	mu              sync.RWMutex
	ID              int32    `json:"id"`               // Unique identifier for this wheel
	StarterLinkID   int32    `json:"starter_link_id"`  // ID of the starter this wheel belongs to
	Order           int8     `json:"order"`            // 0 = unordered, 1+ = ordered
	ShiftIcon       int16    `json:"shift_icon"`       // Icon that can shift/change the wheel
	Chance          float32  `json:"chance"`           // Probability factor for selecting this wheel
	Abilities       [6]int16 `json:"abilities"`        // Array of ability icons for the wheel
	SpellID         int32    `json:"spell_id"`         // Spell cast when HO completes successfully
	Name            string   `json:"name"`             // Display name for this wheel
	Description     string   `json:"description"`      // Description text
	RequiredPlayers int8     `json:"required_players"` // Minimum players required
	SaveNeeded      bool     `json:"-"`                // Flag indicating if database save is needed
}

// HeroicOP represents an active heroic opportunity instance
type HeroicOP struct {
	mu               sync.RWMutex
	ID               int64          `json:"id"`                // Unique instance ID
	EncounterID      int32          `json:"encounter_id"`      // Encounter this HO belongs to
	StarterID        int32          `json:"starter_id"`        // ID of the completed starter
	WheelID          int32          `json:"wheel_id"`          // ID of the active wheel
	State            int8           `json:"state"`             // Current HO state
	StartTime        time.Time      `json:"start_time"`        // When the HO started
	WheelStartTime   time.Time      `json:"wheel_start_time"`  // When wheel phase started
	TimeRemaining    int32          `json:"time_remaining"`    // Milliseconds remaining
	TotalTime        int32          `json:"total_time"`        // Total time allocated (ms)
	Complete         int8           `json:"complete"`          // Completion status (0/1)
	Countered        [6]int8        `json:"countered"`         // Which wheel abilities are completed
	ShiftUsed        int8           `json:"shift_used"`        // Whether shift has been used
	StarterProgress  int8           `json:"starter_progress"`  // Current position in starter chain
	Participants     map[int32]bool `json:"participants"`      // Character IDs that participated
	CurrentStarters  []int32        `json:"current_starters"`  // Active starter IDs during chain phase
	CompletedBy      int32          `json:"completed_by"`      // Character ID that completed the HO
	SpellName        string         `json:"spell_name"`        // Name of completion spell
	SpellDescription string         `json:"spell_description"` // Description of completion spell
	SaveNeeded       bool           `json:"-"`                 // Flag indicating if database save is needed
}

// HeroicOPProgress tracks progress during starter chain phase
type HeroicOPProgress struct {
	StarterID       int32 `json:"starter_id"`       // Starter being tracked
	CurrentPosition int8  `json:"current_position"` // Current position in the chain (0-5)
	IsEliminated    bool  `json:"is_eliminated"`    // Whether this starter has been eliminated
}

// HeroicOPData represents database record structure
type HeroicOPData struct {
	ID            int32   `json:"id"`
	HOType        string  `json:"ho_type"`         // "Starter" or "Wheel"
	StarterClass  int8    `json:"starter_class"`   // For starters
	StarterIcon   int16   `json:"starter_icon"`    // For starters
	StarterLinkID int32   `json:"starter_link_id"` // For wheels
	ChainOrder    int8    `json:"chain_order"`     // For wheels
	ShiftIcon     int16   `json:"shift_icon"`      // For wheels
	SpellID       int32   `json:"spell_id"`        // For wheels
	Chance        float32 `json:"chance"`          // For wheels
	Ability1      int16   `json:"ability1"`
	Ability2      int16   `json:"ability2"`
	Ability3      int16   `json:"ability3"`
	Ability4      int16   `json:"ability4"`
	Ability5      int16   `json:"ability5"`
	Ability6      int16   `json:"ability6"`
	Name          string  `json:"name"`
	Description   string  `json:"description"`
}

// MasterHeroicOPList manages all heroic opportunity configurations
type MasterHeroicOPList struct {
	mu sync.RWMutex
	// Structure: map[class]map[starter_id][]wheel
	starters map[int8]map[int32]*HeroicOPStarter
	wheels   map[int32][]*HeroicOPWheel // starter_id -> wheels
	spells   map[int32]SpellInfo        // spell_id -> spell info
	loaded   bool
}

// HeroicOPManager manages active heroic opportunity instances
type HeroicOPManager struct {
	mu             sync.RWMutex
	activeHOs      map[int64]*HeroicOP   // instance_id -> HO
	encounterHOs   map[int32][]*HeroicOP // encounter_id -> HOs
	masterList     *MasterHeroicOPList
	database       HeroicOPDatabase
	eventHandler   HeroicOPEventHandler
	logger         LogHandler
	nextInstanceID int64
	// Configuration
	defaultWheelTimer int32 // milliseconds
	maxConcurrentHOs  int
	enableLogging     bool
	enableStatistics  bool
}

// SpellInfo contains information about completion spells
type SpellInfo struct {
	ID          int32  `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Icon        int16  `json:"icon"`
}

// HeroicOPStatistics tracks system usage statistics
type HeroicOPStatistics struct {
	TotalHOsStarted       int64           `json:"total_hos_started"`
	TotalHOsCompleted     int64           `json:"total_hos_completed"`
	TotalHOsFailed        int64           `json:"total_hos_failed"`
	TotalHOsTimedOut      int64           `json:"total_hos_timed_out"`
	AverageCompletionTime float64         `json:"average_completion_time"` // seconds
	MostUsedStarter       int32           `json:"most_used_starter"`
	MostUsedWheel         int32           `json:"most_used_wheel"`
	SuccessRate           float64         `json:"success_rate"`     // percentage
	ShiftUsageRate        float64         `json:"shift_usage_rate"` // percentage
	ActiveHOCount         int             `json:"active_ho_count"`
	ParticipationStats    map[int32]int64 `json:"participation_stats"` // character_id -> HO count
}

// HeroicOPSearchCriteria for searching heroic opportunities
type HeroicOPSearchCriteria struct {
	StarterClass    int8    `json:"starter_class"`    // Filter by starter class (0 = any)
	SpellID         int32   `json:"spell_id"`         // Filter by completion spell
	MinChance       float32 `json:"min_chance"`       // Minimum wheel chance
	MaxChance       float32 `json:"max_chance"`       // Maximum wheel chance
	RequiredPlayers int8    `json:"required_players"` // Filter by player requirements
	NamePattern     string  `json:"name_pattern"`     // Filter by name pattern
	HasShift        bool    `json:"has_shift"`        // Filter by shift availability
	IsOrdered       bool    `json:"is_ordered"`       // Filter by wheel order type
}

// HeroicOPEvent represents an event in the HO system
type HeroicOPEvent struct {
	ID          int64     `json:"id"`
	InstanceID  int64     `json:"instance_id"`
	EventType   int       `json:"event_type"`
	CharacterID int32     `json:"character_id"`
	AbilityIcon int16     `json:"ability_icon"`
	Timestamp   time.Time `json:"timestamp"`
	Data        string    `json:"data"` // JSON encoded additional data
}

// PacketData represents data sent to client for HO display
type PacketData struct {
	SpellName        string   `json:"spell_name"`
	SpellDescription string   `json:"spell_description"`
	TimeRemaining    int32    `json:"time_remaining"` // milliseconds
	TotalTime        int32    `json:"total_time"`     // milliseconds
	Abilities        [6]int16 `json:"abilities"`      // Current wheel abilities
	Countered        [6]int8  `json:"countered"`      // Completion status
	Complete         int8     `json:"complete"`       // Overall completion (0/1)
	State            int8     `json:"state"`          // Current HO state
	CanShift         bool     `json:"can_shift"`      // Whether shift is available
	ShiftIcon        int16    `json:"shift_icon"`     // Icon for shift ability
}

// PlayerHOInfo contains player-specific HO information
type PlayerHOInfo struct {
	CharacterID       int32     `json:"character_id"`
	ParticipatingHOs  []int64   `json:"participating_hos"` // HO instance IDs
	LastActivity      time.Time `json:"last_activity"`
	TotalHOsJoined    int64     `json:"total_hos_joined"`
	TotalHOsCompleted int64     `json:"total_hos_completed"`
	SuccessRate       float64   `json:"success_rate"`
}

// Configuration structure for HO system
type HeroicOPConfig struct {
	DefaultWheelTimer   int32 `json:"default_wheel_timer"`   // milliseconds
	StarterChainTimeout int32 `json:"starter_chain_timeout"` // milliseconds
	MaxConcurrentHOs    int   `json:"max_concurrent_hos"`
	EnableLogging       bool  `json:"enable_logging"`
	EnableStatistics    bool  `json:"enable_statistics"`
	EnableShifting      bool  `json:"enable_shifting"`
	RequireClassMatch   bool  `json:"require_class_match"`   // Enforce starter class restrictions
	AutoCleanupInterval int32 `json:"auto_cleanup_interval"` // seconds
	MaxHistoryEntries   int   `json:"max_history_entries"`
}
