<?php

require_once __DIR__ . '/../../src/System/SaveManager.php';
require_once __DIR__ . '/../../src/Utilities/GameHelper.php';

class Kobold
{
    private $id;
    private $userId;
    private $saveId;
    private $name;
    private $age;
    private $stats = [];
    private $spriteMorph;
    private $isLeader;
    private $isAlive = true;
    private $isExpelled = false;
    private $injuries = [];
    private $items = [];
    private $fatigue = 0;
    private $fatherId;
    private $motherId;
    private $saveManager;

    private $colourPrimary;
    private $colourSecondary;
    private $colourTertiary;

    private $male;
    public $dataStore;

    public $isRival = false;

    private static $statNames = [
        'vitality',
        'intelligence',
        'medicine',
        'crafting',
        'personality',
        'will',
        'fighting'
    ];

    private static $statTitles = [
        'vitality' => 'Pathfinder',
        'intelligence' => 'Lorekeeper',
        'medicine' => 'Healer',
        'crafting' => 'Tinkerer',
        'personality' => 'Speaker',
        'will' => 'Warden',
        'fighting' => 'Warrior'
    ];

    public function getTitle($hasSecondary = true)
    {
        $rankedStats = [];

        foreach (self::$statNames as $statName) {
            $rankedStats[$statName] = (int) ($this->stats[$statName] ?? 0);
        }

        arsort($rankedStats);
        $statKeys = array_keys($rankedStats);
        $statValues = array_values($rankedStats);

        if ($statValues[0] < 50)
            return $this->male ? "Tribesman" : "Tribeswoman";

        $topStat = $statKeys[0] ?? null;
        if ($topStat === null) {
            return '';
        }

        $topTitle = self::$statTitles[$topStat] ?? '';

        if (($topTitle === 'Warrior' || $topTitle === 'Pathfinder') && $hasSecondary) {
            $secondStat = $statKeys[1] ?? null;
            $secondTitle = $secondStat !== null ? (self::$statTitles[$secondStat] ?? '') : '';

            if ($secondTitle !== '') {
                return trim($topTitle . ' ' . $secondTitle);
            }
        }

        return $topTitle;
    }

    public function getHighestStatName()
    {
        $rankedStats = [];

        foreach (self::$statNames as $statName) {
            $rankedStats[$statName] = (int) ($this->stats[$statName] ?? 0);
        }

        arsort($rankedStats);
        $statKeys = array_keys($rankedStats);

        return $statKeys[0] ?? null;
    }

    public function __construct($id, $userId, $saveId, $name, $age, $spriteMorph, $isLeader = false)
    {
        $this->id = $id;
        $this->userId = $userId;
        $this->saveId = $saveId;
        $this->name = $name;
        $this->age = $age;
        $this->spriteMorph = $spriteMorph;
        $this->isLeader = $isLeader;
        $this->male = rand(0, 100) > 50;
        $this->fatigue = 0;

        $min = 120;
        $mx = 240;

        $this->colourPrimary = sprintf(
            "#%02X%02X%02X",
            random_int($min, $mx),
            random_int($min, $mx),
            random_int($min, $mx)
        );

        $this->colourSecondary = sprintf(
            "#%02X%02X%02X",
            random_int($min, $mx),
            random_int($min, $mx),
            random_int($min, $mx)
        );

        $this->colourTertiary = sprintf(
            "#%02X%02X%02X",
            random_int($min, $mx),
            random_int($min, $mx),
            random_int($min, $mx)
        );

        $this->saveManager = new SaveManager();

        // Initialize stats with random values
        foreach (self::$statNames as $stat) {
            $this->stats[$stat] = rand(0, 100);
        }
    }

    public function he()
    {
        return $this->male ? "he" : "she";
    }

    public function him()
    {
        return $this->male ? "him" : "her";
    }

    public function his()
    {
        return $this->male ? "his" : "her";
    }

    public function setLeader()
    {
        $this->isLeader = true;
    }

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

    public static function generate($userId, $saveId, $age = null, $rival = false)
    {
        if ($age === null) {
            $age = rand(5, 50);
        }

        $spriteMorph = self::getRandomSpriteMorph();
        $name = self::generateRandomName();
        $kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);

        $kobold->isRival = $rival;

