<?php
declare(strict_types=1);

/**
 * Pure, deterministic Allianties rule engine.
 * Server and tests share this. The client replays the same event log.
 *
 * Extra rules (jury, shrinking arena, and future ones) are toggles on the
 * game's `rules` object and are applied only from here, so they can be
 * turned on or off without touching the rest of the stack.
 */
final class Engine
{
    public const TZ = 'Europe/Amsterdam';
    public const STARTING_LIVES = 3;
    public const STARTING_RANGE = 2;
    public const STARTING_AP = 1;
    public const MIN_PLAYERS = 2;
    public const MAX_PLAYERS = 16;
    public const MIN_GRID = 6;
    /** Suggested side: max(6 + ceil(n/2), n + 1), capped at MAX_GRID. */
    public const MAX_GRID = 24;
    public const MIN_ARENA = 3;
    public const DEFAULT_SHRINK_DAYS = 7;
    public const MIN_SHRINK_DAYS = 1;
    public const MAX_SHRINK_DAYS = 30;
    public const NOTE_MAX = 2000;
    public const CHAT_MAX = 1000;
    public const NAME_MAX = 64;
    public const CODE_LEN = 6;

    /** @var list<string> Allowed vis_shots values; first is the default. */
    public const VIS_SHOTS = ['public', 'elim_public', 'known_target', 'elim_known_target'];
    /** @var list<string> */
    public const VIS_GIFTS = ['public', 'known_recipient', 'anonymous'];
    /** @var list<string> */
    public const VIS_AP = ['public', 'within_range', 'hidden'];
    /** @var list<string> */
    public const VIS_RANGE = ['public', 'known_in_range', 'hidden'];
    /** @var list<string> */
    public const VIS_LIVES = ['public', 'within_range', 'hidden'];

    /** @var list<string> */
    public const COLORS = [
        '#e74c3c', '#3498db', '#2ecc71', '#f1c40f',
        '#9b59b6', '#e67e22', '#1abc9c', '#e91e63',
        '#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',
        '#795548', '#607d8b', '#cddc39', '#ff9800',
    ];

    /** Injected unix timestamp for tests; null means time(). */
    public static ?int $now = null;

    public static function now(): int
    {
        return self::$now ?? time();
    }

    public static function defaultRules(): array
    {
        return [
            'jury' => true,
            'shrinking_arena' => false,
            'shrink_interval_days' => self::DEFAULT_SHRINK_DAYS,
            'ceasefire' => false,
            'ceasefire_ranges' => [],
            'ap_loot' => false,
            'ap_time' => '00:00',
            'tz' => self::TZ,
            'vis_shots' => 'public',
            'vis_gifts' => 'public',
            'vis_ap' => 'public',
            'vis_range' => 'public',
            'vis_lives' => 'public',
            'grid' => self::suggestedGrid(1),
            'grid_auto' => true,
        ];
    }

    public static function normalizeRules(array $raw): array
    {
        $d = self::defaultRules();
        $d['jury'] = array_key_exists('jury', $raw) ? (bool) $raw['jury'] : true;
        $d['shrinking_arena'] = !empty($raw['shrinking_arena']);
        $n = isset($raw['shrink_interval_days']) ? (int) $raw['shrink_interval_days'] : self::DEFAULT_SHRINK_DAYS;
        if ($n < self::MIN_SHRINK_DAYS) {
            $n = self::MIN_SHRINK_DAYS;
        }
        if ($n > self::MAX_SHRINK_DAYS) {
            $n = self::MAX_SHRINK_DAYS;
        }
        $d['shrink_interval_days'] = $n;
        $d['ceasefire'] = self::asBool($raw['ceasefire'] ?? false);
        $d['ceasefire_ranges'] = self::normalizeRanges($raw['ceasefire_ranges'] ?? []);
        $d['ap_loot'] = self::asBool($raw['ap_loot'] ?? false);
        $hm = self::parseHm($raw['ap_time'] ?? '00:00');
        $d['ap_time'] = $hm ?? '00:00';
        $d['tz'] = self::validTz($raw['tz'] ?? null);
        $d['vis_shots'] = self::visChoice($raw['vis_shots'] ?? null, self::VIS_SHOTS, 'public');
        $d['vis_gifts'] = self::visChoice($raw['vis_gifts'] ?? null, self::VIS_GIFTS, 'public');
        $d['vis_ap'] = self::visChoice($raw['vis_ap'] ?? null, self::VIS_AP, 'public');
        $d['vis_range'] = self::visChoice($raw['vis_range'] ?? null, self::VIS_RANGE, 'public');
        $d['vis_lives'] = self::visChoice($raw['vis_lives'] ?? null, self::VIS_LIVES, 'public');
        $d['grid_auto'] = array_key_exists('grid_auto', $raw) ? self::asBool($raw['grid_auto']) : true;
        if (array_key_exists('grid', $raw) && $raw['grid'] !== null && $raw['grid'] !== '') {
            $d['grid'] = self::clampGrid((int) $raw['grid']);
        } else {
            $d['grid'] = self::suggestedGrid(1);
        }
        return $d;
    }

    /**
     * Suggested square board side for $n players:
     * max(6 + ceil(n / 2), n + 1), capped at MAX_GRID (24).
     * ceil() rounds halves upward (3 players: ceil(1.5) = 2 → side 8).
     * Hosts may choose any size from MIN_GRID (6) to MAX_GRID (24).
     */
    public static function suggestedGrid(int $n): int
    {
        if ($n < 1) {
            $n = 1;
        }
        $side = max(6 + (int) ceil($n / 2.0), $n + 1);
        return min(self::MAX_GRID, $side);
    }

    /** @deprecated alias of suggestedGrid(); kept for call-site clarity in older tests. */
    public static function gridSize(int $n): int
    {
        return self::suggestedGrid($n);
    }

    public static function clampGrid(int $size): int
    {
        if ($size < self::MIN_GRID) {
            return self::MIN_GRID;
        }
        if ($size > self::MAX_GRID) {
            return self::MAX_GRID;
        }
        return $size;
    }

    /** Smallest side that has enough tiles and meets MIN_GRID. */
    public static function minGridFor(int $n): int
    {
        return max(self::MIN_GRID, (int) ceil(sqrt(max(1, $n))));
    }

    /**
     * True when $size is an allowed side and starting positions for $n
     * players are unique and on the board.
     */
    public static function gridFits(int $size, int $n): bool
    {
        if ($size < self::MIN_GRID || $size > self::MAX_GRID || $size * $size < $n) {
            return false;
        }
        $pos = self::startingPositions($n, $size);
        if (count($pos) !== $n) {
            return false;
        }
        $seen = [];
        foreach ($pos as $p) {
            if (!self::inBounds($size, (int) $p['x'], (int) $p['y'])) {
                return false;
            }
            $k = $p['x'] . ',' . $p['y'];
            if (isset($seen[$k])) {
                return false;
            }
            $seen[$k] = true;
        }
        return true;
    }

    /**
     * If grid_auto is on, set rules.grid to the suggestion for the current
     * player count. Always mirrors rules.grid onto game.grid in the lobby.
     *
     * @param array<string,mixed> $game
     * @return array<string,mixed>
     */
    public static function applyGridSuggestion(array $game): array
    {
        $rules = $game['rules'] ?? self::defaultRules();
        $n = max(1, count($game['players'] ?? []));
        if (!empty($rules['grid_auto'])) {
            $rules['grid'] = self::suggestedGrid($n);
            $game['rules'] = $rules;
        }
        $game['grid'] = (int) ($game['rules']['grid'] ?? self::suggestedGrid($n));
        return $game;
    }

