<?php

require_once __DIR__ . '/../../src/System/SaveManager.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';

class Tribe
{
    private $userId;
    private $saveId;
    private $name;
    public $kobolds = [];
    private $storage = [];
    private $currentMonth = 0;
    private $currentSeason = 'spring';
    private $foodCount = 0;
    private $createdAt;
    private $lastPlayed;
    private $saveManager;

    // Food requirement by age tier (portion units)
    private $foodRequirements = [
        'egg' => 0,        // Eggs don't eat
        'baby' => 0.5,     // Babies eat less
        'adult' => 1.0,    // Adults eat standard amount
        'old' => 0.6,      // Elderly eat less
        'very_old' => 0.4  // Very old eat even less
    ];

    public function __construct($userId, $saveId, $name = '')
    {
        $this->userId = $userId;
        $this->saveId = $saveId;
        $this->name = $name;
        $this->saveManager = new SaveManager();
        $this->loadFromFile();
    }

    public static function create($userId, $saveName)
    {
        $saveManager = new SaveManager();
        $saveId = $saveManager->generateSaveId($userId);

        $tribe = new self($userId, $saveId, $saveName);
        $tribe->createdAt = date('Y-m-d H:i:s');
        $tribe->lastPlayed = date('Y-m-d H:i:s');
        $tribe->save();

        return $tribe;
    }

    public static function load($userId, $saveId)
    {
        return new self($userId, $saveId);
    }

    private function loadFromFile()
    {
        $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
        $saveFile = $savePath . '/save.json';

        if (file_exists($saveFile)) {
            $data = $this->saveManager->loadJson($saveFile);

            if ($data) {
                $this->name = $data['name'] ?? '';
                $this->currentMonth = $data['current_month'] ?? 0;
                $this->currentSeason = $data['current_season'] ?? 'spring';
                $this->foodCount = $data['food_count'] ?? 0;
                $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
                $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
            }
        }

        $this->loadKobolds();
        $this->loadStorage();
    }

