<?php
declare(strict_types=1);

/** Frozen-Synapse-style simultaneous act simulation. */
final class SynhexSim
{
    /**
     * Run one locked act. Mutates/returns a new state with timeline, updated units, fog, leftover paths.
     */
    public static function runAct(array $s, array $cfg): array
    {
        $tickMs = max(1, (int)$cfg['sim_tick_ms']);
        $duration = max($tickMs, (int)$cfg['act_duration_ms']);
        $ticks = intdiv($duration, $tickMs);
        $walk = max(1, (int)$cfg['walk_range']);
        $stepTicks = max(1, intdiv($ticks, $walk));
        $walls = array_fill_keys($s['walls'], true);
        $rng = new SynhexRng(((int)$s['seed'] ^ (($s['act'] + 1) * 10007)) & 0x7fffffff);

        $units = [];
        foreach ($s['units'] as $u) {
            $units[$u['id']] = $u + [
                'alive' => $u['alive'] ?? true,
                'remaining' => $u['remaining'] ?? [],
                'thisMoved' => false,
                'thisTargets' => [],
                'lastShotAt' => -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'],
                'deathTick' => $u['deathTick'] ?? null,
            ];
        }

        foreach (['w', 'b'] as $team) {
            $plan = $s['plans'][$team]['units'] ?? [];
            if (!is_array($plan)) {
                continue;
            }
            foreach ($plan as $id => $spec) {
                if (!isset($units[$id]) || $units[$id]['team'] !== $team || !$units[$id]['alive']) {
                    continue;
                }
                $path = self::normalizePath($spec['path'] ?? []);
                $units[$id]['remaining'] = $path;
                if ($path === [] && isset($spec['facing']) && is_int($spec['facing'])) {
                    $units[$id]['facing'] = ($spec['facing'] % 6 + 6) % 6;
                }
            }
        }

        return self::simulate($s, $cfg, $units, $walls, $rng, $tickMs, $duration, $ticks, $walk, $stepTicks);
    }