    /** Largest inset that still leaves a MIN_ARENA playable square. */
    public static function maxInset(int $size): int
    {
        return max(0, (int) floor(($size - self::MIN_ARENA) / 2));
    }

    /**
     * Place players evenly on a ring around the centre, on unique tiles,
     * starting at the top and going clockwise. Never on the same tile.
     *
     * @return list<array{x:int,y:int}>
     */
    public static function startingPositions(int $n, int $size): array
    {
        if ($n < 1) {
            return [];
        }
        $cx = ($size - 1) / 2.0;
        $cy = ($size - 1) / 2.0;
        $radius = max(1.0, ($size - 1) / 2.0 - 1.0);
        $used = [];
        $out = [];
        for ($i = 0; $i < $n; $i++) {
            $ang = -M_PI / 2 + ($i * 2 * M_PI / $n);
            $fx = $cx + $radius * cos($ang);
            $fy = $cy + $radius * sin($ang);
            $x = (int) max(0, min($size - 1, (int) round($fx)));
            $y = (int) max(0, min($size - 1, (int) round($fy)));
            $key = $x . ',' . $y;
            if (isset($used[$key])) {
                $found = false;
                for ($d = 1; $d < $size * 2 && !$found; $d++) {
                    for ($dx = -$d; $dx <= $d && !$found; $dx++) {
                        for ($dy = -$d; $dy <= $d; $dy++) {
                            if (max(abs($dx), abs($dy)) !== $d) {
                                continue;
                            }
                            $nx = $x + $dx;
                            $ny = $y + $dy;
                            if ($nx < 0 || $ny < 0 || $nx >= $size || $ny >= $size) {
                                continue;
                            }
                            $k2 = $nx . ',' . $ny;
                            if (!isset($used[$k2])) {
                                $x = $nx;
                                $y = $ny;
                                $key = $k2;
                                $found = true;
                                break;
                            }
                        }
                    }
                }
            }
            $used[$key] = true;
            $out[] = ['x' => $x, 'y' => $y];
        }
        return $out;
    }

    public static function chebyshev(int $x1, int $y1, int $x2, int $y2): int
    {
        return max(abs($x1 - $x2), abs($y1 - $y2));
    }

    public static function inBounds(int $size, int $x, int $y): bool
    {
        return $x >= 0 && $y >= 0 && $x < $size && $y < $size;
    }

    public static function isPassable(int $size, int $inset, int $x, int $y): bool
    {
        if (!self::inBounds($size, $x, $y)) {
            return false;
        }
        return $x >= $inset && $y >= $inset && $x < $size - $inset && $y < $size - $inset;
    }

    /**
     * The host's IANA time zone for ap_time and cease-fire ranges.
     * Unknown or missing values fall back to Europe/Amsterdam.
     */
    public static function validTz(mixed $tz): string
    {
        if (!is_string($tz) || $tz === '' || strlen($tz) > 64) {
            return self::TZ;
        }
        try {
            $z = new DateTimeZone($tz);
        } catch (Throwable $e) {
            return self::TZ;
        }
        $name = $z->getName();
        // Only named zones (no raw offsets like +02:00): those carry DST rules.
        if (!in_array($name, DateTimeZone::listIdentifiers(), true) && $name !== 'UTC') {
            return self::TZ;
        }
        return $name;
    }

    /** Rules' time zone (host's zone at the time of the last rules edit). */
    public static function rulesTz(array $game): string
    {
        return self::validTz(($game['rules'] ?? [])['tz'] ?? null);
    }

    /**
     * Next occurrence of a wall-clock time in $tz (default Europe/Amsterdam) strictly after $from.
     * Used for the per-lobby daily AP time (default 00:00).
     * If that clock time is skipped by a spring-forward DST gap, PHP's
     * DateTime::setTime lands on the first valid instant after the gap.
     */
    public static function nextDistribution(int $from, ?string $hm = null, ?string $tzName = null): int
    {
        $hm = self::parseHm($hm ?? '00:00') ?? '00:00';
        [$h, $min] = array_map('intval', explode(':', $hm));
        $tz = new DateTimeZone(self::validTz($tzName));
        $dt = (new DateTime('@' . $from))->setTimezone($tz);
        $candidate = clone $dt;
        $candidate->setTime($h, $min, 0);
        if ($candidate->getTimestamp() <= $from) {
            $candidate->modify('+1 day');
            $candidate->setTime($h, $min, 0);
        }
        return $candidate->getTimestamp();
    }

    /** Next 00:00 Europe/Amsterdam strictly after $from. */
    public static function nextMidnight(int $from): int
    {
        return self::nextDistribution($from, '00:00');
    }

    /** Today's 00:00 Amsterdam on or before $from. */
    public static function thisMidnight(int $from): int
    {
        $tz = new DateTimeZone(self::TZ);
        $dt = new DateTime('@' . $from);
        $dt->setTimezone($tz);
        $dt->setTime(0, 0, 0);
        return $dt->getTimestamp();
    }

    /**
     * A new lobby (status=lobby) with the host as first member.
     */
    public static function newLobby(
        string $id,
        string $code,
        string $hostId,
        string $hostName,
        ?string $avatar,
        array $rules,
        int $now
    ): array {
        $rules = self::normalizeRules($rules);
        $game = [
            'id' => $id,
            'code' => $code,
            'host_id' => $hostId,
            'status' => 'lobby',
            'created_at' => $now,
            'started_at' => null,
            'finished_at' => null,
            'rules' => $rules,
            'grid' => (int) ($rules['grid'] ?? self::suggestedGrid(1)),
            'day' => 0,
            'next_distribution_at' => null,
            'arena_inset' => 0,
            'winner_id' => null,
            'draw' => false,
            'players' => [
                self::newPlayer($hostId, $hostName, $avatar, 0, $now),
            ],
            'events' => [],
            'votes' => [],
            'notes' => [],
            'messages' => [],
            'event_seq' => 0,
            'version' => 1,
        ];
        return self::applyGridSuggestion($game);
    }

    public static function newPlayer(string $id, string $name, ?string $avatar, int $colorIndex, int $now): array
    {
        $colors = self::COLORS;
        $color = $colors[$colorIndex % count($colors)];
        return [
            'id' => $id,
            'name' => $name,
            'avatar' => $avatar,
            'color' => $color,
            'color_index' => $colorIndex,
            'x' => 0,
            'y' => 0,
            'lives' => self::STARTING_LIVES,
            'ap' => 0,
            'range' => self::STARTING_RANGE,
            'alive' => true,
            'surrendered' => false,
            'joined_at' => $now,
        ];
    }

    public static function playerIndex(array $game, string $userId): ?int
    {
        foreach ($game['players'] as $i => $p) {
            if ($p['id'] === $userId) {
                return (int) $i;
            }
        }
        return null;
    }

    public static function player(array $game, string $userId): ?array
    {
        $i = self::playerIndex($game, $userId);
        return $i === null ? null : $game['players'][$i];
    }

    /** @return list<array> */
    public static function living(array $game): array
    {
        return array_values(array_filter($game['players'], fn ($p) => !empty($p['alive'])));
    }

    public static function occupiedByLiving(array $game, int $x, int $y, ?string $except = null): ?string
    {
        foreach ($game['players'] as $p) {
            if (empty($p['alive'])) {
                continue;
            }
            if ($except !== null && $p['id'] === $except) {
                continue;
            }
            if ((int) $p['x'] === $x && (int) $p['y'] === $y) {
                return $p['id'];
            }
        }
        return null;
    }

