<?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 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;

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

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

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

        $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();
        $kobold = new self(uniqid('kob_'), $userId, $saveId, '', $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';
    }

    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;

        return $kobold;
    }

    public function toArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'age' => $this->age,
            '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
        ];
    }

    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()
    {
        $spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
        $ageSprite = $this->getAgeSpriteName();
        $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
        $destFile = $spriteDir . '/' . $ageSprite . '.png';

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

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

    /**
     * Get the sprite filename for current age
     */
    public function getAgeSpriteName()
    {
        $ageCategory = $this->getAgeCategory();
        $spriteMap = [
            'egg' => 'egg',
            'baby' => 'baby',
            'adult' => 'adult',
            'old' => 'old',
            'very_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()
    {
        $spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
        $ageSprite = $this->getAgeSpriteName();
        return $spriteDir . '/' . $ageSprite . '.png';
    }

    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 = $this->getSpritePath();

        if (!file_exists($spritePath)) {
            return; // Base sprite not created yet
        }

        // Load the image
        $image = imagecreatefrompng($spritePath);
        if (!$image) {
            return; // Failed to load image
        }

        // Apply injury markings if kobold has taken damage
        $vitalityStat = $this->getStat('vitality');
        if ($vitalityStat < 50) {
            $this->applyInjuryMarkings($image);
        }

        // Apply age-based color adjustments (desaturate for elderly)
        if ($this->getAgeCategory() === 'old' || $this->getAgeCategory() === 'very_old') {
            $this->desaturateImage($image);
        }

        // Save modified image back to the sprite file
        imagepng($image, $spritePath);
        imagedestroy($image);
    }

    /**
     * Draw injury marks (red scars) on the sprite
     * Number of marks increases with injury level
     */
    private function applyInjuryMarkings(&$image)
    {
        $red = imagecolorallocate($image, 255, 0, 0);
        $darkRed = imagecolorallocate($image, 139, 0, 0);

        // Number of scars based on vitality stat
        $vitalityStat = $this->getStat('vitality');
        $scarCount = intval((50 - $vitalityStat) / 10) + 1;
        $scarCount = min(5, $scarCount);

        $imageWidth = imagesx($image);
        $imageHeight = imagesy($image);

        // Draw scars at various positions
        for ($i = 0; $i < $scarCount; $i++) {
            $x = rand(10, $imageWidth - 10);
            $y = rand(10, $imageHeight - 10);
            $length = rand(5, 15);

            // Draw a jagged line scar
            imageline($image, $x, $y, $x + $length, $y, $darkRed);
            imageline($image, $x, $y + 1, $x + $length, $y + 1, $red);
        }
    }

    /**
     * Desaturate the sprite image for elderly kobolds
     * Reduces color saturation to make them appear older
     */
    private function desaturateImage(&$image)
    {
        $imageWidth = imagesx($image);
        $imageHeight = imagesy($image);

        for ($y = 0; $y < $imageHeight; $y++) {
            for ($x = 0; $x < $imageWidth; $x++) {
                $rgb = imagecolorat($image, $x, $y);

                // Extract color components
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                $a = ($rgb >> 24) & 0xFF;

                // Calculate grayscale value using luminance formula
                $gray = intval(0.299 * $r + 0.587 * $g + 0.114 * $b);

                // Blend original color with grayscale (60% desaturated)
                $newR = intval($r * 0.4 + $gray * 0.6);
                $newG = intval($g * 0.4 + $gray * 0.6);
                $newB = intval($b * 0.4 + $gray * 0.6);

                $newColor = imagecolorallocatealpha($image, $newR, $newG, $newB, $a);
                imagesetpixel($image, $x, $y, $newColor);
            }
        }
    }
}