    private static function simulate(array $s, array $cfg, array $units, array $walls, SynhexRng $rng, int $tickMs, int $duration, int $ticks, int $walk, int $stepTicks): array
    {
        // Reset movement bookkeeping from the draft above.
        foreach ($units as $id => &$u) {
            $u['stepsTaken'] = 0;
            $u['thisMoved'] = false;
            $u['thisTargets'] = [];
            $u['lastShotAt'] = -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'];
        }
        unset($u);

        $shots = [];
        $kills = [];
        $visibleEver = ['w' => [], 'b' => []];
        $firedTicks = [];
        $snapshots = [];
        $deathTick = ['w' => null, 'b' => null];

        $recordSnap = static function (int $t) use (&$snapshots, &$units): void {
            $snapshots[] = ['t' => $t, 'units' => self::publicUnits($units)];
        };
        $recordSnap(0);

        for ($t = 0; $t <= $ticks; $t++) {
            $steppedIds = [];
            if ($t > 0 && $t % $stepTicks === 0) {
                foreach ($units as $id => &$u) {
                    if (!$u['alive'] || $u['stepsTaken'] >= $walk || !$u['remaining']) {
                        continue;
                    }
                    $next = $u['remaining'][0];
                    $nq = (int)$next['q'];
                    $nr = (int)$next['r'];
                    if (isset($walls[HexGrid::key($nq, $nr)]) || !HexGrid::inBounds($nq, $nr, $s['grid']['cols'], $s['grid']['rows'])) {
                        $u['remaining'] = [];
                        continue;
                    }
                    if (HexGrid::distance($u['q'], $u['r'], $nq, $nr) !== 1) {
                        $u['remaining'] = [];
                        continue;
                    }
                    array_shift($u['remaining']);
                    $u['q'] = $nq;
                    $u['r'] = $nr;
                    $u['thisMoved'] = true;
                    $u['stepsTaken']++;
                    $steppedIds[$id] = true;
                    if (array_key_exists('facing', $next) && $next['facing'] !== null && $next['facing'] !== '') {
                        $u['facing'] = ((int)$next['facing'] % 6 + 6) % 6;
                    }
                }
                unset($u);
            }

            $now = $t * $tickMs;
            $intended = self::intendedShots($units, $walls, $cfg, $now);
            $focus = [];
            foreach ($intended as $id => $target) {
                $focus[$target] = ($focus[$target] ?? 0) + 1;
            }
            $aimedAt = array_flip($intended);

            foreach ($intended as $id => $targetId) {
                $shooter = $units[$id];
                $weapon = $shooter['weapon'];
                $rof = (int)$cfg['weapon_'.$weapon.'_rof_ms'];
                $pellets = $weapon === 'shotgun' ? (int)$cfg['weapon_shotgun_pellets'] : 1;
                $acc = self::accuracy($cfg, $units, $id, $targetId, $intended, $focus, $aimedAt, $walls, isset($steppedIds[$id]), isset($steppedIds[$targetId]));
                $units[$id]['lastShotAt'] = $now;
                $units[$id]['thisTargets'][$targetId] = true;
                $firedTicks[$id] = $t;
                $aims = self::pelletAims($shooter, $units[$targetId], $pellets, (int)$cfg['weapon_shotgun_spread']);
                foreach ($aims as $aim) {
                    $victim = self::rayVictimToward($units, $walls, $shooter, $targetId, $aim[0], $aim[1], (int)$cfg['shot_range'], $cfg['friendly_fire']);
                    $hit = false;
                    if ($victim !== null) {
                        $chance = $victim === $targetId ? $acc : (int)$cfg['base_accuracy'];
                        $hit = $rng->chance($chance);
                        if ($hit && $units[$victim]['alive']) {
                            $units[$victim]['alive'] = false;
                            $units[$victim]['deathTick'] = $t;
                            if (($units[$victim]['role'] ?? '') === 'vip' && $deathTick[$units[$victim]['team']] === null) {
                                $deathTick[$units[$victim]['team']] = $t;
                            }
                            $kills[] = ['t' => $now, 'id' => $victim, 'by' => $id, 'weapon' => $weapon];
                        }
                    }
                    $shots[] = [
                        't' => $now,
                        'id' => $id,
                        'target' => $targetId,
                        'victim' => $victim,
                        'hit' => $hit,
                        'weapon' => $weapon,
                        'accuracy' => $acc,
                        'aim' => ['q' => $aim[0], 'r' => $aim[1]],
                    ];
                }
            }

            $seen = self::visibility($units, $walls, $cfg, $firedTicks, $t);
            foreach (['w', 'b'] as $team) {
                foreach ($seen[$team] as $oid) {
                    $visibleEver[$team][$oid] = true;
                }
            }

            if ($t === 0 || $t === $ticks || $steppedIds) {
                $recordSnap($now);
            }
        }

        $endUnits = [];
        foreach ($units as $u) {
            $prevTargets = array_keys($u['thisTargets']);
            $endUnits[] = [
                'id' => $u['id'],
                'team' => $u['team'],
                'role' => $u['role'],
                'weapon' => $u['weapon'],
                'q' => $u['q'],
                'r' => $u['r'],
                'facing' => $u['facing'],
                'alive' => $u['alive'],
                'remaining' => array_values($u['remaining']),
                'stationaryPrevAct' => !$u['thisMoved'],
                'shotTargetPrevAct' => count($prevTargets) === 1 ? $prevTargets[0] : (count($prevTargets) > 1 ? '*' : null),
                'deathTick' => $u['deathTick'],
            ];
        }

        $lastKnown = $s['lastKnown'] ?? ['w' => [], 'b' => []];
        foreach (['w', 'b'] as $team) {
            foreach ($endUnits as $u) {
                if ($u['team'] === $team) {
                    continue;
                }
                $seen = isset($visibleEver[$team][$u['id']]) || isset($firedTicks[$u['id']]);
                if ($seen || ($s['act'] === 0 && !empty($cfg['see_enemies_at_match_start']))) {
                    $lastKnown[$team][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => $u['alive']];
                }
            }
        }

        $winner = null;
        $reason = null;
        if ($deathTick['w'] !== null && $deathTick['b'] !== null) {
            if ($deathTick['w'] === $deathTick['b']) {
                $reason = 'Both VIPs fell';
            } else {
                $winner = $deathTick['w'] < $deathTick['b'] ? 'b' : 'w';
                $reason = 'VIP eliminated';
            }
        } elseif ($deathTick['w'] !== null) {
            $winner = 'b';
            $reason = 'VIP eliminated';
        } elseif ($deathTick['b'] !== null) {
            $winner = 'w';
            $reason = 'VIP eliminated';
        }

        $timeline = [
            'act' => $s['act'] + 1,
            'durationMs' => $duration,
            'tickMs' => $tickMs,
            'snapshots' => self::dedupeSnaps($snapshots),
            'shots' => $shots,
            'kills' => $kills,
            'endUnits' => $endUnits,
            'winner' => $winner,
            'reason' => $reason,
        ];

        $s['units'] = $endUnits;
        $s['act'] = $s['act'] + 1;
        $s['phase'] = 'playback';
        $s['committed'] = ['w' => false, 'b' => false];
        $s['acked'] = ['w' => false, 'b' => false];
        $s['plans'] = ['w' => null, 'b' => null];
        $s['drafts'] = ['w' => null, 'b' => null];
        $s['timeline'] = $timeline;
        $s['history'][] = $timeline;
        $s['lastKnown'] = $lastKnown;
        $s['result'] = $winner || $reason ? ['winner' => $winner, 'reason' => $reason] : null;
        return $s;
    }