    public static function pushEvent(array &$game, string $type, array $data, int $now): array
    {
        $game['event_seq'] = (int) ($game['event_seq'] ?? 0) + 1;
        $game['version'] = (int) ($game['version'] ?? 0) + 1;
        $ev = array_merge([
            'id' => $game['event_seq'],
            't' => $now,
            'type' => $type,
        ], $data);
        $game['events'][] = $ev;
        return $ev;
    }

    /**
     * Join a lobby. Throws RuntimeException with a stable error code.
     */
    public static function join(array $game, string $userId, string $name, ?string $avatar, int $now): array
    {
        if ($game['status'] !== 'lobby') {
            throw new RuntimeException('game_started');
        }
        if (self::playerIndex($game, $userId) !== null) {
            return $game; // already in
        }
        if (count($game['players']) >= self::MAX_PLAYERS) {
            throw new RuntimeException('lobby_full');
        }
        $game['players'][] = self::newPlayer($userId, $name, $avatar, count($game['players']), $now);
        return self::applyGridSuggestion($game);
    }

    public static function leaveLobby(array $game, string $userId, int $now): ?array
    {
        if ($game['status'] !== 'lobby') {
            throw new RuntimeException('game_started');
        }
        $idx = self::playerIndex($game, $userId);
        if ($idx === null) {
            return $game;
        }
        array_splice($game['players'], $idx, 1);
        if (count($game['players']) === 0) {
            return null; // delete lobby
        }
        // Re-index colours; if host left, earliest joiner becomes host.
        foreach ($game['players'] as $i => &$p) {
            $p['color_index'] = $i;
            $p['color'] = self::COLORS[$i % count(self::COLORS)];
        }
        unset($p);
        if ($game['host_id'] === $userId) {
            $game['host_id'] = $game['players'][0]['id'];
        }
        return self::applyGridSuggestion($game);
    }

    public static function setLobbyRules(array $game, string $userId, array $rules): array
    {
        if ($game['status'] !== 'lobby') {
            throw new RuntimeException('game_started');
        }
        if ($game['host_id'] !== $userId) {
            throw new RuntimeException('not_host');
        }
        $game['rules'] = self::normalizeRules(array_merge($game['rules'], $rules));
        return self::applyGridSuggestion($game);
    }

    public static function start(array $game, string $userId, int $now): array
    {
        if ($game['status'] !== 'lobby') {
            throw new RuntimeException('game_started');
        }
        if ($game['host_id'] !== $userId) {
            throw new RuntimeException('not_host');
        }
        $n = count($game['players']);
        if ($n < self::MIN_PLAYERS) {
            throw new RuntimeException('min_players');
        }
        $rules = $game['rules'] ?? self::defaultRules();
        if (!empty($rules['grid_auto'])) {
            $size = self::suggestedGrid($n);
        } else {
            $size = self::clampGrid((int) ($rules['grid'] ?? self::suggestedGrid($n)));
        }
        if (!self::gridFits($size, $n)) {
            throw new RuntimeException('bad_grid');
        }
        $rules['grid'] = $size;
        $game['rules'] = $rules;
        $pos = self::startingPositions($n, $size);
        $game['grid'] = $size;
        $game['status'] = 'running';
        $game['started_at'] = $now;
        $game['day'] = 0;
        $game['arena_inset'] = 0;
        $game['next_distribution_at'] = self::nextDistribution($now, $game['rules']['ap_time'] ?? '00:00', self::rulesTz($game));
        $placed = [];
        foreach ($game['players'] as $i => &$p) {
            $p['x'] = $pos[$i]['x'];
            $p['y'] = $pos[$i]['y'];
            $p['lives'] = self::STARTING_LIVES;
            $p['ap'] = self::STARTING_AP;
            $p['range'] = self::STARTING_RANGE;
            $p['alive'] = true;
            $p['surrendered'] = false;
            $placed[] = [
                'id' => $p['id'],
                'x' => $p['x'],
                'y' => $p['y'],
                'color' => $p['color'],
                'name' => $p['name'],
            ];
        }
        unset($p);
        self::pushEvent($game, 'start', [
            'grid' => $size,
            'players' => $placed,
            'rules' => $game['rules'],
            'spend' => false,
        ], $now);
        return $game;
    }

    /**
     * Catch up daily distributions (AP, jury, shrink) until $now.
     * Safe to call on every request.
     */
    public static function applyDue(array $game, int $now): array
    {
        if ($game['status'] !== 'running') {
            return $game;
        }
        $guard = 0;
        while (
            isset($game['next_distribution_at'])
            && $game['next_distribution_at'] !== null
            && (int) $game['next_distribution_at'] <= $now
            && $game['status'] === 'running'
            && $guard < 4000
        ) {
            $at = (int) $game['next_distribution_at'];
            $game = self::distributeOneDay($game, $at);
            $game['next_distribution_at'] = self::nextDistribution($at, $game['rules']['ap_time'] ?? '00:00', self::rulesTz($game));
            $guard++;
        }
        return $game;
    }

    public static function daysUntilShrink(array $game): ?int
    {
        if ($game['status'] !== 'running' || empty($game['rules']['shrinking_arena'])) {
            return null;
        }
        $size = (int) $game['grid'];
        if ((int) $game['arena_inset'] >= self::maxInset($size)) {
            return null;
        }
        $interval = (int) $game['rules']['shrink_interval_days'];
        $day = (int) $game['day'];
        // Next shrink at day = k*interval for k>=1, i.e. after `interval` midnights.
        $nextAt = (int) (ceil(($day + 1) / $interval) * $interval);
        if ($nextAt <= $day) {
            $nextAt += $interval;
        }
        return $nextAt - $day;
    }

    private static function distributeOneDay(array $game, int $at): array
    {
        $game['day'] = (int) $game['day'] + 1;
        $day = (int) $game['day'];
        $grants = [];
        $jury = null;

        // 1. Shrink first so someone who dies today does not receive AP.
        $shrink = null;
        if (!empty($game['rules']['shrinking_arena'])) {
            $interval = (int) $game['rules']['shrink_interval_days'];
            $size = (int) $game['grid'];
            $inset = (int) $game['arena_inset'];
            if ($interval > 0 && $day % $interval === 0 && $inset < self::maxInset($size)) {
                $result = self::applyShrink($game, $at);
                $game = $result['game'];
                $shrink = $result['report'];
            }
        }

        if ($game['status'] !== 'running') {
            // Finished mid-shrink; still record the day event.
            self::pushEvent($game, 'daily', [
                'day' => $day,
                'grants' => $grants,
                'jury' => $jury,
                'shrink' => $shrink,
                'spend' => false,
            ], $at);
            return $game;
        }

        // 2. Jury: unique or tied living targets each get +1. Votes stay secret.
        if (!empty($game['rules']['jury'])) {
            $jury = self::tallyJury($game);
        }

        // 3. Grant 1 AP to every living player, plus jury bonus.
        foreach ($game['players'] as &$p) {
            if (empty($p['alive'])) {
                continue;
            }
            $add = 1;
            if ($jury && in_array($p['id'], $jury['winners'], true)) {
                $add += 1;
            }
            $p['ap'] = (int) $p['ap'] + $add;
            $grants[$p['id']] = $add;
        }
        unset($p);

        // Votes reset for the new day (changeable until the next distribution).
        $game['votes'] = [];

        self::pushEvent($game, 'daily', [
            'day' => $day,
            'grants' => $grants,
            'jury' => $jury,
            'shrink' => $shrink,
            'spend' => false,
        ], $at);

        $game = self::checkEnd($game, $at);
        return $game;
    }

