<?php
declare(strict_types=1);

/**
 * Append-only block registry shared with the JS client (server/lib/blocks.json).
 * Never reorder entries; new blocks are appended. Thresholds stay in lockstep
 * with src/blocks.js: Terra's first five are free; index 5 costs 500 lifetime
 * points, each next index costs 14.5% more (rounded to a strictly increasing int).
 */
final class Blocks
{
    public const TERRA_COUNT = 5;
    public const FIRST_THRESHOLD = 500;
    public const GROWTH = 1.145;

    private static ?array $all = null;
    private static ?array $byId = null;

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

    /** @return list<array> */
    public static function all(): array
    {
        if (self::$all !== null) {
            return self::$all;
        }
        $raw = file_get_contents(self::path());
        if ($raw === false) {
            throw new RuntimeException('blocks.json ontbreekt.');
        }
        $data = json_decode($raw, true);
        if (!is_array($data) || !isset($data['blocks']) || !is_array($data['blocks'])) {
            throw new RuntimeException('blocks.json is ongeldig.');
        }
        self::$all = [];
        self::$byId = [];
        foreach ($data['blocks'] as $i => $row) {
            if (!is_array($row) || empty($row['id'])) {
                continue;
            }
            $row['_index'] = $i;
            self::$all[] = $row;
            self::$byId[(string) $row['id']] = $row;
        }
        if (count(self::$all) < self::TERRA_COUNT) {
            throw new RuntimeException('blocks.json mist de Terra-blokjes.');
        }
        return self::$all;
    }

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

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

    public static function indexOf(string $id): ?int
    {
        $b = self::byId($id);
        return $b !== null ? (int) $b['_index'] : null;
    }

    public static function isTerra(string $id): bool
    {
        $i = self::indexOf($id);
        return $i !== null && $i < self::TERRA_COUNT;
    }

    /** Lifetime points required to unlock the block at $index (0-based). */
    public static function threshold(int $index): int
    {
        if ($index < self::TERRA_COUNT) {
            return 0;
        }
        $t = self::FIRST_THRESHOLD;
        for ($i = self::TERRA_COUNT; $i < $index; $i++) {
            $next = (int) round($t * self::GROWTH);
            $t = max($t + 1, $next);
        }
        return $t;
    }

    public static function unlocked(int $index, int $points): bool
    {
        return $points >= self::threshold($index);
    }

    public static function unlockedId(string $id, int $points): bool
    {
        $i = self::indexOf($id);
        return $i !== null && self::unlocked($i, $points);
    }

    /** Public list for the client: every block plus its threshold and unlock state. */
    public static function present(int $points): array
    {
        $out = [];
        foreach (self::all() as $i => $b) {
            $need = self::threshold($i);
            $out[] = [
                'id' => (string) $b['id'],
                'name' => (string) ($b['name'] ?? $b['id']),
                'hex' => (string) ($b['hex'] ?? '#888'),
                'shape' => (string) ($b['shape'] ?? ''),
                'image' => (string) ($b['image'] ?? ''),
                'terra' => !empty($b['terra']) || $i < self::TERRA_COUNT,
                'index' => $i,
                'threshold' => $need,
                'unlocked' => $points >= $need,
            ];
        }
        return $out;
    }

    /** Resolve a registry id to a planet-slot colour (with a 0–4 slot id). */
    public static function asColor(string $id, int $slot): ?array
    {
        $b = self::byId($id);
        if ($b === null) {
            return null;
        }
        return [
            'id' => $slot,
            'block' => (string) $b['id'],
            'name' => (string) ($b['name'] ?? $b['id']),
            'hex' => (string) ($b['hex'] ?? '#888'),
            'shape' => (string) ($b['shape'] ?? ''),
            'image' => (string) ($b['image'] ?? ''),
        ];
    }
}
