package ground_spawn

import (
	"sync"
	"time"

	"eq2emu/internal/spawn"
)

// GroundSpawn represents a harvestable resource node in the game world
type GroundSpawn struct {
	*spawn.Spawn // Embed spawn for base functionality

	numberHarvests        int8   // Number of harvests remaining
	numAttemptsPerHarvest int8   // Attempts per harvest session
	groundspawnID         int32  // Database ID for this groundspawn entry
	collectionSkill       string // Required skill for harvesting
	randomizeHeading      bool   // Whether to randomize heading on spawn

	harvestMutex    sync.Mutex // Thread safety for harvest operations
	harvestUseMutex sync.Mutex // Thread safety for use operations
}

// GroundSpawnEntry represents harvest table data from database
type GroundSpawnEntry struct {
	MinSkillLevel     int16   // Minimum skill level required
	MinAdventureLevel int16   // Minimum adventure level required
	BonusTable        bool    // Whether this is a bonus table
	Harvest1          float32 // Chance for 1 item (percentage)
	Harvest3          float32 // Chance for 3 items (percentage)
	Harvest5          float32 // Chance for 5 items (percentage)
	HarvestImbue      float32 // Chance for imbue item (percentage)
	HarvestRare       float32 // Chance for rare item (percentage)
	Harvest10         float32 // Chance for 10 + rare items (percentage)
	HarvestCoin       float32 // Chance for coin reward (percentage)
}

// GroundSpawnEntryItem represents items that can be harvested
type GroundSpawnEntryItem struct {
	ItemID   int32 // Item database ID
	IsRare   int8  // 0=normal, 1=rare, 2=imbue
	GridID   int32 // Grid restriction (0=any)
	Quantity int16 // Item quantity (usually 1)
}

// HarvestResult represents the outcome of a harvest attempt
type HarvestResult struct {
	Success      bool             // Whether harvest succeeded
	HarvestType  int8             // Type of harvest achieved
	ItemsAwarded []*HarvestedItem // Items given to player
	MessageText  string           // Message to display to player
	SkillGained  bool             // Whether skill was gained
	Error        error            // Any error that occurred
}

// HarvestedItem represents an item awarded from harvesting
type HarvestedItem struct {
	ItemID   int32  // Database item ID
	Quantity int16  // Number of items
	IsRare   bool   // Whether this is a rare item
	Name     string // Item name for messages
}

// HarvestContext contains all data needed for a harvest operation
type HarvestContext struct {
	Player             *Player                 // Player attempting harvest
	GroundSpawn        *GroundSpawn            // The ground spawn being harvested
	PlayerSkill        *Skill                  // Player's harvesting skill
	TotalSkill         int16                   // Total skill including bonuses
	GroundSpawnEntries []*GroundSpawnEntry     // Available harvest tables
	GroundSpawnItems   []*GroundSpawnEntryItem // Available harvest items
	IsCollection       bool                    // Whether this is collection harvesting
	MaxSkillRequired   int16                   // Maximum skill required for any table
}

// SpawnLocation represents a spawn position with grid information
type SpawnLocation struct {
	X       float32 // World X coordinate
	Y       float32 // World Y coordinate
	Z       float32 // World Z coordinate
	Heading float32 // Spawn heading/rotation
	GridID  int32   // Grid zone identifier
}

// HarvestModifiers contains modifiers that affect harvesting
type HarvestModifiers struct {
	SkillMultiplier    float32 // Skill gain multiplier
	RareChanceBonus    float32 // Bonus to rare item chance
	QuantityMultiplier float32 // Quantity multiplier
	LuckModifier       int16   // Player luck modifier
}

// GroundSpawnConfig contains configuration for ground spawn creation
type GroundSpawnConfig struct {
	GroundSpawnID      int32         // Database entry ID
	CollectionSkill    string        // Required harvesting skill
	NumberHarvests     int8          // Harvests before depletion
	AttemptsPerHarvest int8          // Attempts per harvest session
	RandomizeHeading   bool          // Randomize spawn heading
	RespawnTimer       time.Duration // Time before respawn
	Location           SpawnLocation // Spawn position
	Name               string        // Display name
	Description        string        // Spawn description
}

// Manager manages all ground spawn operations
type Manager struct {
	groundSpawns map[int32]*GroundSpawn            // Active ground spawns by ID
	spawnsByZone map[int32][]*GroundSpawn          // Ground spawns by zone ID
	entriesByID  map[int32][]*GroundSpawnEntry     // Harvest entries by groundspawn ID
	itemsByID    map[int32][]*GroundSpawnEntryItem // Harvest items by groundspawn ID
	respawnQueue map[int32]time.Time               // Respawn timestamps

	database Database // Database interface
	logger   Logger   // Logging interface

	mutex sync.RWMutex // Thread safety

	// Statistics
	totalHarvests      int64            // Total harvest attempts
	successfulHarvests int64            // Successful harvests
	rareItemsHarvested int64            // Rare items harvested
	skillUpsGenerated  int64            // Skill increases given
	harvestsBySkill    map[string]int64 // Harvests by skill type
}

// HarvestStatistics contains harvest system statistics
type HarvestStatistics struct {
	TotalHarvests      int64            `json:"total_harvests"`
	SuccessfulHarvests int64            `json:"successful_harvests"`
	RareItemsHarvested int64            `json:"rare_items_harvested"`
	SkillUpsGenerated  int64            `json:"skill_ups_generated"`
	HarvestsBySkill    map[string]int64 `json:"harvests_by_skill"`
	ActiveGroundSpawns int              `json:"active_ground_spawns"`
	GroundSpawnsByZone map[int32]int    `json:"ground_spawns_by_zone"`
}