    /**
     * Tally current votes. Winners are living players with the strictly
     * highest count; on a tie every tied player is a winner (each +1 AP).
     * Players with zero votes never win, even if nobody voted (no award).
     *
     * @return array{winners:list<string>,counts:array<string,int>,votes_cast:int}|null
     */
    public static function tallyJury(array $game): ?array
    {
        $livingIds = [];
        foreach (self::living($game) as $p) {
            $livingIds[$p['id']] = true;
        }
        $counts = [];
        $cast = 0;
        foreach ($game['votes'] as $voter => $target) {
            if (!is_string($voter) || !is_string($target)) {
                continue;
            }
            if (!isset($livingIds[$target])) {
                continue;
            }
            // Voter should be a dead participant.
            $v = self::player($game, $voter);
            if (!$v || !empty($v['alive'])) {
                continue;
            }
            $counts[$target] = ($counts[$target] ?? 0) + 1;
            $cast++;
        }
        if ($cast === 0 || $counts === []) {
            return ['winners' => [], 'counts' => $counts, 'votes_cast' => 0];
        }
        $max = max($counts);
        $winners = [];
        foreach ($counts as $id => $c) {
            if ($c === $max) {
                $winners[] = $id;
            }
        }
        sort($winners);
        return ['winners' => $winners, 'counts' => $counts, 'votes_cast' => $cast];
    }

    /**
     * Advance arena_inset by 1. Players on the new outer ring lose 1 life
     * and, if still alive, are pushed to the nearest free passable tile.
     *
     * @return array{game:array,report:array}
     */
    public static function applyShrink(array $game, int $now): array
    {
        $size = (int) $game['grid'];
        $newInset = (int) $game['arena_inset'] + 1;
        if ($newInset > self::maxInset($size)) {
            return ['game' => $game, 'report' => null];
        }
        $game['arena_inset'] = $newInset;
        $moved = [];
        $hurt = [];
        $killed = [];
        $crushed = [];

        // Deterministic order: by player id.
        $indices = [];
        foreach ($game['players'] as $i => $p) {
            $indices[] = $i;
        }
        usort($indices, function ($a, $b) use ($game) {
            return strcmp($game['players'][$a]['id'], $game['players'][$b]['id']);
        });

        foreach ($indices as $i) {
            $p = $game['players'][$i];
            if (empty($p['alive'])) {
                continue;
            }
            $x = (int) $p['x'];
            $y = (int) $p['y'];
            if (self::isPassable($size, $newInset, $x, $y)) {
                continue;
            }
            // Standing on the new ring: take 1 damage.
            $p['lives'] = (int) $p['lives'] - 1;
            $hurt[] = $p['id'];
            if ($p['lives'] <= 0) {
                $p['lives'] = 0;
                $p['alive'] = false;
                $p['ap'] = 0;
                $killed[] = $p['id'];
                $game['players'][$i] = $p;
                self::pushEvent($game, 'death', [
                    'player' => $p['id'],
                    'cause' => 'shrink',
                    'spend' => false,
                ], $now);
                continue;
            }
            $dest = self::nearestFreeTile($game, $size, $newInset, $x, $y, $p['id']);
            if ($dest === null) {
                // No free inward tile: crushed, eliminated.
                $p['lives'] = 0;
                $p['alive'] = false;
                $p['ap'] = 0;
                $killed[] = $p['id'];
                $crushed[] = $p['id'];
                $game['players'][$i] = $p;
                self::pushEvent($game, 'death', [
                    'player' => $p['id'],
                    'cause' => 'crushed',
                    'spend' => false,
                ], $now);
                continue;
            }
            $from = ['x' => $x, 'y' => $y];
            $p['x'] = $dest['x'];
            $p['y'] = $dest['y'];
            $moved[] = ['id' => $p['id'], 'from' => $from, 'to' => $dest];
            $game['players'][$i] = $p;
        }

        $report = [
            'inset' => $newInset,
            'hurt' => $hurt,
            'killed' => $killed,
            'crushed' => $crushed,
            'moved' => $moved,
        ];
        self::pushEvent($game, 'shrink', array_merge($report, ['spend' => false]), $now);
        $game = self::checkEnd($game, $now);
        return ['game' => $game, 'report' => $report];
    }

    /**
     * Nearest free passable tile, Chebyshev first, then Euclidean to centre,
     * then (y, x) for a stable leftover tie.
     *
     * @return array{x:int,y:int}|null
     */
    public static function nearestFreeTile(
        array $game,
        int $size,
        int $inset,
        int $fromX,
        int $fromY,
        string $moverId
    ): ?array {
        $cx = ($size - 1) / 2.0;
        $cy = ($size - 1) / 2.0;
        $best = null;
        $bestKey = null;
        for ($x = $inset; $x < $size - $inset; $x++) {
            for ($y = $inset; $y < $size - $inset; $y++) {
                if (self::occupiedByLiving($game, $x, $y, $moverId) !== null) {
                    continue;
                }
                $d = self::chebyshev($fromX, $fromY, $x, $y);
                $dc = ($x - $cx) * ($x - $cx) + ($y - $cy) * ($y - $cy);
                $key = sprintf('%04d-%012.6f-%04d-%04d', $d, $dc, $y, $x);
                if ($bestKey === null || $key < $bestKey) {
                    $bestKey = $key;
                    $best = ['x' => $x, 'y' => $y];
                }
            }
        }
        return $best;
    }

    public static function checkEnd(array $game, int $now): array
    {
        if ($game['status'] !== 'running') {
            return $game;
        }
        $alive = self::living($game);
        if (count($alive) === 1) {
            $game['status'] = 'finished';
            $game['finished_at'] = $now;
            $game['winner_id'] = $alive[0]['id'];
            $game['draw'] = false;
            self::pushEvent($game, 'win', [
                'player' => $alive[0]['id'],
                'spend' => false,
            ], $now);
        } elseif (count($alive) === 0) {
            $game['status'] = 'finished';
            $game['finished_at'] = $now;
            $game['winner_id'] = null;
            $game['draw'] = true;
            self::pushEvent($game, 'draw', ['spend' => false], $now);
        }
        return $game;
    }

