<?php

class GameHelper
{
    /**
     * Delete cached kobold sprite sets for kobolds not present in any save for a user
     * @param int $userId
     * @return array List of deleted kobold IDs
     */

    public static function cleanupUnusedKoboldSprites($userId)
    {
        $deleted = [];
        $saveManager = new \SaveManager();
        $userSavesPath = $saveManager->getUserSavesPath($userId);
        $koboldsDir = $userSavesPath . '/kobolds';
        if (!is_dir($koboldsDir))
            return $deleted;

        // 1. Collect all kobold IDs in all saves for this user
        $activeKoboldIds = [];
        $saveDirs = glob($userSavesPath . '/*', GLOB_ONLYDIR);
        foreach ($saveDirs as $saveDir) {
            $koboldsJson = $saveDir . '/kobolds.json';
            if (file_exists($koboldsJson)) {
                $data = json_decode(file_get_contents($koboldsJson), true);
                if (is_array($data)) {
                    foreach ($data as $kobold) {
                        if (isset($kobold['id'])) {
                            $activeKoboldIds[$kobold['id']] = true;
                        }
                    }
                }
            }
        }

        // 2. Scan kobolds/ for all sprite sets
        $dirs = glob($koboldsDir . '/kob_*', GLOB_ONLYDIR);
        foreach ($dirs as $koboldDir) {
            $koboldId = basename($koboldDir);
            if (!isset($activeKoboldIds[$koboldId])) {
                // Delete the entire kobold sprite directory
                self::rrmdir($koboldDir);
                $deleted[] = $koboldId;
            }
        }
        return $deleted;
    }

