<?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 $environmentId = null;
    private $createdAt;
    private $lastPlayed;
    private $saveManager;
    public $dataStore;

    // Food requirement by age tier (portion units)
    public $foodRequirements = [
        'egg' => 0,
        'baby' => 1,
        'young' => 2,
        'adult' => 3,
        'old' => 2
    ];

    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->environmentId = $data['environment_id'] ?? null;
                $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->dataStore = $data['data_store'] ?? new stdClass();
            }
        }

        $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,
            'food_months_left' => $this->foodMonthsLeft($this->foodCount),
            'environment_id' => $this->environmentId,
            'created_at' => $this->createdAt,
            'last_played' => $this->lastPlayed,
            'data_store' => $this->dataStore ?? new stdClass()
        ];

        $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;
    }

    public function getEnvironmentId()
    {
        return $this->environmentId;
    }

    public function setEnvironmentId($environmentId)
    {
        $this->environmentId = $environmentId;
    }

    // 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 $item, int $count = 1): array
    {
        // 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_');
            }
            for ($i = 0; $i < $count; $i++)
                $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 for one month
     */
    public function calculateFoodNeeded()
    {
        $needed = 0;

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

        return $needed;
    }

    /**
     * Calculate how many full months the current kobolds can be fed
     * with the provided amount of food.
     */
    public function foodMonthsLeft($amount)
    {
        $foodPerMonth = $this->calculateFoodNeeded();
        if ($foodPerMonth <= 0) {
            return 0;
        }

        $available = max(0, (float) $amount);
        return (int) floor($available / $foodPerMonth);
    }

    /**
     * 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


                $malnourishedId = $this->getMalnourishedInjuryId($kobold);
                if (!$malnourishedId) {
                    $kobold->addInjury('malnourished-slight');
                    $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
                } else {
                    if ($malnourishedId === 'malnourished-slight') {
                        $kobold->removeInjury($malnourishedId);
                        $kobold->addInjury('malnourished-mild');
                        $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
                    } elseif ($malnourishedId === 'malnourished-mild') {
                        $kobold->removeInjury($malnourishedId);
                        $kobold->addInjury('malnourished-severe');
                        $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
                    } elseif ($malnourishedId === 'malnourished-severe') {
                        $kobold->removeInjury($malnourishedId);
                        $kobold->addInjury('malnourished-brink');
                        $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
                    } elseif ($malnourishedId === 'malnourished-brink') {
                        $kobold->die();
                        $story .= "{$kobold->getName()} succumbed to starvation.\n";
                    }
                }
            }
        }

        // 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']);
            }
        }
    }

    /**
     * Get current malnourished injury id if present
     */
    private function getMalnourishedInjuryId(Kobold $kobold)
    {
        $injuries = $kobold->getInjuries();
        foreach ($injuries as $injury) {
            if (($injury['category'] ?? null) === 'malnourished') {
                return $injury['id'] ?? null;
            }
        }
        return null;
    }

    public function tryMate()
    {
        $kobolds = array_values($this->getKobolds());
        $count = count($kobolds);

        if ($count === 0) {
            return '';
        }

        $roll = rand(1, 30);
        if ($roll <= $count) {
            return '';
        }

        $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
        $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));

        if (empty($males) || empty($females)) {
            return '';
        }

        $pair = null;
        $attempts = 20;
        while ($attempts-- > 0) {
            $male = $males[array_rand($males)];
            $female = $females[array_rand($females)];

            $maleParents = $male->getParents();
            $femaleParents = $female->getParents();

            $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
            $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
            $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
            $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);

            if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
                continue;
            }

            $pair = [$male, $female];
            break;
        }

        if (!$pair) {
            return '';
        }

        [$male, $female] = $pair;

        if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
            return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
        }

        $child = Kobold::generate($this->userId, $this->saveId, -6);

        $inheritRoll = rand(1, 100);
        if ($inheritRoll <= 40) {
            $child->setSpriteMorph($male->getSpriteMorph());
        } elseif ($inheritRoll <= 80) {
            $child->setSpriteMorph($female->getSpriteMorph());
        }

        $blendHex = function ($a, $b) {
            $hexToRgb = function ($hex) {
                $hex = ltrim($hex, '#');
                return [
                    'r' => hexdec(substr($hex, 0, 2)),
                    'g' => hexdec(substr($hex, 2, 2)),
                    'b' => hexdec(substr($hex, 4, 2))
                ];
            };

            $rgbToHex = function ($rgb) {
                return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
            };

            $ra = $hexToRgb($a);
            $rb = $hexToRgb($b);
            $ratio = rand(0, 100) / 100;

            $offset = function () {
                return rand(-20, 20);
            };

            $mix = function ($c1, $c2) use ($ratio, $offset) {
                $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
                return max(0, min(255, $val));
            };

            $mixed = [
                'r' => $mix($ra['r'], $rb['r']),
                'g' => $mix($ra['g'], $rb['g']),
                'b' => $mix($ra['b'], $rb['b'])
            ];

            return $rgbToHex($mixed);
        };

        $maleColours = $male->getColours();
        $femaleColours = $female->getColours();

        $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
        $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
        $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);

        $child->setColours($childPrimary, $childSecondary, $childTertiary);
        $child->setParents($male->getId(), $female->getId());
        $child->regenerateSprite();

        $this->addKobold($child);

        $pairName = $female->getName() . " and " . $male->getName();
        $momName = $female->getName();
        $variations = [
            "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
            "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
            "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
            "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
            "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
            "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
            "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
            "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
            "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
            "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
        ];

        return $variations[array_rand($variations)];
    }

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

        foreach ($this->kobolds as $kobold) {
            $kobold->resetFatigue();
        }

        $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 .= "\n" . $this->tryMate();
        $foodStory .= "\nIt's {$this->currentSeason}.\n";

        foreach ($this->kobolds as $kobold) {
            if ($kobold->isDead()) {
                $foodStory = $foodStory . "\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();
    }
}
