<?php

require_once __DIR__ . '/../../src/System/SaveManager.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 $fatherId;
    private $motherId;
    private $saveManager;

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

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

    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;

        $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 static function generate($userId, $saveId, $age = null)
    {
        if ($age === null) {
            $age = rand(5, 20);
        }

        $spriteMorph = self::getRandomSpriteMorph();
        $name = self::generateRandomName();
        $kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);
        // Copy and transform sprite from assets to save folder
        $kobold->initializeSprite();

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

    private 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 = $data['injuries'] ?? [];
        $kobold->items = $data['items'] ?? [];
        $kobold->fatherId = $data['father_id'] ?? null;
        $kobold->motherId = $data['mother_id'] ?? null;

        $kobold->colourPrimary = $data['colour_primary'] ?? '#FFFFFF';
        $kobold->colourSecondary = $data['colour_secondary'] ?? '#FFFFFF';
        $kobold->colourTertiary = $data['colour_tertiary'] ?? '#FFFFFF';

        return $kobold;
    }

    public function toArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'age' => $this->age,
            'ageCategory' => $this->getAgeCategory(),
            'stats' => $this->stats,
            'sprite_morph' => $this->spriteMorph,
            'is_leader' => $this->isLeader,
            'is_alive' => $this->isAlive,
            'is_expelled' => $this->isExpelled,
            'injuries' => $this->injuries,
            'items' => $this->items,
            'father_id' => $this->fatherId,
            'mother_id' => $this->motherId,
            'colour_primary' => $this->colourPrimary,
            'colour_secondary' => $this->colourSecondary,
            'colour_tertiary' => $this->colourTertiary
        ];
    }

    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();
        $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'  // Reuse old sprite for very_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();
        $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 getId()
    {
        return $this->id;
    }

    public function getName()
    {
        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()
    {
        if ($this->age < 0)
            return 'egg';
        if ($this->age < 4)
            return 'baby';
        if ($this->age < 35)
            return 'young';
        if ($this->age < 60)
            return 'adult';
        return 'old';
    }

    public function getAgeProgress()
    {
        // Returns 0-1 indicating progress to next age tier
        $ageTiers = [-1, 0, 4, 35, 60];

        for ($i = 0; $i < count($ageTiers) - 1; $i++) {
            $tierStart = $ageTiers[$i];
            $tierEnd = $ageTiers[$i + 1];

            if ($this->age >= $tierStart && $this->age < $tierEnd) {
                $duration = $tierEnd - $tierStart;
                $progress = ($this->age - $tierStart) / $duration;
                return $progress;
            }
        }

        return 1;
    }

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

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

        // Scale stats for non-adult kobolds
        if ($this->getAgeCategory() === 'baby' || $this->getAgeCategory() === 'egg') {
            $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)
    {
        $stat = $this->getStat($statName);

        // Apply injury modifications
        $totalInjurySeverity = array_sum(array_column($this->injuries, 'severity', null));
        if ($totalInjurySeverity === null) {
            $totalInjurySeverity = 0;
        }

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

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

    public function addInjury($injuryType, $category, $severity = 1)
    {
        $id = uniqid('inj_');

        $this->injuries[] = [
            'id' => $id,
            'kobold_id' => $this->id,
            'injury_type' => $injuryType,
            'category' => $category,
            'severity' => $severity
        ];
    }

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

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

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

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