    private function loadKobolds()
    {
        $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
        $koboldsFile = $savePath . '/kobolds.json';

        $this->kobolds = [];

        if (file_exists($koboldsFile)) {
            $data = $this->saveManager->loadJson($koboldsFile);

            if ($data && is_array($data)) {
                foreach ($data as $koboldData) {
                    $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId);
                    if ($kobold) {
                        $this->kobolds[$kobold->getId()] = $kobold;
                    }
                }
            }
        }
    }

    private function loadStorage()
    {
        $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
        $itemsFile = $savePath . '/items.json';

        $this->storage = [];

        if (file_exists($itemsFile)) {
            $this->storage = $this->saveManager->loadJson($itemsFile) ?? [];
        }
    }

    public function save()
    {
        $this->lastPlayed = date('Y-m-d H:i:s');

        $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);

        // Save tribe metadata
        $tribeData = [
            'name' => $this->name,
            'current_month' => $this->currentMonth,
            'current_season' => $this->currentSeason,
            'food_count' => $this->foodCount,
            'created_at' => $this->createdAt,
            'last_played' => $this->lastPlayed
        ];

        $this->saveManager->saveJson($savePath . '/save.json', $tribeData);

        // Save kobolds
        $koboldsData = [];
        foreach ($this->kobolds as $kobold) {
            if (!$kobold->isDead()) {
                $kobold->save();
                $koboldsData[] = $kobold->toArray();
            }
        }

        $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData);

        // Save items
        $this->saveManager->saveJson($savePath . '/items.json', $this->storage);

        GameHelper::cleanupUnusedKoboldSprites($this->userId);
    }

    // Getters and Setters
    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getSaveId()
    {
        return $this->saveId;
    }

    public function getUserId()
    {
        return $this->userId;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function getLastPlayed()
    {
        return $this->lastPlayed;
    }

    public function getCurrentMonth()
    {
        return $this->currentMonth;
    }

    public function setCurrentMonth($month)
    {
        $this->currentMonth = max(0, $month);
    }

    public function getCurrentSeason()
    {
        return $this->currentSeason;
    }

    public function setCurrentSeason($season)
    {
        $this->currentSeason = $season;
    }

    // Kobold management
    public function getKobolds($includeDeadAndExpelled = false)
    {
        if ($includeDeadAndExpelled) {
            return $this->kobolds;
        }

        return array_filter($this->kobolds, function (Kobold $k) {
            return !$k->isDead() && !$k->isExpelled();
        });
    }

    public function getKobold($id)
    {
        return $this->kobolds[$id] ?? null;
    }

    public function addKobold(Kobold $kobold)
    {
        $this->kobolds[$kobold->getId()] = $kobold;
        return $kobold;
    }

    public function removeKobold($id)
    {
        unset($this->kobolds[$id]);
    }

    public function getAliveKobolds()
    {
        return array_filter($this->kobolds, fn($k) => !$k->isDead());
    }

    // Storage management
    public function addToStorage($item)
    {
        // Accept either Item object or array
        if (is_object($item) && method_exists($item, 'toArray')) {
            $this->storage[] = $item->toArray();
        } elseif (is_array($item)) {
            // Ensure it has an id
            if (!isset($item['id'])) {
                $item['id'] = uniqid('itm_');
            }
            $this->storage[] = $item;
        }
        return $this->storage;
    }

    public function getStorage()
    {
        return $this->storage;
    }

    // Food system methods
    public function getFoodCount()
    {
        return $this->foodCount;
    }

    public function addFood($amount)
    {
        $this->foodCount += $amount;
        return $this->foodCount;
    }

    public function removeFood($amount)
    {
        $this->foodCount = max(0, $this->foodCount - $amount);
        return $this->foodCount;
    }

    /**
     * Calculate total food needed for all alive kobolds
     */
    public function calculateFoodNeeded()
    {
        $needed = 0;

        foreach ($this->getAliveKobolds() as $kobold) {
            $ageCategory = $kobold->getAgeCategory();
            $requirement = $this->foodRequirements[$ageCategory] ?? 1.0;
            $needed += $requirement;
        }

        return $needed;
    }

    /**
     * Get food requirement for a specific kobold
     */
    public function getFoodRequirement(Kobold $kobold)
    {
        $ageCategory = $kobold->getAgeCategory();
        return $this->foodRequirements[$ageCategory] ?? 1.0;
    }

    /**
     * Consume food at end of month after events
     * Prioritizes: malnourished kobolds first, then younger before older
     * Returns story of food consumption and any starvations
     */
    public function consumeFood()
    {
        $story = "";
        $aliveKobolds = $this->getAliveKobolds();

        if (empty($aliveKobolds)) {
            return $story;
        }

        // Sort kobolds: malnourished first, then by age (younger first)
        usort($aliveKobolds, function ($a, $b) {
            // Check for malnourished injury
            $aMalnourished = $this->hasInjuryCategory($a, 'malnourished');
            $bMalnourished = $this->hasInjuryCategory($b, 'malnourished');

            if ($aMalnourished && !$bMalnourished)
                return -1;
            if (!$aMalnourished && $bMalnourished)
                return 1;

            // Both have or both don't have malnourished
            // Younger first (lower age = higher priority)
            return $a->getAge() - $b->getAge();
        });

        $fedKobolds = [];
        $starvedKobolds = [];

        foreach ($aliveKobolds as $kobold) {
            $needed = $this->getFoodRequirement($kobold);

            if ($this->foodCount >= $needed) {
                // Fed this kobold
                $this->foodCount -= $needed;
                $fedKobolds[$kobold->getId()] = $kobold;

                // If malnourished, cure it
                if ($this->hasInjuryCategory($kobold, 'malnourished')) {
                    $this->removeMalnourishedInjury($kobold);
                    $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n";
                }
            } else {
                // Not enough food - starve this kobold
                $starvedKobolds[$kobold->getId()] = $kobold;
                $this->foodCount = 0; // Use remaining food

                // Add malnourished injury if not already present
                if (!$this->hasInjuryCategory($kobold, 'malnourished')) {
                    $kobold->addInjury('malnourished');
                    $story .= "{$kobold->getName()} went hungry and became malnourished.\n";
                } else {
                    // Already malnourished - becomes more severe
                    $injuries = $kobold->getInjuries();
                    foreach ($injuries as $injury) {
                        if ($injury['category'] === 'malnourished') {
                            $injury['severity']++;
                            $story .= "{$kobold->getName()} remained hungry and suffered.\n";
                            break;
                        }
                    }
                }
            }
        }

        // Save updated kobolds
        foreach ($aliveKobolds as $kobold) {
            $kobold->save();
        }

        return $story;
    }

    /**
     * Check if a kobold has an injury in a specific category
     */
    private function hasInjuryCategory(Kobold $kobold, $category)
    {
        $injuries = $kobold->getInjuries();
        foreach ($injuries as $injury) {
            if ($injury['category'] === $category) {
                return true;
            }
        }
        return false;
    }

    /**
     * Remove all malnourished injuries from a kobold
     */
    private function removeMalnourishedInjury(Kobold $kobold)
    {
        $injuries = $kobold->getInjuries();
        foreach ($injuries as $injury) {
            if ($injury['category'] === 'malnourished') {
                $kobold->removeInjury($injury['id']);
            }
        }
    }

    public function endMonth()
    {
        $this->currentMonth++;

        $seasons = ['spring', 'summer', 'autumn', 'winter'];

        $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
        $index = intdiv($monthOfYear - 1, 3);

        $this->currentSeason = $seasons[$index];
        // Random month events happen here (handled by EventManager in API)
        // After events, consume food



        // age eggs
        $foodStory = "A month passes...\n" . $this->consumeFood();
        $foodStory .= "\n";

        foreach ($this->kobolds as $kobold) {
            if ($kobold->getAge() < 0) {
                $kobold->incrementAge();

                if ($kobold->getAge() >= 0) {
                    $kobold->setName(Kobold::generateRandomName());
                    $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
                }

                $kobold->save();
            }
        }

        // Age all kobolds
        if ($this->currentMonth % 12 === 0) {
            $foodStory .= "\nA new year begins.\n";

            foreach ($this->kobolds as $kobold) {
                if ($kobold->getAge() >= 0) {
                    $kobold->incrementAge();

                    // Check for old-age injuries
                    if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
                        $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
                        $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
                        $kobold->addInjury($injury);
                    }

                    // Old-age death roll: if roll < (age + total injury severity), kobold dies
                    if ($kobold->getAge() >= 35) {
                        $roll = rand(1, 100);
                        $totalSeverity = $kobold->getTotalInjurySeverity();
                        if ($roll < ($kobold->getAge() + $totalSeverity)) {
                            $foodStory .= $kobold->getName() . " dies of old age.\n";
                            $kobold->die();
                        }
                    }

                    $kobold->save();
                }
            }
        }
        $foodStory .= "\nIt's {$this->currentSeason}.\n";

        foreach ($this->kobolds as $kobold) {
            if ($kobold->isDead()) {
                $story = $story . "\n" . $kobold->getName() . " has died.";
            }
        }

        $this->save();

        return $foodStory;
    }

    private function shouldAddOldAgeInjury(Kobold $kobold)
    {
        // 1d100 roll under age starting at 35
        $roll = rand(1, 100);
        return $roll <= $kobold->getAge();
    }
}