        return $kobold;
    }

    private static function getRandomSpriteMorph()
    {
        $morphsPath = __DIR__ . '/../../assets/sprites';
        if (!is_dir($morphsPath)) {
            return 'default';
        }

        $morphs = array_filter(scandir($morphsPath), function ($item) use ($morphsPath) {
            return is_dir($morphsPath . '/' . $item) && $item[0] !== '.';
        });

        $morphs = array_values($morphs);

        return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';
    }

    public static function generateRandomName()
    {
        // Kobold name syllables
        $firstSyllables = [
            'Grik',
            'Gnak',
            'Drog',
            'Mog',
            'Bik',
            'Zag',
            'Kra',
            'Snak',
            'Grok',
            'Tik',
            'Nag',
            'Brack',
            'Flak',
            'Grat',
            'Krag',
            'Skrit',
            'Zik',
            'Bog',
            'Crag',
            'Gull',
            'Kith',
            'Mick',
            'Nib',
            'Prat',
            'Rik',
            'Tig',
            'Vex',
            'Wik',
            'Xak',
            'Yak',
            'Zap'
        ];

        $lastSyllables = [
            'ink',
            'ack',
            'og',
            'ag',
            'ug',
            'ik',
            'ek',
            'ock',
            'ar',
            'ax',
            'er',
            'it',
            'ut',
            'ot',
            'or',
            'in',
            'an',
            'en',
            'un',
            'on',
            'oo',
            'ee',
            'im',
            'um'
        ];

        $firstName = $firstSyllables[array_rand($firstSyllables)];
        $lastName = $lastSyllables[array_rand($lastSyllables)];

        return $firstName . $lastName;
    }

    public static function fromArray($data, $userId, $saveId)
    {
        $kobold = new self(
            $data['id'] ?? null,
            $userId,
            $saveId,
            $data['name'] ?? '',
            $data['age'] ?? 0,
            $data['sprite_morph'] ?? 'default',
            $data['is_leader'] ?? false
        );

        if (isset($data['stats'])) {
            $kobold->stats = $data['stats'];
        }

        $kobold->isAlive = $data['is_alive'] ?? true;
        $kobold->isExpelled = $data['is_expelled'] ?? false;
        $kobold->injuries = array_values($data['injuries'] ?? []);
        $kobold->items = $data['items'] ?? [];
        $kobold->fatigue = $data['fatigue'] ?? 0;
        $kobold->fatherId = $data['father_id'] ?? null;
        $kobold->motherId = $data['mother_id'] ?? null;
        $kobold->male = $data['male'] ?? rand(0, 100) > 50;

        $kobold->colourPrimary = $data['colour_primary'] ?? '#FFFFFF';
        $kobold->colourSecondary = $data['colour_secondary'] ?? '#FFFFFF';
        $kobold->colourTertiary = $data['colour_tertiary'] ?? '#FFFFFF';
        $kobold->dataStore = $data['data_store'] ?? new stdClass();
        $kobold->isRival = $data['is_rival'] ?? false;

        if (is_array($kobold->dataStore)) {
            $kobold->dataStore = (object) $kobold->dataStore;
        }

        return $kobold;
    }

    public function toArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->getAgeCategory() !== "egg" ? $this->name : "Egg",
            'age' => $this->age,
            'ageCategory' => $this->getAgeCategory(),
            'stats' => $this->stats,
            'sprite_morph' => $this->spriteMorph,
            'is_leader' => $this->isLeader,
            'is_alive' => !$this->isDead(),
            'is_expelled' => $this->isExpelled,
            'injuries' => $this->injuries,
            'items' => $this->items,
            'fatigue' => $this->fatigue,
            'fatigue_label' => $this->getFatigueLabel(),
            'father_id' => $this->fatherId,
            'mother_id' => $this->motherId,
            'colour_primary' => $this->colourPrimary,
            'colour_secondary' => $this->colourSecondary,
            'colour_tertiary' => $this->colourTertiary,
            'male' => $this->male,
            'data_store' => $this->dataStore ?? new stdClass(),
            'is_rival' => $this->isRival ?? false
        ];
    }

    public function save()
    {
        // Kobolds are saved as part of the Tribe's kobolds.json
        // Sprite files are stored in:
        // /data/saves/{userId}/kobolds/{koboldId}/sprites/
    }

    /**
     * Initialize sprite by copying base sprite from assets and applying transformations
     * Called on kobold generation to populate the save folder
     */
    private function initializeSprite()
    {
        $ageSprite = $this->getAgeSpriteName();

        if ($ageSprite === "old" || $ageSprite === "adult")
            $ageSprite = $ageSprite . "_" . ($this->male ? "male" : "female");

        $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);
        $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
        $destFile = $spriteDir;

        // Copy base sprite from assets
        if (file_exists($sourceFile)) {
            copy($sourceFile, $destFile);
        }

        // Apply transformations to the sprite
        $this->transformSprite($destFile);
    }

    /**
     * Get the sprite filename for current age
     */
    public function getAgeSpriteName()
    {
        $ageCategory = $this->getAgeCategory();
        $spriteMap = [
            'egg' => 'egg',
            'baby' => 'baby',
            'young' => 'young',
            'adult' => 'adult',
            'old' => 'old'
        ];

        return $spriteMap[$ageCategory] ?? 'adult';
    }

    /**
     * Get path to the kobold's sprite file for current age
     */
    public function getSpritePath($age)
    {
        $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);
        $ageSprite = $age ?? $this->getAgeSpriteName();

        if ($ageSprite === "old" || $ageSprite === "adult")
            $ageSprite = $ageSprite . "_" . ($this->male ? "male" : "female");

        $destFile = $spriteDir;

        if (!file_exists($destFile)) {
            $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';

            // Copy base sprite from assets
            if (file_exists($sourceFile)) {
                copy($sourceFile, $destFile);
            }

            // Apply transformations to the sprite
            $this->transformSprite($destFile);
        }

        return $destFile;
    }

    public function getMale()
    {
        return $this->male;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

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

    public function getAge()
    {
        return $this->age;
    }

    public function setAge($age)
    {
        $this->age = max(0, $age);
    }

    public function incrementAge()
    {
        $this->age++;
    }

    public function getAgeCategory()
    {
        return GameHelper::getAgeCategory($this->age);
    }

    public function getAgeProgress()
    {
        if ($this->age < 17) {
            return max(1, $this->age / 17);
        } else if ($this->age > 40) {
            return max(1, 1 - (40 / $this->age));
        }

        return 1;
    }

    public function getStat($statName)
    {
        if (!isset($this->stats[$statName])) {
            return null;
        }

        $baseStat = $this->stats[$statName];

        $baseStat = (int) ($baseStat * $this->getAgeProgress());

        return $baseStat;
    }

    public function setStat($statName, $value)
    {
        if (isset($this->stats[$statName])) {
            $this->stats[$statName] = max(0, min(100, $value));
        }
    }

    public function checkStat($statName, $bonus = 0)
    {
        $stat = $this->getStat($statName);

        if ($stat === null) {
            return false;
        }

        // Apply item stat modifications (support arrays from JSON or Item objects)
        $itemModTotal = 0;
        if (!empty($this->items) && is_array($this->items)) {
            foreach ($this->items as $itm) {
                $mods = [];
                if (is_array($itm)) {
                    $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
                } elseif (is_object($itm)) {
                    if (method_exists($itm, 'getStatModifications')) {
                        $mods = $itm->getStatModifications();
                    } elseif (property_exists($itm, 'statModifications')) {
                        $mods = $itm->statModifications;
                    }
                }

                if (is_array($mods) && isset($mods[$statName])) {
                    $itemModTotal += (int) $mods[$statName];
                }
            }
        }

        // First apply item modifications to the stat
        $stat += $itemModTotal;

        // Apply injury modifications
        $totalInjurySeverity = 0;
        if (!empty($this->injuries) && is_array($this->injuries)) {
            foreach ($this->injuries as $inj) {
                $totalInjurySeverity += $inj['severity'] ?? 0;
            }
        }

        $stat -= $totalInjurySeverity;
        $stat = max(0, min(100, $stat));

        // Roll under 1d100
        $roll = min(100, rand(1, 100) + $bonus);
        return $roll <= $stat;
    }

    public function checkPersonality(Kobold $otherKobold)
    {
        // Get the like value that otherKobold has for this kobold
        $bonus = 0;

        if (isset($otherKobold->dataStore) && $otherKobold->dataStore instanceof stdClass) {
            if (isset($otherKobold->dataStore->likes) && is_array($otherKobold->dataStore->likes)) {
                $bonus = $otherKobold->dataStore->likes[$this->getId()] ?? 0;
            }
        }

        // Call checkStat with the like value as bonus
        return $this->checkStat('personality', $bonus);
    }

    public function addInjury($injuryType)
    {
        // Reject duplicates
        foreach ($this->injuries as $inj) {
            if (($inj['id'] ?? null) === $injuryType) {
                return false;
            }
        }

        // If an injury file exists in assets, load it for full data
        $injData = null;
        require_once __DIR__ . '/../Utilities/GameHelper.php';
        $maybe = GameHelper::loadInjury($injuryType);
        if ($maybe) {
            $injData = $maybe;
            // ensure kobold id
            $injData['kobold_id'] = $this->id;
            $this->injuries[] = $injData;

            if ($this->isDead()) {
                if (!isset($this->dataStore)) {
                    $this->dataStore = new stdClass();
                }

                $injuryLabel = str_replace(['_', '-'], ' ', $injuryType);
                $deathVariations = [
                    "{$this->getName()} died from {$injuryLabel}.",
                    "{$this->getName()} succumbed to {$injuryLabel}.",
                    "{$this->getName()} could not survive {$injuryLabel}.",
                    "{$injuryLabel} claimed {$this->getName()}.",
                    "{$this->getName()} passed away after suffering {$injuryLabel}."
                ];

                $deathMessage = $deathVariations[array_rand($deathVariations)];
                $this->dataStore->lastDeathMessage = $deathMessage;

                return $deathMessage;
            }

            return true;
        }

        return false;
    }

    public function removeInjury($injuryId)
    {
        $this->injuries = array_values(array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId));
    }

    public function getInjuries()
    {
        return $this->injuries;
    }

    public function getFatigue()
    {
        return $this->fatigue;
    }

    public function setFatigue($value)
    {
        $this->fatigue = max(0, (int) $value);
    }

    public function addFatigue($amount)
    {
        $this->fatigue = max(0, $this->fatigue + (int) $amount);
    }

    public function resetFatigue()
    {
        $this->fatigue = 0;
    }

    public function getFatigueLabel()
    {
        $vitality = (int) ($this->getStat('vitality') ?? 0);
        if ($vitality <= 0) {
            return 'exhausted';
        }

        $ratio = $this->fatigue / max(1, $vitality);

        if ($this->fatigue <= 0) {
            return 'energetic';
        }
        if ($ratio < 0.3) {
            return 'fresh';
        }
        if ($ratio < 0.6) {
            return 'tired';
        }
        if ($ratio < 0.85) {
            return 'weary';
        }
        return 'exhausted';
    }

    public function getTotalInjurySeverity()
    {
        $sum = 0;
        foreach ($this->injuries as $injury) {
            $sum += $injury['severity'] ?? 0;
        }
        return $sum;
    }

    public function isDead()
    {
        return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
    }

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

    public function setExpelled($expelled)
    {
        $this->isExpelled = $expelled;
    }

    public function die()
    {
        $this->isAlive = false;
    }

    public function getSpriteMorph()
    {
        return $this->spriteMorph;
    }

    public function setSpriteMorph($spriteMorph)
    {
        $this->spriteMorph = $spriteMorph;
    }

    public function getColours()
    {
        return [
            'primary' => $this->colourPrimary,
            'secondary' => $this->colourSecondary,
            'tertiary' => $this->colourTertiary
        ];
    }

    public function setColours($primary, $secondary, $tertiary)
    {
        $this->colourPrimary = $primary;
        $this->colourSecondary = $secondary;
        $this->colourTertiary = $tertiary;
    }

    public function regenerateSprite()
    {
        $this->initializeSprite();
    }

    public function getStatLabel($statValue)
    {
        if ($statValue >= 90)
            return 'godlike';
        if ($statValue >= 80)
            return 'divine';
        if ($statValue >= 70)
            return 'master';
        if ($statValue >= 60)
            return 'fantastic';
        if ($statValue >= 50)
            return 'excellent';
        if ($statValue >= 40)
            return 'good';
        if ($statValue >= 30)
            return 'decent';
        if ($statValue >= 20)
            return 'unskilled';
        if ($statValue >= 10)
            return 'bad';
        return 'terrible';
    }

    public function setParents($fatherId, $motherId)
    {
        $this->fatherId = $fatherId;
        $this->motherId = $motherId;
    }

    public function getParents()
    {
        return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
    }

    public function getItems()
    {
        return $this->items;
    }

    public function addItem($item)
    {
        $this->items[] = $item;
    }

    public function removeItem($itemId)
    {
        $this->items = array_filter($this->items, function ($item) use ($itemId) {
            return $item['id'] !== $itemId;
        });
        $this->items = array_values($this->items);
    }

    /**
     * Apply transformations to sprite (injuries, age coloring, leadership marks)
     * Uses PHP GD library to modify the sprite image
     */
    private function transformSprite($spritePath)
    {
        if (!file_exists($spritePath))
            return;

        $image = imagecreatefrompng($spritePath);
        if (!$image)
            return;

        // Ensure truecolour (important if PNG is palette-based)
        if (!imageistruecolor($image)) {
            imagepalettetotruecolor($image);
        }

        $primaryRGB = $this->hexToRgb($this->colourPrimary);
        $secondaryRGB = $this->hexToRgb($this->colourSecondary);
        $tertiaryRGB = $this->hexToRgb($this->colourTertiary);

        $width = imagesx($image);
        $height = imagesy($image);

        // For exact per-pixel alpha writes:
        imagealphablending($image, false);
        imagesavealpha($image, true);

        $cache = []; // cache allocated colours "r,g,b,a" => int

        for ($y = 0; $y < $height; $y++) {
            for ($x = 0; $x < $width; $x++) {
                $idx = imagecolorat($image, $x, $y);
                $rgba = imagecolorsforindex($image, $idx);

                $baseR = $rgba['red'];
                $baseG = $rgba['green'];
                $baseB = $rgba['blue'];
                $baseA = $rgba['alpha']; // 0..127

                // If fully transparent, skip work (optional)
                if ($baseA === 127) {
                    continue;
                }

                $newR = 0;
                $newG = 0;
                $newB = 0;

                $rW = $baseR / 255.0;
                $gW = $baseG / 255.0;
                $bW = $baseB / 255.0;

                $sum = $rW + $gW + $bW;

                if ($sum > 0) {
                    $newR = ($rW * $primaryRGB['r']
                        + $gW * $secondaryRGB['r']
                        + $bW * $tertiaryRGB['r']) / $sum;

                    $newG = ($rW * $primaryRGB['g']
                        + $gW * $secondaryRGB['g']
                        + $bW * $tertiaryRGB['g']) / $sum;

                    $newB = ($rW * $primaryRGB['b']
                        + $gW * $secondaryRGB['b']
                        + $bW * $tertiaryRGB['b']) / $sum;
                } else {
                    $newR = $newG = $newB = 0;
                }

                $w = min($baseR, $baseG, $baseB) / 255.0;

                $newR = (int) round($newR + (255 - $newR) * $w);
                $newG = (int) round($newG + (255 - $newG) * $w);
                $newB = (int) round($newB + (255 - $newB) * $w);

                $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)

                $newR *= $intensity;
                $newG *= $intensity;
                $newB *= $intensity;

                $newR = max(0, min(255, $newR));
                $newG = max(0, min(255, $newG));
                $newB = max(0, min(255, $newB));

                $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
                if (!isset($cache[$key])) {
                    $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
                }

                imagesetpixel($image, $x, $y, $cache[$key]);
            }
        }

        imagepng($image, $spritePath);
    }


    /**
     * Convert HEX color string to RGB array
     * @param string $hex HEX color in format #RRGGBB
     * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
     */
    private function hexToRgb($hex)
    {
        // Remove # if present
        $hex = ltrim($hex, '#');

        // Convert HEX to RGB
        return [
            'r' => hexdec(substr($hex, 0, 2)),
            'g' => hexdec(substr($hex, 2, 2)),
            'b' => hexdec(substr($hex, 4, 2))
        ];
    }
}
