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

    /** Difficulty in 0..1. Higher is harder. */
    public static function power(array $planet): float
    {
        $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
        $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
        $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
        $gravity = ($j - 1) / 3;
        $air = (5 - $f) / 4;
        $mass = (3 - $r) / 2.5;
        return ($gravity + $air + $mass) / 3;
    }

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

    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), 1, 4);
        $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
        $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
        $power = self::power($planet);
        return [
            'gravity' => 9.81 * $j / 2,
            'density' => 0.25 + ((5 - $f) / 4) * 1.60,
            'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
            'power' => (int) round($power * 100),
            'missChance' => 0.60 - 0.55 * $power,
        ];
    }

    /** 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' => (float) $p['jumpsToClear'],
            'fallTime' => (float) $p['fallTime'],
            'riseTime' => (float) $p['riseTime'],
            'miss_chance' => $d['missChance'],
            'display' => $d,
            'colors' => $colors,
        ];
    }

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