    /**
     * Legal actions for a viewer (after applyDue).
     *
     * @return array{
     *   move:list<array{x:int,y:int}>,
     *   shoot:list<string>,
     *   give:list<string>,
     *   upgrade:bool,
     *   surrender:bool,
     *   vote:list<string>|null,
     *   my_vote:?string
     * }
     */
    public static function legal(array $game, string $userId, ?int $now = null): array
    {
        $now = $now ?? self::now();

        $empty = [
            'move' => [],
            'shoot' => [],
            'give' => [],
            'upgrade' => false,
            'surrender' => false,
            'vote' => null,
            'my_vote' => null,
            'ceasefire' => false,
        ];
        if ($game['status'] !== 'running') {
            return $empty;
        }
        $me = self::player($game, $userId);
        if (!$me) {
            return $empty;
        }
        $size = (int) $game['grid'];
        $inset = (int) $game['arena_inset'];
        if (empty($me['alive'])) {
            $vote = null;
            $myVote = null;
            if (!empty($game['rules']['jury'])) {
                $vote = [];
                foreach (self::living($game) as $p) {
                    $vote[] = $p['id'];
                }
                $v = $game['votes'][$userId] ?? null;
                $myVote = is_string($v) ? $v : null;
            }
            $empty['vote'] = $vote;
            $empty['my_vote'] = $myVote;
            return $empty;
        }
        $empty['surrender'] = true;
        if ((int) $me['ap'] < 1) {
            return $empty;
        }
        // Moves: 8 neighbours.
        for ($dx = -1; $dx <= 1; $dx++) {
            for ($dy = -1; $dy <= 1; $dy++) {
                if ($dx === 0 && $dy === 0) {
                    continue;
                }
                $x = (int) $me['x'] + $dx;
                $y = (int) $me['y'] + $dy;
                if (!self::isPassable($size, $inset, $x, $y)) {
                    continue;
                }
                if (self::occupiedByLiving($game, $x, $y, $userId) !== null) {
                    continue;
                }
                $empty['move'][] = ['x' => $x, 'y' => $y];
            }
        }
        $range = (int) $me['range'];
        foreach ($game['players'] as $p) {
            if ($p['id'] === $userId || empty($p['alive'])) {
                continue;
            }
            $d = self::chebyshev((int) $me['x'], (int) $me['y'], (int) $p['x'], (int) $p['y']);
            if ($d <= $range) {
                $empty['shoot'][] = $p['id'];
                $empty['give'][] = $p['id'];
            }
        }
        // Upgrade: cap at the board's max Chebyshev distance (covers the board).
        $maxRange = max(1, $size - 1);
        $empty['upgrade'] = (int) $me['range'] < $maxRange;
        if (self::ceasefireActive($game, $now)) {
            $empty['shoot'] = [];
            $empty['ceasefire'] = true;
        } else {
            $empty['ceasefire'] = false;
        }
        return $empty;
    }

    /**
     * Apply a player action. $action = {type, ...}.
     * Types: move, shoot, give, upgrade, surrender, vote.
     */
    public static function applyAction(array $game, string $userId, array $action, int $now): array
    {
        $game = self::applyDue($game, $now);
        if ($game['status'] !== 'running') {
            throw new RuntimeException('game_finished');
        }
        $type = (string) ($action['type'] ?? '');
        $me = self::player($game, $userId);
        if (!$me) {
            throw new RuntimeException('not_in_game');
        }

        if ($type === 'vote') {
            return self::actVote($game, $userId, $action, $now);
        }
        if ($type === 'surrender') {
            return self::actSurrender($game, $userId, $now);
        }
        if (empty($me['alive'])) {
            throw new RuntimeException('dead');
        }
        $legal = self::legal($game, $userId, $now);
        return match ($type) {
            'move' => self::actMove($game, $userId, $action, $legal, $now),
            'shoot' => self::actShoot($game, $userId, $action, $legal, $now),
            'give' => self::actGive($game, $userId, $action, $legal, $now),
            'upgrade' => self::actUpgrade($game, $userId, $legal, $now),
            default => throw new RuntimeException('unknown_action'),
        };
    }

    private static function spendAp(array &$game, string $userId, int $n = 1): void
    {
        $i = self::playerIndex($game, $userId);
        if ($i === null || (int) $game['players'][$i]['ap'] < $n) {
            throw new RuntimeException('no_ap');
        }
        $game['players'][$i]['ap'] = (int) $game['players'][$i]['ap'] - $n;
    }

    private static function actMove(array $game, string $userId, array $action, array $legal, int $now): array
    {
        $x = (int) ($action['x'] ?? -1);
        $y = (int) ($action['y'] ?? -1);
        $ok = false;
        foreach ($legal['move'] as $t) {
            if ((int) $t['x'] === $x && (int) $t['y'] === $y) {
                $ok = true;
                break;
            }
        }
        if (!$ok) {
            throw new RuntimeException('invalid_move');
        }
        self::spendAp($game, $userId, 1);
        $i = self::playerIndex($game, $userId);
        $from = ['x' => (int) $game['players'][$i]['x'], 'y' => (int) $game['players'][$i]['y']];
        $game['players'][$i]['x'] = $x;
        $game['players'][$i]['y'] = $y;
        self::pushEvent($game, 'move', [
            'player' => $userId,
            'from' => $from,
            'to' => ['x' => $x, 'y' => $y],
            'spend' => true,
        ], $now);
        return $game;
    }

    private static function actShoot(array $game, string $userId, array $action, array $legal, int $now): array
    {
        if (self::ceasefireActive($game, $now)) {
            throw new RuntimeException('ceasefire');
        }
        $targetId = (string) ($action['target'] ?? '');
        if (!in_array($targetId, $legal['shoot'], true)) {
            throw new RuntimeException('out_of_range');
        }
        self::spendAp($game, $userId, 1);
        $ti = self::playerIndex($game, $targetId);
        $game['players'][$ti]['lives'] = (int) $game['players'][$ti]['lives'] - 1;
        $livesLeft = (int) $game['players'][$ti]['lives'];
        $killed = false;
        $loot = 0;
        if ($livesLeft <= 0) {
            $game['players'][$ti]['lives'] = 0;
            $game['players'][$ti]['alive'] = false;
            $killed = true;
            // AP loot (lobby option, default off): shooter takes the target's
            // remaining AP on an eliminating shot only. Shrink/surrender do not loot.
            if (!empty($game['rules']['ap_loot'])) {
                $loot = max(0, (int) $game['players'][$ti]['ap']);
                if ($loot > 0) {
                    $si = self::playerIndex($game, $userId);
                    if ($si !== null) {
                        $game['players'][$si]['ap'] = (int) $game['players'][$si]['ap'] + $loot;
                    }
                }
            }
            $game['players'][$ti]['ap'] = 0;
        }
        $shootEv = [
            'player' => $userId,
            'target' => $targetId,
            'lives_left' => max(0, $livesLeft),
            'damage' => 1,
            'killed' => $killed,
            'spend' => true,
        ];
        if ($loot > 0) {
            $shootEv['loot'] = $loot;
        }
        self::pushEvent($game, 'shoot', $shootEv, $now);
        if ($killed) {
            $death = [
                'player' => $targetId,
                'cause' => 'shot',
                'by' => $userId,
                'spend' => false,
            ];
            if ($loot > 0) {
                $death['loot'] = $loot;
            }
            self::pushEvent($game, 'death', $death, $now);
            $game = self::checkEnd($game, $now);
        }
        return $game;
    }

    private static function actGive(array $game, string $userId, array $action, array $legal, int $now): array
    {
        $targetId = (string) ($action['target'] ?? '');
        $amount = (int) ($action['amount'] ?? 0);
        if (!in_array($targetId, $legal['give'], true)) {
            throw new RuntimeException('out_of_range');
        }
        $me = self::player($game, $userId);
        if ($amount < 1 || $amount > (int) $me['ap']) {
            throw new RuntimeException('bad_give');
        }
        self::spendAp($game, $userId, $amount);
        $ti = self::playerIndex($game, $targetId);
        $game['players'][$ti]['ap'] = (int) $game['players'][$ti]['ap'] + $amount;
        self::pushEvent($game, 'give', [
            'player' => $userId,
            'target' => $targetId,
            'amount' => $amount,
            'spend' => true,
        ], $now);
        return $game;
    }