    /**
     * Recursively remove a directory
     */
    private static function rrmdir($dir)
    {
        if (!is_dir($dir))
            return;
        $items = scandir($dir);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..')
                continue;
            $path = $dir . DIRECTORY_SEPARATOR . $item;
            if (is_dir($path)) {
                self::rrmdir($path);
            } else {
                @unlink($path);
            }
        }
        @rmdir($dir);
    }

    /**
     * Get stat display label from numeric value
     */
    public static function getStatLabel($value)
    {
        $value = max(0, min(100, $value));

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

    /**
     * Roll 1d100 under value
     */
    public static function rollUnder($value)
    {
        $value = max(0, min(100, $value));
        $roll = rand(1, 100);
        return $roll <= $value;
    }

    /**
     * Get age category for display
     */
    public static function getAgeCategory($age)
    {
        if ($age < 0)
            return 'egg';
        if ($age < 4)
            return 'baby';
        if ($age < 17)
            return 'young';
        if ($age < 40)
            return 'adult';

        return 'old';
    }

    /**
     * Get sprite name for age category
     */
    public static function getAgeSprite($ageCategory)
    {
        $spriteMap = [
            'egg' => 'egg',
            'baby' => 'baby',
            'young' => 'young',
            'adult' => 'adult',
            'old' => 'old'
        ];

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

    /**
     * Get season for month number
     */
    public static function getSeason($month)
    {
        $seasons = ['spring', 'summer', 'autumn', 'winter'];
        return $seasons[($month / 3) % 4];
    }

    /**
     * Check if kobold can have old-age injury
     */
    public static function shouldCheckOldAgeInjury($age)
    {
        return $age >= 35;
    }

    /**
     * Get stat value with age scaling
     */
    public static function getEffectiveStat($baseStat, $age)
    {
        $ageCategory = self::getAgeCategory($age);

        // For babies and eggs, scale by age
        if ($ageCategory === 'egg') {
            return 0; // Eggs can't do anything
        }

        if ($ageCategory === 'baby') {
            // Progress from 0 to 4 years = 0% to 100%
            $progress = $age / 4;
            return (int) ($baseStat * $progress);
        }

        // Adults at full value
        return $baseStat;
    }

    /**
     * Get random name from list
     */
    public static function getRandomKoboldName()
    {
        $names = [
            'Zyx',
            'Krellin',
            'Tik',
            'Borp',
            'Schnax',
            'Grell',
            'Vix',
            'Nok',
            'Pix',
            'Grin',
            'Skitter',
            'Blort',
            'Zap',
            'Clicket',
            'Snort',
            'Gik',
            'Spork',
            'Krunk',
            'Vik',
            'Tock',
            'Blix',
            'Zazzle',
            'Sprocket',
            'Klik',
            'Fizz',
            'Gorp',
            'Skronk',
            'Thrall',
            'Glint',
            'Zink',
            'Plock',
            'Bzzzt'
        ];

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

    /**
     * Generate random stats
     */
    public static function generateRandomStats()
    {
        $stats = [];
        $statNames = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];

        foreach ($statNames as $stat) {
            $stats[$stat] = rand(0, 100);
        }

        return $stats;
    }

    /**
     * Format story text (for narrative generation)
     */
    public static function formatStory($text)
    {
        // Could add markdown parsing, formatting, etc.
        return nl2br(htmlspecialchars($text));
    }

    /**
     * Get injury cure type
     */
    public static function getInjuryCure($injuryCategory)
    {
        $cureMap = [
            'wound' => 'basic_medicine',
            'fracture' => 'bone_setting',
            'infection' => 'healing_herbs',
            'poison' => 'antidote',
            'burn' => 'burn_salve',
            'malnourished' => 'food',
            'old-age' => null
        ];

        return $cureMap[$injuryCategory] ?? null;
    }

    /**
     * Check if injury is treatable
     */
    public static function isInjuryTreatable($injuryCategory)
    {
        return self::getInjuryCure($injuryCategory) !== null;
    }

    /**
     * Capitalize words
     */
    public static function humanize($text)
    {
        return ucfirst(str_replace('_', ' ', $text));
    }

    /**
     * Load item from JSON file by ID
     * 
     * @param string $itemId The filename without extension (e.g. 'book')
     * @return Item|null The loaded item or null if file not found
     */
    public static function loadItem($itemId)
    {
        require_once __DIR__ . '/../Classes/Item.php';

        $itemPath = __DIR__ . '/../../assets/items/' . $itemId . '.json';

        if (!file_exists($itemPath)) {
            return null;
        }

        $json = file_get_contents($itemPath);
        $data = json_decode($json, true);

        if (!$data) {
            return null;
        }

        // Create Item with filename as ID
        $item = new Item(
            $itemId,
            $data['name'] ?? '',
            $data['description'] ?? '',
            $data['itemType'] ?? 'generic',
            $data['statModifications'] ?? []
        );

        return $item;
    }

    /**
     * Load injury from JSON file by ID
     *
     * @param string $injuryId filename without extension (e.g. 'brokenLeg')
     * @return array|null normalized injury array or null if not found
     */
    public static function loadInjury(string $injuryId)
    {
        $injuryPath = __DIR__ . '/../../assets/injuries/' . $injuryId . '.json';

        if (!file_exists($injuryPath)) {
            return null;
        }

        $json = file_get_contents($injuryPath);
        $data = json_decode($json, true);
        if (!$data)
            return null;

        // Normalize to snake_case keys matching internal storage
        $inj = [];
        $inj['id'] = $injuryId;
        $inj['injury_type'] = $data['injuryType'] ?? ($data['injury_type'] ?? $injuryId);
        $inj['description'] = $data['description'] ?? '';
        $inj['category'] = $data['category'] ?? null;
        $inj['severity'] = $data['severity'] ?? ($data['severity'] ?? 1);
        $inj['stat_modifications'] = $data['statModifications'] ?? $data['stat_modifications'] ?? [];
        $inj['required_medicine'] = Injury::getCureForCategory($inj['category']);

        return $inj;
    }

    public static function findBestKoboldForStat(array $kobolds, string $skillId): Kobold
    {
        $highest = -1;
        $selected = null;

        for ($k = 0; $k < count($kobolds); $k++) {
            $kobold = $kobolds[$k];
            if ($kobold->getStat($skillId) > $highest) {
                $highest = $kobold->getStat($skillId);
                $selected = $kobold;
            }
        }

        return $selected;
    }
}
