<?php

namespace App\Support;

/**
 * Per-game extra manifest for Heroes of Might & Magic: Olden Era.
 *
 * `loading.json` keeps the generic stream metadata (game, subtitle, mic…).
 * Olden Era specifics — matchup factions, heroes, the player's team color,
 * map name — live in their own `olden-era-manifest.json` so the loading
 * schema doesn't grow a new key every time a game gets bespoke chrome.
 */
class OldenEra
{
    /** Twitch Helix category id for "Heroes of Might & Magic: Olden Era". */
    public const GAME_ID = '1426873999';

    /** Public URL prefix; resolved via the webapp/public/games symlink. */
    public const URL = '/games/olden-era';

    private ?array $catalogCache = null;

    /**
     * Faction → {logo URL, heroes list}. Built by globbing
     * resources/games/olden-era/{factions,heroes/<Faction>}/*.png.
     */
    public function catalog(): array
    {
        if ($this->catalogCache !== null) return $this->catalogCache;

        $root = resource_path('games/olden-era');
        $out  = [];

        foreach (glob($root . '/factions/*.png') ?: [] as $factionPng) {
            $faction = pathinfo($factionPng, PATHINFO_FILENAME);
            $heroes  = [];
            foreach (glob($root . '/heroes/' . $faction . '/*.png') ?: [] as $heroPng) {
                $name = pathinfo($heroPng, PATHINFO_FILENAME);
                $heroes[] = [
                    'name'     => $name,
                    'portrait' => self::URL . '/heroes/' . rawurlencode($faction) . '/' . rawurlencode($name) . '.png',
                ];
            }
            usort($heroes, fn($a, $b) => strcasecmp($a['name'], $b['name']));
            $out[$faction] = [
                'logo'   => self::URL . '/factions/' . rawurlencode($faction) . '.png',
                'heroes' => $heroes,
            ];
        }

        ksort($out);
        return $this->catalogCache = $out;
    }

    public function manifest(): array
    {
        $path = $this->manifestPath();
        if (!is_file($path)) return [];
        $parsed = json_decode((string) @file_get_contents($path), true);
        return is_array($parsed) ? $parsed : [];
    }

    public function writeManifest(array $data): string
    {
        $path = $this->manifestPath();
        @mkdir(dirname($path), 0775, true);
        file_put_contents(
            $path,
            json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"
        );
        return $path;
    }

    public function manifestPath(): string
    {
        return rtrim(config('rig.storage_data'), '/') . '/olden-era-manifest.json';
    }
}