    private static function actUpgrade(array $game, string $userId, array $legal, int $now): array
    {
        if (empty($legal['upgrade'])) {
            throw new RuntimeException('invalid_move');
        }
        self::spendAp($game, $userId, 1);
        $i = self::playerIndex($game, $userId);
        $game['players'][$i]['range'] = (int) $game['players'][$i]['range'] + 1;
        self::pushEvent($game, 'upgrade', [
            'player' => $userId,
            'range' => (int) $game['players'][$i]['range'],
            'spend' => true,
        ], $now);
        return $game;
    }

    private static function actSurrender(array $game, string $userId, int $now): array
    {
        $i = self::playerIndex($game, $userId);
        if (empty($game['players'][$i]['alive'])) {
            throw new RuntimeException('dead');
        }
        $game['players'][$i]['alive'] = false;
        $game['players'][$i]['lives'] = 0;
        $game['players'][$i]['ap'] = 0;
        $game['players'][$i]['surrendered'] = true;
        self::pushEvent($game, 'surrender', [
            'player' => $userId,
            'spend' => false,
        ], $now);
        self::pushEvent($game, 'death', [
            'player' => $userId,
            'cause' => 'surrender',
            'spend' => false,
        ], $now);
        return self::checkEnd($game, $now);
    }

    private static function actVote(array $game, string $userId, array $action, int $now): array
    {
        if (empty($game['rules']['jury'])) {
            throw new RuntimeException('cannot_vote');
        }
        $me = self::player($game, $userId);
        if (!$me || !empty($me['alive'])) {
            throw new RuntimeException('cannot_vote');
        }
        $targetId = (string) ($action['target'] ?? '');
        $t = self::player($game, $targetId);
        if (!$t || empty($t['alive'])) {
            throw new RuntimeException('bad_vote');
        }
        $game['votes'][$userId] = $targetId;
        // Votes are secret: no public event, but version bumps so polls refresh.
        $game['_vote_updated'] = $now;
        $game['version'] = (int) ($game['version'] ?? 0) + 1;
        return $game;
    }

    public static function setNote(array $game, string $viewerId, string $subjectId, string $text): array
    {
        if (self::playerIndex($game, $viewerId) === null) {
            throw new RuntimeException('not_in_game');
        }
        if (self::playerIndex($game, $subjectId) === null) {
            throw new RuntimeException('not_in_game');
        }
        $text = trim($text);
        if (mb_strlen($text) > self::NOTE_MAX) {
            $text = mb_substr($text, 0, self::NOTE_MAX);
        }
        $key = $viewerId . "\0" . $subjectId;
        if ($text === '') {
            unset($game['notes'][$key]);
        } else {
            $game['notes'][$key] = $text;
        }
        $game['version'] = (int) ($game['version'] ?? 0) + 1;
        return $game;
    }

