// Replay real games with the SAME chess library the client ships, and dump the
// FEN sequence so the PHP validator can be checked against genuine play.
import fs from 'node:fs';
const src = fs.readFileSync(new URL('../public/js/lib/chess.min.js', import.meta.url),'utf8');
const mod = {exports:{}};
new Function('module','exports','globalThis', src)(mod, mod.exports, globalThis);
const Chess = globalThis.Chess || mod.exports.Chess || mod.exports;

const games = {
  // Morphy — Opera Game, 1858 (ends in mate)
  opera: "e4 e5 Nf3 d6 d4 Bg4 dxe5 Bxf3 Qxf3 dxe5 Bc4 Nf6 Qb3 Qe7 Nc3 c6 Bg5 b5 Nxb5 cxb5 Bxb5+ Nbd7 O-O-O Rd8 Rxd7 Rxd7 Rd1 Qe6 Bxd7+ Nxd7 Qb8+ Nxb8 Rd8#",
  // Kasparov–Topalov, Wijk aan Zee 1999 (long, many captures)
  topalov: "e4 d6 d4 Nf6 Nc3 g6 Be3 Bg7 Qd2 c6 f3 b5 Nge2 Nbd7 Bh6 Bxh6 Qxh6 Bb7 a3 e5 O-O-O Qe7 Kb1 a6 Nc1 O-O-O Nb3 exd4 Rxd4 c5 Rd1 Nb6 g3 Kb8 Na5 Ba8 Bh3 d5 Qf4+ Ka7 Rhe1 d4 Nd5 Nbxd5 exd5 Qd6 Rxd4 cxd4 Re7+ Kb6 Qxd4+ Kxa5 b4+ Ka4 Qc3 Qxd5 Ra7 Bb7 Rxb7 Qc4 Qxf6 Kxa3 Qxa6+ Kxb4 c3+ Kxc3 Qa1+ Kd2 Qb2+ Kd1 Bf1 Rd2 Rd7 Rxd7 Bxc4 bxc4 Qxh8 Rd3 Qa8 c3 Qa4+ Ke1 f4 f5 Kc1 Rd2 Qa7",
  // A game with promotion
  promo: "e4 e5 Nf3 Nc6 Bc4 Bc5 b4 Bxb4 c3 Ba5 d4 exd4 O-O d3 Qb3 Qf6 e5 Qg6 Re1 Nge7 Ba3 b5 Qxb5 Rb8 Qa4 Bb6 Nbd2 Bb7 Ne4 Qf5 Bxd3 Qh5 Nf6+ gxf6 exf6 Rg8 Rad1 Qxf3 Rxe7+ Nxe7 Qxd7+ Kxd7 Bf5+ Ke8 Bd7+ Kf8 Bxe7#",
};

const out = {};
for (const [name, pgnMoves] of Object.entries(games)) {
  const c = new Chess();
  const seq = [{fen: c.fen(), mover: null, san: null}];
  for (const san of pgnMoves.split(/\s+/).filter(Boolean)) {
    const before = c.turn();
    const m = c.move(san);
    if (!m) { console.error(`${name}: failed at ${san}`); break; }
    seq.push({fen: c.fen(), mover: before, san});
  }
  out[name] = seq;
  console.error(`${name}: ${seq.length-1} plies, final=${c.fen()}, gameOver=${c.isGameOver?.() ?? c.game_over?.()}`);
}
fs.writeFileSync('real_games.json', JSON.stringify(out));
