<?php
declare(strict_types=1);

/** Match lifecycle: spawn, plans, fog, commit/playback. */
final class SynhexMatch
{
    public static function config(): array
    {
        if (function_exists('gameConfig')) {
            return gameConfig();
        }
        return require __DIR__.'/game-config.php';
    }

    public static function initial(?int $seed = null, ?array $cfg = null): array
    {
        $cfg ??= self::config();
        $seed ??= random_int(1, 0x7ffffffe);
        $cols = (int)$cfg['grid_cols'];
        $rows = (int)$cfg['grid_rows'];
        $units = [];
        $spawns = [];
        foreach (['w', 'b'] as $team) {
            foreach ($cfg['spawn'][$team] as $spec) {
                [$q, $r] = HexGrid::axial((int)$spec['col'], (int)$spec['row']);
                $id = $team.'-'.$spec['id'];
                $units[] = [
                    'id' => $id,
                    'team' => $team,
                    'role' => $spec['role'],
                    'weapon' => $spec['weapon'],
                    'q' => $q,
                    'r' => $r,
                    'facing' => (int)$spec['facing'],
                    'alive' => true,
                    'remaining' => [],
                    'stationaryPrevAct' => true,
                    'shotTargetPrevAct' => null,
                    'deathTick' => null,
                ];
                $spawns[] = [$q, $r];
            }
        }
        $walls = self::generateWalls($seed, $cfg, $spawns);
        $lastKnown = ['w' => [], 'b' => []];
        foreach ($units as $u) {
            $other = $u['team'] === 'w' ? 'b' : 'w';
            $lastKnown[$other][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => true];
        }
        return [
            'phase' => 'planning',
            'act' => 0,
            'seed' => $seed,
            'grid' => ['cols' => $cols, 'rows' => $rows, 'orientation' => $cfg['hex_orientation'], 'offset' => $cfg['hex_offset']],
            'walls' => $walls,
            'units' => $units,
            'initialUnits' => $units,
            'plans' => ['w' => null, 'b' => null],
            'drafts' => ['w' => null, 'b' => null],
            'committed' => ['w' => false, 'b' => false],
            'acked' => ['w' => false, 'b' => false],
            'timeline' => null,
            'history' => [],
            'lastKnown' => $lastKnown,
            'result' => null,
        ];
    }

    /**
     * @param list<array{0:int,1:int}> $spawns
     * @return list<string>
     */
    public static function generateWalls(int $seed, array $cfg, array $spawns): array
    {
        $cols = (int)$cfg['grid_cols'];
        $rows = (int)$cfg['grid_rows'];
        $density = (float)$cfg['wall_density'];
        $clear = (int)$cfg['wall_clear_radius'];
        $attempts = max(1, (int)$cfg['wall_gen_attempts']);
        $all = HexGrid::allHexes($cols, $rows);
        $protected = [];
        foreach ($spawns as [$q, $r]) {
            foreach ($all as $key => $_) {
                [$qq, $rr] = HexGrid::parse($key);
                if (HexGrid::distance($q, $r, $qq, $rr) <= $clear) {
                    $protected[$key] = true;
                }
            }
        }
        $start = HexGrid::key($spawns[0][0], $spawns[0][1]);
        $mid = intdiv(count($spawns), 2);
        $goal = HexGrid::key($spawns[$mid][0], $spawns[$mid][1]);
        $rng = new SynhexRng($seed);
        $walls = [];
        for ($try = 0; $try < $attempts; $try++) {
            $walls = [];
            foreach ($all as $key => $_) {
                if (isset($protected[$key])) {
                    continue;
                }
                if ($rng->unit() < $density) {
                    $walls[$key] = true;
                }
            }
            $walkable = $all;
            foreach ($walls as $key => $_) {
                unset($walkable[$key]);
            }
            $midCol = intdiv($cols, 2);
            if ($density > 0) {
                for ($row = 2; $row < $rows - 2; $row++) {
                    if ($row % 3 === 0) {
                        continue;
                    }
                    [$q, $r] = HexGrid::axial($midCol, $row);
                    $k = HexGrid::key($q, $r);
                    if (!isset($protected[$k])) {
                        $walls[$k] = true;
                        unset($walkable[$k]);
                    }
                }
            }
            [$sq, $sr] = HexGrid::parse($start);
            [$gq, $gr] = HexGrid::parse($goal);
            if (HexGrid::path($sq, $sr, $gq, $gr, $walkable)) {
                break;
            }
            $density *= 0.85;
        }
        return array_keys($walls);
    }

    public static function isYourTurn(array $s, string $color): bool
    {
        if (($s['phase'] ?? '') === 'planning') {
            return empty($s['committed'][$color]);
        }
        if (($s['phase'] ?? '') === 'playback') {
            return empty($s['acked'][$color]);
        }
        return false;
    }