    public static function addMessage(array $game, string $fromId, string $toId, string $text, int $now): array
    {
        if (self::playerIndex($game, $fromId) === null || self::playerIndex($game, $toId) === null) {
            throw new RuntimeException('not_in_game');
        }
        if ($fromId === $toId) {
            throw new RuntimeException('invalid_move');
        }
        $text = trim($text);
        if ($text === '' || mb_strlen($text) > self::CHAT_MAX) {
            throw new RuntimeException('bad_give');
        }
        if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $text)) {
            throw new RuntimeException('bad_give');
        }
        $game['messages'][] = [
            'id' => count($game['messages']) + 1,
            'from' => $fromId,
            'to' => $toId,
            'text' => $text,
            't' => $now,
        ];
        $game['version'] = (int) ($game['version'] ?? 0) + 1;
        return $game;
    }

    /**
     * Viewer-specific presentation: hide others' votes and notes, hide
     * other people's private chats, include legal actions and shrink ETA.
     */

    public static function visChoice(mixed $raw, array $allowed, string $default): string
    {
        if (is_string($raw) && in_array($raw, $allowed, true)) {
            return $raw;
        }
        return $default;
    }

    /**
     * Per-viewer player card. Own lives/AP/range are always present.
     * Movement, identity, and alive/dead are always public.
     * Hidden numeric stats are omitted (null) so the API does not leak them.
     *
     * @param array<string,mixed> $game
     * @param array<string,mixed> $p
     * @return array<string,mixed>
     */
    public static function presentPlayer(array $game, array $p, string $viewerId, string $noteKey): array
    {
        $rules = $game['rules'] ?? self::defaultRules();
        $isSelf = $p['id'] === $viewerId;
        $out = [
            'id' => $p['id'],
            'name' => $p['name'],
            'avatar' => $p['avatar'],
            'color' => $p['color'],
            'x' => (int) $p['x'],
            'y' => (int) $p['y'],
            'alive' => !empty($p['alive']),
            'surrendered' => !empty($p['surrendered']),
            'is_you' => $isSelf,
            'is_host' => $p['id'] === $game['host_id'],
            'note' => $game['notes'][$noteKey] ?? '',
            'lives' => null,
            'ap' => null,
            'range' => null,
        ];
        if (self::canSeeStat($game, $viewerId, $p, 'vis_lives')) {
            $out['lives'] = (int) $p['lives'];
        }
        if (self::canSeeStat($game, $viewerId, $p, 'vis_ap')) {
            $out['ap'] = (int) $p['ap'];
        }
        if ($isSelf || ($rules['vis_range'] ?? 'public') === 'public') {
            $out['range'] = (int) $p['range'];
        } elseif (($rules['vis_range'] ?? 'public') === 'known_in_range'
            && self::viewerInRangeOf($game, $viewerId, $p)) {
            $out['range'] = (int) $p['range'];
        }
        return $out;
    }

    /**
     * True when the viewer is within $subject's current firing range
     * (Chebyshev, including diagonals). Used for vis_range = known_in_range.
     *
     * @param array<string,mixed> $game
     * @param array<string,mixed> $subject
     */
    public static function viewerInRangeOf(array $game, string $viewerId, array $subject): bool
    {
        $v = self::player($game, $viewerId);
        if ($v === null) {
            return false;
        }
        $dist = self::chebyshev((int) $v['x'], (int) $v['y'], (int) $subject['x'], (int) $subject['y']);
        return $dist <= (int) $subject['range'];
    }

    /**
     * True when $subject is within the VIEWER's current firing range
     * (Chebyshev ≤ the viewer's range). Used for vis_ap / vis_lives =
     * within_range. This is the opposite criterion of viewerInRangeOf.
     *
     * @param array<string,mixed> $game
     * @param array<string,mixed> $subject
     */
    public static function subjectInViewerRange(array $game, string $viewerId, array $subject): bool
    {
        $v = self::player($game, $viewerId);
        if ($v === null) {
            return false;
        }
        $dist = self::chebyshev((int) $v['x'], (int) $v['y'], (int) $subject['x'], (int) $subject['y']);
        return $dist <= (int) $v['range'];
    }

    /**
     * Whether the viewer may see a numeric stat (lives or AP) of $subject.
     * Own data is always visible. "within_range" uses the viewer's range.
     *
     * @param array<string,mixed> $game
     * @param array<string,mixed> $subject
     */
    public static function canSeeStat(array $game, string $viewerId, array $subject, string $ruleKey): bool
    {
        if (($subject['id'] ?? '') === $viewerId) {
            return true;
        }
        $mode = ($game['rules'] ?? [])[$ruleKey] ?? 'public';
        if ($mode === 'public') {
            return true;
        }
        if ($mode === 'within_range') {
            return self::subjectInViewerRange($game, $viewerId, $subject);
        }
        return false; // hidden, or unknown
    }

    /**
     * Whether $viewerId may see a shot event (who shot whom).
     * The shooter always sees their own shot.
     */
    public static function canSeeShot(array $rules, string $viewerId, string $shooter, string $target, bool $killed): bool
    {
        if ($viewerId === $shooter) {
            return true;
        }
        $mode = $rules['vis_shots'] ?? 'public';
        return match ($mode) {
            'public' => true,
            'elim_public' => $killed || $viewerId === $target,
            'known_target' => $viewerId === $target,
            'elim_known_target' => $killed && $viewerId === $target,
            default => true,
        };
    }

    /**
     * Filter the stored event log for one viewer. Hidden events are omitted
     * entirely (no generic marker — a tick would leak that something happened).
     * Returns clones; the stored game is never mutated.
     *
     * @return list<array<string,mixed>>
     */
    public static function filterEvents(array $game, string $viewerId): array
    {
        $out = [];
        foreach ($game['events'] ?? [] as $ev) {
            $f = self::filterEvent($game, $ev, $viewerId);
            if ($f !== null) {
                $out[] = $f;
            }
        }
        return $out;
    }

    /**
     * @param array<string,mixed> $ev
     * @return array<string,mixed>|null
     */
    public static function filterEvent(array $game, array $ev, string $viewerId): ?array
    {
        $rules = $game['rules'] ?? self::defaultRules();
        $type = $ev['type'] ?? '';
        $copy = $ev; // shallow copy; nested arrays are replaced when stripped

        if ($type === 'shoot') {
            $shooter = (string) ($ev['player'] ?? '');
            $target = (string) ($ev['target'] ?? '');
            $killed = !empty($ev['killed']);
            if (!self::canSeeShot($rules, $viewerId, $shooter, $target, $killed)) {
                return null;
            }
            // Remaining lives belong to the target: visible per vis_lives.
            $targetP = self::player($game, $target);
            if (!$targetP || !self::canSeeStat($game, $viewerId, $targetP, 'vis_lives')) {
                unset($copy['lives_left']);
            }
            $copy['damage'] = (int) ($ev['damage'] ?? 1);
            // Loot is AP the shooter gained: visible per vis_ap on the shooter
            // (the shooter always sees it via canSeeStat self).
            if (isset($copy['loot'])) {
                $shooterP = self::player($game, $shooter);
                if (!$shooterP || !self::canSeeStat($game, $viewerId, $shooterP, 'vis_ap')) {
                    unset($copy['loot']);
                }
            }
            return $copy;
        }

        if ($type === 'give') {
            $giver = (string) ($ev['player'] ?? '');
            $recipient = (string) ($ev['target'] ?? '');
            $mode = $rules['vis_gifts'] ?? 'public';
            if ($viewerId === $giver || $mode === 'public') {
                return $copy;
            }
            if ($mode === 'known_recipient' && $viewerId === $recipient) {
                return $copy;
            }
            if ($mode === 'anonymous' && $viewerId === $recipient) {
                unset($copy['player']);
                $copy['anonymous'] = true;
                return $copy;
            }
            return null;
        }

        if ($type === 'upgrade') {
            $who = (string) ($ev['player'] ?? '');
            if ($viewerId === $who) {
                return $copy;
            }
            $mode = $rules['vis_range'] ?? 'public';
            if ($mode === 'public') {
                return $copy;
            }
            if ($mode === 'hidden') {
                return null;
            }
            // known_in_range: visible iff the viewer may currently see that player's range.
            $subj = self::player($game, $who);
            if ($subj && self::viewerInRangeOf($game, $viewerId, $subj)) {
                return $copy;
            }
            return null;
        }

        if ($type === 'death') {
            // Death (alive=false) is always public. Strip "by" if the eliminating
            // shot is not visible to this viewer, so the killer is not leaked.
            $cause = $ev['cause'] ?? '';
            if ($cause === 'shot' && isset($ev['by'])) {
                $killer = (string) $ev['by'];
                $victim = (string) ($ev['player'] ?? '');
                if (!self::canSeeShot($rules, $viewerId, $killer, $victim, true)) {
                    unset($copy['by']);
                }
                if (isset($copy['loot'])) {
                    $killerP = self::player($game, $killer);
                    if (!$killerP || !self::canSeeStat($game, $viewerId, $killerP, 'vis_ap')) {
                        unset($copy['loot']);
                    }
                }
            }
            return $copy;
        }

        if ($type === 'daily') {
            $mode = $rules['vis_ap'] ?? 'public';
            if ($mode !== 'public') {
                $grants = $ev['grants'] ?? [];
                if (is_array($grants)) {
                    $kept = [];
                    foreach ($grants as $id => $amt) {
                        $subj = self::player($game, (string) $id);
                        if ($subj && self::canSeeStat($game, $viewerId, $subj, 'vis_ap')) {
                            $kept[(string) $id] = $amt;
                        }
                    }
                    $copy['grants'] = $kept;
                }
            }
            // Jury winners stay public (the announced result). Vote counts, if
            // present, are not needed by the client; strip to keep votes secret.
            if (isset($copy['jury']) && is_array($copy['jury'])) {
                $jury = $copy['jury'];
                unset($jury['counts']);
                $copy['jury'] = $jury;
            }
            return $copy;
        }

        if ($type === 'shrink') {
            // Movement in the report is public. The explicit "hurt" list leaks
            // a life loss when lives are hidden — keep only the viewer's own id.
            if (($rules['vis_lives'] ?? 'public') !== 'public') {
                $hurt = $ev['hurt'] ?? [];
                $copy['hurt'] = array_values(array_filter(
                    is_array($hurt) ? $hurt : [],
                    function ($id) use ($game, $viewerId) {
                        $subj = self::player($game, (string) $id);
                        return $subj && self::canSeeStat($game, $viewerId, $subj, 'vis_lives');
                    }
                ));
            }
            return $copy;
        }

        // move, start, surrender, win, draw, shrink deaths: always visible.
        return $copy;
    }

        public static function present(array $game, string $viewerId, ?int $now = null): array
    {
        $now = $now ?? self::now();
        $legal = $game['status'] === 'running' ? self::legal($game, $viewerId, $now) : [
            'move' => [], 'shoot' => [], 'give' => [], 'upgrade' => false,
            'surrender' => false, 'vote' => null, 'my_vote' => null,
        ];
        $players = [];
        foreach ($game['players'] as $p) {
            $noteKey = $viewerId . "\0" . $p['id'];
            $players[] = self::presentPlayer($game, $p, $viewerId, $noteKey);
        }
        $messages = [];
        foreach ($game['messages'] as $m) {
            if ($m['from'] === $viewerId || $m['to'] === $viewerId) {
                $messages[] = $m;
            }
        }
        $events = self::filterEvents($game, $viewerId);
        $shrinkIn = self::daysUntilShrink($game);
        return [
            'id' => $game['id'],
            'code' => $game['code'],
            'host_id' => $game['host_id'],
            'status' => $game['status'],
            'created_at' => $game['created_at'],
            'started_at' => $game['started_at'],
            'finished_at' => $game['finished_at'],
            'rules' => $game['rules'],
            'grid' => (int) $game['grid'],
            'day' => (int) $game['day'],
            'next_distribution_at' => $game['next_distribution_at'],
            'arena_inset' => (int) $game['arena_inset'],
            'max_inset' => self::maxInset((int) $game['grid']),
            'shrink_in_days' => $shrinkIn,
            'winner_id' => $game['winner_id'],
            'draw' => !empty($game['draw']),
            'players' => $players,
            'events' => $events,
            'messages' => $messages,
            'legal' => $legal,
            'you' => $viewerId,
            'timezone' => self::rulesTz($game),
            'version' => (int) ($game['version'] ?? $game['event_seq'] ?? 0),
            'server_now' => $now,
            'ceasefire' => self::ceasefireInfo($game, $now),
        ];
    }

    public static function lobbyView(array $game, string $viewerId): array
    {
        $players = [];
        foreach ($game['players'] as $p) {
            $players[] = [
                'id' => $p['id'],
                'name' => $p['name'],
                'avatar' => $p['avatar'],
                'color' => $p['color'],
                'is_you' => $p['id'] === $viewerId,
                'is_host' => $p['id'] === $game['host_id'],
            ];
        }
        return [
            'id' => $game['id'],
            'code' => $game['code'],
            'host_id' => $game['host_id'],
            'status' => $game['status'],
            'created_at' => $game['created_at'],
            'rules' => $game['rules'],
            'players' => $players,
            'can_start' => $game['status'] === 'lobby'
                && $game['host_id'] === $viewerId
                && count($game['players']) >= self::MIN_PLAYERS,
            'you' => $viewerId,
            'timezone' => self::rulesTz($game),
        ];
    }

    public static function asBool(mixed $v): bool
    {
        if (is_bool($v)) {
            return $v;
        }
        if (is_int($v) || is_float($v)) {
            return $v != 0;
        }
        if (!is_string($v)) {
            return (bool) $v;
        }
        $s = strtolower(trim($v));
        return !in_array($s, ['', '0', 'false', 'off', 'no', 'null'], true);
    }

    /**
     * Normalise "HH:MM"-"HH:MM" ranges. Invalid entries are dropped.
     * A range may wrap midnight (start > end). Zero-length (start==end) is dropped.
     *
     * @param mixed $raw
     * @return list<array{start:string,end:string}>
     */
    public static function normalizeRanges(mixed $raw): array
    {
        if (!is_array($raw)) {
            return [];
        }
        $out = [];
        $seen = [];
        foreach ($raw as $r) {
            if (!is_array($r)) {
                continue;
            }
            $start = self::parseHm($r['start'] ?? $r[0] ?? null);
            $end = self::parseHm($r['end'] ?? $r[1] ?? null);
            if ($start === null || $end === null || $start === $end) {
                continue;
            }
            $key = $start . '-' . $end;
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;
            $out[] = ['start' => $start, 'end' => $end];
        }
        usort($out, fn ($a, $b) => strcmp($a['start'], $b['start']));
        return array_slice($out, 0, 12);
    }

    /** @return string|null "HH:MM" */
    public static function parseHm(mixed $v): ?string
    {
        if (is_int($v)) {
            if ($v < 0 || $v > 23 * 60 + 59) {
                return null;
            }
            return sprintf('%02d:%02d', intdiv($v, 60), $v % 60);
        }
        if (!is_string($v)) {
            return null;
        }
        $v = trim($v);
        if (!preg_match('/^(\d{1,2}):(\d{2})$/', $v, $m)) {
            return null;
        }
        $h = (int) $m[1];
        $min = (int) $m[2];
        if ($h > 23 || $min > 59) {
            return null;
        }
        return sprintf('%02d:%02d', $h, $min);
    }

    public static function hmToMinutes(string $hm): int
    {
        [$h, $m] = array_map('intval', explode(':', $hm));
        return $h * 60 + $m;
    }

    /**
     * Convert a local Europe/Amsterdam wall-clock on a calendar date to unix.
     * Uses midnight + hours/minutes so DST spring-forward skips and
     * fall-back uses PHP's first occurrence, then addition continues correctly.
     */
    public static function amsterdamWallclock(string $ymd, string $hm, ?string $tzName = null): int
    {
        $tz = new DateTimeZone(self::validTz($tzName));
        $dt = new DateTime($ymd . ' 00:00:00', $tz);
        $mins = self::hmToMinutes($hm);
        if ($mins > 0) {
            $dt->modify('+' . $mins . ' minutes');
        }
        return $dt->getTimestamp();
    }

    /**
     * Merged cease-fire intervals as [start_ts, end_ts] covering yesterday
     * through two days ahead, so midnight wraps and DST are exact.
     *
     * @return list<array{0:int,1:int}>
     */
    public static function ceasefireIntervals(array $ranges, int $now, ?string $tzName = null): array
    {
        if ($ranges === []) {
            return [];
        }
        $tzName = self::validTz($tzName);
        $tz = new DateTimeZone($tzName);
        $anchor = (new DateTime('@' . $now))->setTimezone($tz);
        $intervals = [];
        for ($d = -1; $d <= 3; $d++) {
            $day = (clone $anchor)->modify(($d >= 0 ? '+' : '') . $d . ' day');
            $ymd = $day->format('Y-m-d');
            $next = (clone $day)->modify('+1 day')->format('Y-m-d');
            foreach ($ranges as $r) {
                $startM = self::hmToMinutes($r['start']);
                $endM = self::hmToMinutes($r['end']);
                $startTs = self::amsterdamWallclock($ymd, $r['start'], $tzName);
                if ($endM > $startM) {
                    $endTs = self::amsterdamWallclock($ymd, $r['end'], $tzName);
                } else {
                    // Wraps midnight: ends on the next calendar day.
                    $endTs = self::amsterdamWallclock($next, $r['end'], $tzName);
                }
                if ($endTs > $startTs) {
                    $intervals[] = [$startTs, $endTs];
                }
            }
        }
        if ($intervals === []) {
            return [];
        }
        usort($intervals, fn ($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
        $merged = [];
        foreach ($intervals as $iv) {
            if ($merged === [] || $iv[0] > $merged[count($merged) - 1][1]) {
                $merged[] = $iv;
            } else {
                $merged[count($merged) - 1][1] = max($merged[count($merged) - 1][1], $iv[1]);
            }
        }
        return $merged;
    }

    public static function ceasefireActive(array $game, int $now): bool
    {
        $info = self::ceasefireInfo($game, $now);
        return $info !== null && !empty($info['active']);
    }

    /**
     * @return array{enabled:bool,active:bool,until:?int,seconds:int}|null
     *         null when the rule is off or there are no ranges.
     */
    public static function ceasefireInfo(array $game, int $now): ?array
    {
        $rules = $game['rules'] ?? [];
        if (empty($rules['ceasefire'])) {
            return null;
        }
        $ranges = self::normalizeRanges($rules['ceasefire_ranges'] ?? []);
        if ($ranges === []) {
            return null;
        }
        $intervals = self::ceasefireIntervals($ranges, $now, self::rulesTz($game));
        $active = false;
        $until = null;
        foreach ($intervals as $iv) {
            if ($now >= $iv[0] && $now < $iv[1]) {
                $active = true;
                $until = $iv[1];
                break;
            }
            if ($iv[0] > $now && ($until === null || $iv[0] < $until)) {
                $until = $iv[0];
            }
        }
        $seconds = $until !== null ? max(0, $until - $now) : 0;
        return [
            'enabled' => true,
            'active' => $active,
            'until' => $until,
            'seconds' => $seconds,
            'ranges' => $ranges,
        ];
    }

    public static function generateCode(): string
    {
        // Crockford-ish, no 0/O/I/1/L.
        $alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
        $len = strlen($alphabet);
        $code = '';
        for ($i = 0; $i < self::CODE_LEN; $i++) {
            $code .= $alphabet[random_int(0, $len - 1)];
        }
        return $code;
    }

    public static function generateId(): string
    {
        return bin2hex(random_bytes(12));
    }
}