    private static function dedupeSnaps(array $snaps): array
    {
        $out = [];
        $lastT = -1;
        foreach ($snaps as $snap) {
            if ($snap['t'] === $lastT) {
                $out[count($out) - 1] = $snap;
            } else {
                $out[] = $snap;
                $lastT = $snap['t'];
            }
        }
        return $out;
    }

    private static function publicUnits(array $units): array
    {
        $out = [];
        foreach ($units as $u) {
            $out[] = [
                'id' => $u['id'],
                'team' => $u['team'],
                'role' => $u['role'],
                'weapon' => $u['weapon'],
                'q' => $u['q'],
                'r' => $u['r'],
                'facing' => $u['facing'],
                'alive' => $u['alive'],
            ];
        }
        return $out;
    }

    private static function normalizePath(mixed $path): array
    {
        if (!is_array($path)) {
            return [];
        }
        $out = [];
        foreach ($path as $step) {
            if (!is_array($step) || !isset($step['q'], $step['r'])) {
                continue;
            }
            $item = ['q' => (int)$step['q'], 'r' => (int)$step['r']];
            if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
                $item['facing'] = ((int)$step['facing'] % 6 + 6) % 6;
            }
            $out[] = $item;
        }
        return $out;
    }

    /**
     * @return array<string,string> shooter id => target id
     */
    private static function intendedShots(array $units, array $walls, array $cfg, int $now): array
    {
        $out = [];
        foreach ($units as $id => $u) {
            if (!$u['alive']) {
                continue;
            }
            $rof = (int)$cfg['weapon_'.$u['weapon'].'_rof_ms'];
            if ($now - (int)$u['lastShotAt'] < $rof) {
                continue;
            }
            $best = null;
            $bestD = PHP_INT_MAX;
            foreach ($units as $oid => $o) {
                if (!$o['alive'] || $o['team'] === $u['team']) {
                    continue;
                }
                $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
                if ($d === 0 || $d > (int)$cfg['shot_range']) {
                    continue;
                }
                if (!HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])) {
                    continue;
                }
                if (!HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls)) {
                    continue;
                }
                if ($d < $bestD) {
                    $bestD = $d;
                    $best = $oid;
                }
            }
            if ($best !== null) {
                $out[$id] = $best;
            }
        }
        ksort($out);
        return $out;
    }

    private static function accuracy(array $cfg, array $units, string $id, string $targetId, array $intended, array $focus, array $aimedAt, array $walls, bool $shooterStepped, bool $targetStepped): int
    {
        $s = $units[$id];
        $t = $units[$targetId];
        $acc = (int)$cfg['base_accuracy'];
        if (!$shooterStepped) {
            $acc += (int)$cfg['accuracy_bonus_shooter_stationary'];
        }
        if (HexGrid::onFacingLine($s['q'], $s['r'], (int)$s['facing'], $t['q'], $t['r'], (int)$cfg['shot_range'])) {
            $acc += (int)$cfg['accuracy_bonus_target_forward'];
        }
        $dist = HexGrid::distance($s['q'], $s['r'], $t['q'], $t['r']);
        if ($dist <= (int)$cfg['close_range_hexes']) {
            $acc += (int)$cfg['accuracy_bonus_target_close'];
            if ($s['weapon'] === 'shotgun') {
                $acc += (int)$cfg['accuracy_bonus_shotgun_close_extra'];
            }
        }
        if (($intended[$targetId] ?? null) !== $id) {
            $acc += (int)$cfg['accuracy_bonus_target_not_shooting_this'];
        }
        if (!empty($s['stationaryPrevAct'])) {
            $acc += (int)$cfg['accuracy_bonus_still_previous_act'];
        }
        $prev = $s['shotTargetPrevAct'] ?? null;
        if ($prev === null || $prev === $targetId) {
            $acc += (int)$cfg['accuracy_bonus_same_or_no_target_previous_act'];
        }
        if (($focus[$targetId] ?? 0) > 1) {
            $acc += (int)$cfg['accuracy_bonus_friendly_focus_fire'];
        }
        if (self::noCoverWall($s, $t, $walls)) {
            $acc += (int)$cfg['accuracy_bonus_target_no_cover_wall'];
        }
        if (!$targetStepped) {
            $acc += (int)$cfg['accuracy_bonus_target_stationary'];
        }
        if (!isset($aimedAt[$id])) {
            $acc += (int)$cfg['accuracy_bonus_nobody_shooting_at_shooter'];
        }
        return max(0, min((int)$cfg['accuracy_cap'], $acc));
    }

    private static function noCoverWall(array $shooter, array $target, array $walls): bool
    {
        $tq = $target['q'];
        $tr = $target['r'];
        $cover = false;
        foreach (HexGrid::neighbors($tq, $tr) as [$q, $r]) {
            if (!isset($walls[HexGrid::key($q, $r)])) {
                continue;
            }
            if (HexGrid::distance($shooter['q'], $shooter['r'], $q, $r) < HexGrid::distance($shooter['q'], $shooter['r'], $tq, $tr)) {
                $cover = true;
                break;
            }
        }
        return !$cover;
    }

    /** Aim points for a volley: the target, plus nearby hexes for shotgun pellets. */
    private static function pelletAims(array $shooter, array $target, int $pellets, int $spread): array
    {
        $aims = [[$target['q'], $target['r']]];
        if ($pellets <= 1) {
            return $aims;
        }
        $neighbors = HexGrid::neighbors($target['q'], $target['r']);
        $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $target['q'], $target['r']);
        $order = [];
        foreach ($neighbors as $i => $hex) {
            $away = HexGrid::distance($shooter['q'], $shooter['r'], $hex[0], $hex[1]);
            $order[] = [$away, $i, $hex];
        }
        usort($order, static fn($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
        foreach ($order as [, , $hex]) {
            if (count($aims) >= $pellets) {
                break;
            }
            if (HexGrid::distance($hex[0], $hex[1], $target['q'], $target['r']) <= max(1, $spread)) {
                $aims[] = $hex;
            }
        }
        while (count($aims) < $pellets) {
            $aims[] = HexGrid::neighbor($target['q'], $target['r'], ($dir + count($aims)) % 6);
        }
        return array_slice($aims, 0, $pellets);
    }

    private static function rayVictimToward(array $units, array $walls, array $shooter, string $intended, int $aq, int $ar, int $range, bool $friendlyFire): ?string
    {
        $occ = [];
        foreach ($units as $u) {
            if ($u['alive']) {
                $occ[HexGrid::key($u['q'], $u['r'])][] = $u['id'];
            }
        }
        $line = HexGrid::line($shooter['q'], $shooter['r'], $aq, $ar);
        $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $aq, $ar);
        while (count($line) < $range + 1) {
            $last = $line[count($line) - 1];
            $line[] = HexGrid::neighbor($last[0], $last[1], $dir);
        }
        foreach ($line as $i => [$q, $r]) {
            if ($i === 0) {
                continue;
            }
            $k = HexGrid::key($q, $r);
            if (isset($walls[$k])) {
                return null;
            }
            if (!empty($occ[$k])) {
                foreach ($occ[$k] as $id) {
                    if ($id === $shooter['id']) {
                        continue;
                    }
                    if (!$friendlyFire && $units[$id]['team'] === $shooter['team'] && $id !== $intended) {
                        continue;
                    }
                    return $id;
                }
            }
        }
        return null;
    }

    /**
     * @return array{w: list<string>, b: list<string>}
     */
    public static function visibility(array $units, array $walls, array $cfg, array $firedTicks, int $t): array
    {
        $seen = ['w' => [], 'b' => []];
        foreach ($units as $u) {
            if (!$u['alive']) {
                continue;
            }
            foreach ($units as $o) {
                if ($o['team'] === $u['team']) {
                    $seen[$u['team']][] = $o['id'];
                    continue;
                }
                if (!$o['alive']) {
                    continue;
                }
                $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
                $inVision = $d > 0 && $d <= (int)$cfg['vision_range']
                    && HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])
                    && HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls);
                $firing = !empty($cfg['see_enemies_when_firing']) && isset($firedTicks[$o['id']]) && $firedTicks[$o['id']] === $t;
                if ($inVision || $firing) {
                    $seen[$u['team']][] = $o['id'];
                }
            }
        }
        foreach (['w', 'b'] as $team) {
            $seen[$team] = array_values(array_unique($seen[$team]));
        }
        return $seen;
    }
}