    public static function playersToNotify(array $g, array $s): array
    {
        $out = [];
        foreach (['w', 'b'] as $color) {
            if (self::isYourTurn($s, $color)) {
                $out[] = $color === 'w' ? $g['white'] : ($g['white'] === $g['a'] ? $g['b'] : $g['a']);
            }
        }
        return $out;
    }

    public static function walkable(array $s): array
    {
        $all = HexGrid::allHexes($s['grid']['cols'], $s['grid']['rows']);
        foreach ($s['walls'] as $key) {
            unset($all[$key]);
        }
        return $all;
    }

    public static function sanitizePlan(array $s, string $color, mixed $plan, array $cfg): array
    {
        if (!is_array($plan)) {
            $plan = [];
        }
        $unitsIn = $plan['units'] ?? $plan;
        if (!is_array($unitsIn)) {
            throw new DomainException('Invalid plan.');
        }
        $own = [];
        foreach ($s['units'] as $u) {
            if ($u['team'] === $color && !empty($u['alive'])) {
                $own[$u['id']] = $u;
            }
        }
        $walkable = self::walkable($s);
        $out = [];
        foreach ($unitsIn as $id => $spec) {
            if (!is_string($id) || !isset($own[$id]) || !is_array($spec)) {
                continue;
            }
            $path = [];
            $prevQ = $own[$id]['q'];
            $prevR = $own[$id]['r'];
            $rawPath = $spec['path'] ?? [];
            if (!is_array($rawPath)) {
                throw new DomainException('Invalid path.');
            }
            foreach ($rawPath as $step) {
                if (!is_array($step) || !isset($step['q'], $step['r'])) {
                    throw new DomainException('Invalid waypoint.');
                }
                $q = (int)$step['q'];
                $r = (int)$step['r'];
                if (!isset($walkable[HexGrid::key($q, $r)]) || HexGrid::distance($prevQ, $prevR, $q, $r) !== 1) {
                    throw new DomainException('Path must walk adjacent open hexes.');
                }
                $item = ['q' => $q, 'r' => $r];
                if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
                    $facing = (int)$step['facing'];
                    if ($facing < 0 || $facing > 5) {
                        throw new DomainException('Facing must be 0–5.');
                    }
                    $item['facing'] = $facing;
                }
                $path[] = $item;
                $prevQ = $q;
                $prevR = $r;
            }
            $entry = ['path' => $path];
            if (isset($spec['facing']) && is_int($spec['facing'])) {
                if ($spec['facing'] < 0 || $spec['facing'] > 5) {
                    throw new DomainException('Facing must be 0–5.');
                }
                $entry['facing'] = $spec['facing'];
            }
            $out[$id] = $entry;
        }
        return ['units' => $out];
    }

    public static function saveDraft(array $s, string $color, mixed $plan, array $cfg): array
    {
        if (($s['phase'] ?? '') !== 'planning' || !empty($s['committed'][$color])) {
            throw new DomainException('Plans are locked for this act.');
        }
        $s['drafts'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
        return $s;
    }

    public static function commit(array $s, string $color, mixed $plan, array $cfg): array
    {
        if (($s['phase'] ?? '') !== 'planning') {
            throw new DomainException('This act is not in planning.');
        }
        if (!empty($s['committed'][$color])) {
            throw new DomainException('You have already locked this plan.');
        }
        $s['plans'][$color] = self::sanitizePlan($s, $color, $plan, $cfg);
        $s['drafts'][$color] = $s['plans'][$color];
        $s['committed'][$color] = true;
        if (!empty($s['committed']['w']) && !empty($s['committed']['b'])) {
            $s = SynhexSim::runAct($s, $cfg);
        }
        return $s;
    }

    public static function ackPlayback(array $s, string $color): array
    {
        if (($s['phase'] ?? '') !== 'playback') {
            throw new DomainException('There is no act to play back.');
        }
        $s['acked'][$color] = true;
        if (!empty($s['acked']['w']) && !empty($s['acked']['b'])) {
            if (!empty($s['result'])) {
                $s['phase'] = 'ended';
            } else {
                $s['phase'] = 'planning';
                $s['timeline'] = null;
                $s['acked'] = ['w' => false, 'b' => false];
                foreach (['w', 'b'] as $team) {
                    $draft = ['units' => []];
                    foreach ($s['units'] as $u) {
                        if ($u['team'] === $team && !empty($u['alive']) && !empty($u['remaining'])) {
                            $draft['units'][$u['id']] = ['path' => $u['remaining']];
                        }
                    }
                    $s['drafts'][$team] = $draft['units'] ? $draft : null;
                }
            }
        }
        return $s;
    }

    public static function visibleUnits(array $s, string $color, array $cfg): array
    {
        $out = [];
        $walls = array_fill_keys($s['walls'], true);
        $byId = [];
        foreach ($s['units'] as $u) {
            $byId[$u['id']] = $u;
        }
        $revealAll = ($s['act'] === 0 && ($s['phase'] ?? '') === 'planning' && !empty($cfg['see_enemies_at_match_start']));
        foreach ($s['units'] as $u) {
            if ($u['team'] === $color) {
                $row = $u;
                $row['hologram'] = false;
                $row['known'] = true;
                $out[] = $row;
                continue;
            }
            $visible = $revealAll || self::seenNow($byId, $u, $color, $walls, $cfg);
            if ($visible) {
                $row = $u;
                $row['hologram'] = false;
                $row['known'] = true;
                $out[] = $row;
                continue;
            }
            $ghost = $s['lastKnown'][$color][$u['id']] ?? null;
            if ($ghost) {
                $out[] = [
                    'id' => $u['id'],
                    'team' => $u['team'],
                    'role' => $u['role'],
                    'weapon' => $u['weapon'],
                    'q' => $ghost['q'],
                    'r' => $ghost['r'],
                    'facing' => $ghost['facing'],
                    'alive' => $ghost['alive'] ?? true,
                    'hologram' => true,
                    'known' => true,
                ];
            }
        }
        return $out;
    }

    private static function seenNow(array $byId, array $enemy, string $viewer, array $walls, array $cfg): bool
    {
        if (empty($enemy['alive'])) {
            return false;
        }
        foreach ($byId as $u) {
            if ($u['team'] !== $viewer || empty($u['alive'])) {
                continue;
            }
            $d = HexGrid::distance($u['q'], $u['r'], $enemy['q'], $enemy['r']);
            if ($d === 0 || $d > (int)$cfg['vision_range']) {
                continue;
            }
            if (HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $enemy['q'], $enemy['r'], (float)$cfg['vision_cone_half_deg'])
                && HexGrid::los($u['q'], $u['r'], $enemy['q'], $enemy['r'], $walls)) {
                return true;
            }
        }
        return false;
    }

    public static function clientView(array $s, string $color, array $cfg): array
    {
        $view = [
            'phase' => $s['phase'],
            'act' => $s['act'],
            'grid' => $s['grid'],
            'walls' => $s['walls'],
            'units' => self::visibleUnits($s, $color, $cfg),
            'committed' => !empty($s['committed'][$color]),
            'opponentCommitted' => !empty($s['committed'][$color === 'w' ? 'b' : 'w']),
            'acked' => !empty($s['acked'][$color]),
            'opponentAcked' => !empty($s['acked'][$color === 'w' ? 'b' : 'w']),
            'draft' => $s['drafts'][$color] ?? $s['plans'][$color] ?? ['units' => []],
            'timeline' => ($s['phase'] === 'playback') ? $s['timeline'] : null,
            'result' => $s['result'] ?? null,
            'rules' => [
                'walkRange' => (int)$cfg['walk_range'],
                'actDurationMs' => (int)$cfg['act_duration_ms'],
                'visionConeHalfDeg' => (float)$cfg['vision_cone_half_deg'],
                'weapons' => [
                    'pistol' => ['rofMs' => (int)$cfg['weapon_pistol_rof_ms']],
                    'smg' => ['rofMs' => (int)$cfg['weapon_smg_rof_ms']],
                    'shotgun' => ['rofMs' => (int)$cfg['weapon_shotgun_rof_ms'], 'pellets' => (int)$cfg['weapon_shotgun_pellets']],
                ],
            ],
        ];
        return $view;
    }

    public static function replayFrames(array $s): array
    {
        $frames = [['act' => 0, 'units' => $s['initialUnits'] ?? $s['units'], 'walls' => $s['walls'], 'grid' => $s['grid'], 'timeline' => null]];
        foreach ($s['history'] ?? [] as $i => $act) {
            $frames[] = [
                'act' => $i + 1,
                'units' => $act['endUnits'] ?? $s['units'],
                'walls' => $s['walls'],
                'grid' => $s['grid'],
                'timeline' => $act,
            ];
        }
        return $frames;
    }

    public static function unitBar(array $s): array
    {
        $cfg = self::config();
        $totals = ['w' => 0, 'b' => 0];
        foreach ($s['units'] as $u) {
            if (empty($u['alive'])) {
                continue;
            }
            $totals[$u['team']] += ($u['role'] === 'vip') ? (int)$cfg['unit_bar_vip'] : (int)$cfg['unit_bar_soldier'];
        }
        return $totals;
    }
}
