<?php
require_once dirname(__DIR__) . '/includes/chess.php';

$games = json_decode(file_get_contents('real_games.json'), true);
$fail = 0; $total = 0;

foreach ($games as $name => $seq) {
    echo "-- $name (" . (count($seq) - 1) . " plies)\n";
    for ($i = 1; $i < count($seq); $i++) {
        $prev = $seq[$i-1]['fen'];
        $next = $seq[$i]['fen'];
        $mover = $seq[$i]['mover'];
        $san = $seq[$i]['san'];
        $total++;

        [$ok, $why] = chessValidateTransition($prev, $next, $mover);
        if (!$ok) { $fail++; echo "   REJECTED LEGAL MOVE ply $i ($mover $san): $why\n      prev=$prev\n      next=$next\n"; }

        // The wrong player must never be allowed to push this position.
        $other = $mover === 'w' ? 'b' : 'w';
        [$ok2,] = chessValidateTransition($prev, $next, $other);
        if ($ok2) { $fail++; echo "   ACCEPTED MOVE FROM WRONG PLAYER at ply $i ($san)\n"; }

        // Replaying an earlier position must be refused.
        if ($i >= 3) {
            [$ok3,] = chessValidateTransition($prev, $seq[$i-2]['fen'], $mover);
            if ($ok3) { $fail++; echo "   ACCEPTED A REWIND at ply $i\n"; }
        }
    }
}

// Checkmate detection is derived purely from the final position.
$operaFinal = $games['opera'][count($games['opera'])-1]['fen'];
$d = chessDeriveResult('checkmate', $operaFinal, null);
echo "opera final derived: {$d['result']} (expect white_wins — Black is mated)\n";
if ($d['result'] !== 'white_wins') { $fail++; echo "   WRONG WINNER\n"; }

$promoFinal = $games['promo'][count($games['promo'])-1]['fen'];
$d = chessDeriveResult('checkmate', $promoFinal, null);
echo "promo final derived: {$d['result']} (expect white_wins)\n";
if ($d['result'] !== 'white_wins') { $fail++; echo "   WRONG WINNER\n"; }

echo "\n$total transitions checked, $fail failures\n";
exit($fail ? 1 : 0);
