<?php
declare(strict_types=1);

/**
 * Planet catalog shared with the JS client (server/lib/planets.json).
 * Power and miss-chance formulas must stay in lockstep with src/planet.js.
 */
final class Planets
{
    private static ?array $all = null;

    public static function path(): string
    {
        return __DIR__ . '/planets.json';
    }

    /** @return list<array> raw catalog entries */
    public static function all(): array
    {
        if (self::$all !== null) {
            return self::$all;
        }
        $raw = file_get_contents(self::path());
        if ($raw === false) {
            throw new RuntimeException('planets.json ontbreekt.');
        }
        $data = json_decode($raw, true);
        if (!is_array($data) || !isset($data['planets']) || !is_array($data['planets'])) {
            throw new RuntimeException('planets.json is ongeldig.');
        }
        self::$all = [];
        foreach ($data['planets'] as $row) {
            if (!is_array($row) || empty($row['id'])) {
                continue;
            }
            self::$all[] = $row;
        }
        return self::$all;
    }

    public static function byId(string $id): ?array
    {
        foreach (self::all() as $p) {
            if (($p['id'] ?? '') === $id) {
                return $p;
            }
        }
        return null;
    }

    public static function defaultId(): string
    {
        return 'terra';
    }

    public static function default(): array
    {
        return self::byId(self::defaultId()) ?? self::all()[0];
    }

    public static function known(string $id): bool
    {
        return self::byId($id) !== null;
    }

    /** t1199: gravity (jumpsToClear) range; lower values clamp up to 2. */
    public const GRAVITY_MIN = 2.0;
    public const GRAVITY_MAX = 4.0;
    /** t1199: g shown at 100 % (jumpsToClear 2); display g = 9.81·(v − 1). */
    public const EARTH_G = 9.81;

    public static function clampGravity(float $v): float
    {
        return self::clamp($v, self::GRAVITY_MIN, self::GRAVITY_MAX);
    }

    /** Difficulty in 0..1. Higher is harder. */
    public static function power(array $planet): float
    {
        $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), self::GRAVITY_MIN, self::GRAVITY_MAX);
        $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
        $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
        // t1199: kept on the old 1..4 axis so unchanged planets keep their Power.
        $gravity = ($j - 1) / 3;
        $air = (5 - $f) / 4;
        $mass = (3 - $r) / 2.5;
        return ($gravity + $air + $mass) / 3;
    }

    /** Maximum miss chance; displayed Power is 1 − miss / MAX_MISS_CHANCE. */
    public const MAX_MISS_CHANCE = 0.60;
    public const MIN_MISS_CHANCE = 0.05;

    /** Miss chance: 0.60 at power 0, 0.05 at power 1. Unchanged gameplay formula. */
    public static function missChance(array $planet): float
    {
        return self::MAX_MISS_CHANCE - (self::MAX_MISS_CHANCE - self::MIN_MISS_CHANCE) * self::power($planet);
    }

    /** Displayed Power 0–100: 0% miss → 100% Power, 60% miss → 0% Power. */
    public static function displayPower(array $planet): int
    {
        return (int) round((1 - self::missChance($planet) / self::MAX_MISS_CHANCE) * 100);
    }

    public static function missChanceForId(string $id): float
    {
        $p = self::byId($id);
        if ($p === null) {
            $p = self::default();
        }
        return self::missChance($p);
    }

    /** @return array{gravity:float,density:float,newtons:float,power:int,missChance:float} */
    public static function displayValues(array $planet): array
    {
        $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), self::GRAVITY_MIN, self::GRAVITY_MAX);
        $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
        $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
        return [
            'gravity' => self::EARTH_G * ($j - 1),
            'gravityPct' => (int) round(($j - 1) * 100),
            'density' => 0.25 + ((5 - $f) / 4) * 1.60,
            'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
            'power' => self::displayPower($planet),
            'missChance' => self::missChance($planet),
        ];
    }

    /** Public subset sent to clients (no need to ship the full catalog again). */
    public static function present(?string $id): array
    {
        $p = $id ? self::byId($id) : null;
        if ($p === null) {
            $p = self::default();
        }
        $d = self::displayValues($p);
        $colors = [];
        foreach ($p['colors'] ?? [] as $c) {
            if (!is_array($c)) {
                continue;
            }
            $colors[] = [
                'id' => (int) ($c['id'] ?? 0),
                'name' => (string) ($c['name'] ?? ''),
                'hex' => (string) ($c['hex'] ?? '#888'),
                'shape' => (string) ($c['shape'] ?? ''),
                'image' => (string) ($c['image'] ?? ''),
            ];
        }
        return [
            'id' => (string) $p['id'],
            'name' => (string) $p['name'],
            'people' => (string) $p['people'],
            'jumpsToClear' => self::clampGravity((float) $p['jumpsToClear']),
            'fallTime' => (float) $p['fallTime'],
            'riseTime' => (float) $p['riseTime'],
            'miss_chance' => $d['missChance'],
            'display' => $d,
            'colors' => $colors,
        ];
    }

    /** Present a raw planet array (catalog or a validated custom snapshot). */
    public static function presentData(array $p): array
    {
        $d = self::displayValues($p);
        $colors = [];
        foreach ($p['colors'] ?? [] as $c) {
            if (!is_array($c)) {
                continue;
            }
            $colors[] = [
                'id' => (int) ($c['id'] ?? 0),
                'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
                'name' => (string) ($c['name'] ?? ''),
                'hex' => (string) ($c['hex'] ?? '#888'),
                'shape' => (string) ($c['shape'] ?? ''),
                'image' => (string) ($c['image'] ?? ''),
            ];
        }
        return [
            'id' => (string) ($p['id'] ?? ''),
            'name' => (string) ($p['name'] ?? ''),
            'people' => (string) ($p['people'] ?? ''),
            'jumpsToClear' => self::clamp((float) ($p['jumpsToClear'] ?? 2), self::GRAVITY_MIN, self::GRAVITY_MAX),
            'fallTime' => (float) ($p['fallTime'] ?? 3),
            'riseTime' => (float) ($p['riseTime'] ?? 1.5),
            'miss_chance' => $d['missChance'],
            'display' => $d,
            'colors' => $colors,
            'custom' => !empty($p['custom']),
            'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
        ];
    }

    private static function clamp(float $value, float $lo, float $hi): float
    {
        return max($lo, min($hi, $value));
    }
}
