#!/usr/bin/env node
// NIM — independent verification of the XOR strategy.
//
// Two layers of checking, deliberately separate:
//   • THIS FILE (computational, finite): build the full game tree by exhaustive
//     retrograde analysis (minimax) for every small position and confirm, by an
//     argument that owes NOTHING to the XOR idea, that "the player to move loses"
//     coincides exactly with "nim-sum = 0". It also checks that Bouton's move
//     from nonzero nim-sum lands on a losing-for-opponent position. The page's
//     zero-sum fallback is outside this check.
//   • research/nim/lean/Nim.lean (universal, machine-checked): proves the two
//     invariants (progress + closure) the strategy rests on, for ALL positions
//     and ALL heaps — the part no finite test can reach. Run lean/verify.sh.
//
// This script is what the immersive page's claim "the bot is perfect" stands on
// at finite scale; the Lean file is what it stands on at infinite scale.

let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; } else { fail++; console.error("  ✗ " + msg); } };

// The winning-position branch used by the page's bot.
const nimSum = (heaps) => heaps.reduce((a, b) => a ^ b, 0);

// Bouton's move: if nim-sum s ≠ 0, find a heap whose high bit matches s's high
// bit and reduce it to (heap ^ s). Returns {index, to} or null if s === 0.
function boutonMove(heaps) {
  const s = nimSum(heaps);
  if (s === 0) return null;
  const hi = 31 - Math.clz32(s);           // position of s's top set bit
  for (let i = 0; i < heaps.length; i++) {
    if ((heaps[i] >> hi) & 1) {            // this heap carries the top bit
      const to = heaps[i] ^ s;             // strictly smaller; new nim-sum 0
      return { index: i, to };
    }
  }
  return null; // unreachable: s ≠ 0 ⇒ some heap has the top bit
}

// ── independent ground truth: retrograde analysis (no XOR anywhere) ───────────
// A position is sorted & zero-trimmed and keyed as a string. losing(pos) = the
// player to move has no winning move = every move leads to a winning position.
const key = (h) => h.filter((x) => x > 0).sort((a, b) => a - b).join(",");
const memo = new Map();
function* moves(heaps) {
  for (let i = 0; i < heaps.length; i++)
    for (let t = 0; t < heaps[i]; t++) {     // remove ≥1 from heap i (down to t)
      const next = heaps.slice(); next[i] = t; yield next;
    }
}
function losing(heaps) {                       // true ⇔ player to move LOSES
  const k = key(heaps);
  if (k === "") return true;                   // empty position: to-move loses
  if (memo.has(k)) return memo.get(k);
  memo.set(k, false);                          // guard (game is acyclic anyway)
  let isLosing = true;
  for (const nx of moves(heaps)) {
    if (losing(nx)) { isLosing = false; break } // a move to a losing pos ⇒ we win
  }
  memo.set(k, isLosing);
  return isLosing;
}

// ── 1. BOUTON'S THEOREM, exhaustively: losing ⇔ nim-sum 0 ─────────────────────
// All positions with up to 4 heaps, each 0..9 (≈10^4 positions, deduped).
{
  let mism = 0, checked = 0;
  const seen = new Set();
  for (let a = 0; a <= 9; a++)
   for (let b = a; b <= 9; b++)
    for (let c = b; c <= 9; c++)
     for (let d = c; d <= 9; d++) {
       const h = [a, b, c, d], k = key(h);
       if (seen.has(k)) continue; seen.add(k);
       checked++;
       const lose = losing(h), sum0 = nimSum(h) === 0;
       if (lose !== sum0) mism++;
     }
  ok(mism === 0,
     `Bouton: losing ⇔ nim-sum 0 disagreed on ${mism}/${checked} positions`);
  ok(checked > 700, `expected to sweep many positions, only ${checked}`);
}

// ── 2. The strategy is PERFECT from any nim-sum ≠ 0 position ───────────────────
// For every winning position (nim-sum ≠ 0), Bouton's move exists, is legal,
// makes nim-sum 0, and lands the OPPONENT on a losing position.
{
  let bad = 0, tested = 0;
  for (let a = 0; a <= 7; a++)
   for (let b = a; b <= 7; b++)
    for (let c = b; c <= 7; c++) {
      const h = [a, b, c];
      if (nimSum(h) === 0) continue;
      tested++;
      const mv = boutonMove(h);
      if (!mv) { bad++; continue; }
      const after = h.slice(); after[mv.index] = mv.to;
      const legal = mv.to < h[mv.index] && mv.to >= 0;
      if (!legal || nimSum(after) !== 0 || !losing(after)) bad++;
    }
  ok(bad === 0, `strategy imperfect on ${bad}/${tested} winning positions`);
}

// ── 3. CLOSURE, exhaustively: from nim-sum 0, EVERY move breaks it ─────────────
{
  let viol = 0, tested = 0;
  for (let a = 0; a <= 9; a++)
   for (let b = a; b <= 9; b++)
    for (let c = b; c <= 9; c++) {
      const h = [a, b, c];
      if (nimSum(h) !== 0) continue;
      tested++;
      for (const nx of moves(h)) if (nimSum(nx) === 0) viol++;   // must never happen
    }
  ok(viol === 0, `closure violated: ${viol} moves kept nim-sum 0 from a P-position`);
  ok(tested > 0, "no nim-sum-0 positions tested");
}

// ── 4. PROGRESS gives a real move that strictly lowers the stone count ─────────
{
  let bad = 0, tested = 0;
  for (let a = 0; a <= 12; a++)
   for (let b = 0; b <= 12; b++)
    for (let c = 0; c <= 12; c++) {
      const h = [a, b, c];
      if (nimSum(h) === 0) continue;
      tested++;
      const mv = boutonMove(h);
      const before = a + b + c, after = before - (h[mv.index] - mv.to);
      if (after >= before) bad++;
    }
  ok(bad === 0, `progress move did not decrease stones on ${bad}/${tested}`);
}

// ── 5. nim-sum is XOR: associative/commutative sanity + single-heap law ────────
{
  ok(nimSum([3, 5, 6]) === (3 ^ 5 ^ 6), "nim-sum is the XOR fold");
  ok(boutonMove([5])?.to === 0, "one heap: take it all (move to 0)");
  ok(nimSum([7, 7]) === 0, "mirrored heaps are a P-position (nim-sum 0)");
  // The famous 3-4-5 misère-irrelevant normal-play loss is NOT a P-position:
  ok(nimSum([3, 4, 5]) === 2 && !losing([3, 4, 5]), "3·4·5 is a win (nim-sum 2)");
  // The classic P-position 1·2·3:
  ok(nimSum([1, 2, 3]) === 0 && losing([1, 2, 3]), "1·2·3 is a P-position");
}

console.log(`\nNim verify: ${pass}/${pass + fail} checks passed.`);
process.exit(fail === 0 ? 0 : 1);
