// verify.mjs — every factual claim on the Dots-and-Boxes stratum, recomputed.
//
// Everything here is an EXACT, assumption-free game solve: full minimax over the
// real edge graph with the true rules (complete a box -> score it and move again).
// No heuristic stands in for a proof anywhere in this file.
//
//   node research/dots-and-boxes/verify.mjs          # fast checks (~1s)
//   node research/dots-and-boxes/verify.mjs --full   # also recompute 3x3 (~22s)
//
// The "value" of a position is the net boxes (player-to-move minus opponent) over
// the boxes that remain, under perfect play.  value(empty) > 0  <=>  first player
// wins by that margin.

import { makeBoard, solve } from "./solve.mjs";

let pass = 0, fail = 0;
const eq = (got, want, msg) => {
  const ok = got === want;
  console.log(`${ok ? "  ok " : " FAIL"}  ${msg}  ->  ${got}${ok ? "" : `  (want ${want})`}`);
  ok ? pass++ : fail++;
};

// Solve from a prefilled position (used for the engineered endgames below).
function solveFrom(board, prefill) {
  const memo = new Map();
  const completedBy = (nm, e) => {
    let k = 0;
    for (const b of board.edgeBoxes[e]) {
      const [a, b2, c, d] = board.boxEdges[b];
      if ((nm & (1 << a)) && (nm & (1 << b2)) && (nm & (1 << c)) && (nm & (1 << d))) k++;
    }
    return k;
  };
  function val(mask) {
    if (mask === board.FULL) return 0;
    const h = memo.get(mask);
    if (h !== undefined) return h;
    let best = -Infinity;
    for (let e = 0; e < board.E; e++) {
      const bit = 1 << e;
      if (mask & bit) continue;
      const nm = mask | bit;
      const k = completedBy(nm, e);
      const sub = k > 0 ? k + val(nm) : -val(nm);
      if (sub > best) best = sub;
    }
    memo.set(mask, best);
    return best;
  }
  return val(prefill);
}

// "Naive" variant: a player who has a capturing move MUST take it and keeps
// eating the whole chain (never declines / never double-crosses).  Used to show
// what the double-cross is worth.
function solveNaive(board, prefill) {
  const memo = new Map();
  const completedBy = (nm, e) => {
    let k = 0;
    for (const b of board.edgeBoxes[e]) {
      const [a, b2, c, d] = board.boxEdges[b];
      if ((nm & (1 << a)) && (nm & (1 << b2)) && (nm & (1 << c)) && (nm & (1 << d))) k++;
    }
    return k;
  };
  function val(mask) {
    if (mask === board.FULL) return 0;
    const h = memo.get(mask);
    if (h !== undefined) return h;
    // forced capture: take the first available box (and keep moving)
    for (let e = 0; e < board.E; e++) {
      const bit = 1 << e;
      if (mask & bit) continue;
      const k = completedBy(mask | bit, e);
      if (k > 0) { const v = k + val(mask | bit); memo.set(mask, v); return v; }
    }
    let best = -Infinity;
    for (let e = 0; e < board.E; e++) {
      const bit = 1 << e;
      if (mask & bit) continue;
      best = Math.max(best, -val(mask | bit));
    }
    memo.set(mask, best);
    return best;
  }
  return val(prefill);
}

// k parallel open corridors of length N (a k x N board with every horizontal
// edge drawn): k independent open chains, sharing no open edge.
function corridors(k, N) {
  const b = makeBoard(k, N);
  let mask = 0;
  for (let r = 0; r <= k; r++) for (let c = 0; c < N; c++) mask |= 1 << b.H(r, c);
  return { b, mask };
}

console.log("\n— Exact winners, perfect play (full solve from the empty board) —");
// value(empty), first-player perspective.  These are theorems, not estimates.
eq(solve(makeBoard(1, 1)).value, -1, "1x1 boxes: second player wins by 1");
eq(solve(makeBoard(1, 2)).value, 0, "1x2 boxes: drawn");
eq(solve(makeBoard(1, 3)).value, -1, "1x3 boxes: second player wins by 1");
eq(solve(makeBoard(1, 4)).value, 0, "1x4 boxes: drawn");
eq(solve(makeBoard(1, 5)).value, -1, "1x5 boxes: second player wins by 1");
eq(solve(makeBoard(2, 2)).value, 2, "2x2 boxes: FIRST player wins by 2");
eq(solve(makeBoard(2, 3)).value, -2, "2x3 boxes: second player wins by 2");
eq(solve(makeBoard(2, 4)).value, 2, "2x4 boxes: first player wins by 2");

console.log("\n— A single open chain: the player forced to open it loses every box —");
for (let N = 1; N <= 7; N++) {
  const { b, mask } = corridors(1, N);
  eq(solveFrom(b, mask), -N, `open chain of ${N}: opener loses all ${N}`);
}

console.log("\n— k equal long chains: the controller wins by k·L − 4(k−1) —");
console.log("  (the all-but-two double-cross: concede 2 boxes per chain to keep the move)");
for (const [k, L] of [[2, 3], [2, 4], [2, 5], [3, 3], [3, 4]]) {
  const { b, mask } = corridors(k, L);
  const margin = k * L - 4 * (k - 1); // controller's winning margin
  eq(solveFrom(b, mask), -margin, `${k} chains of ${L}: controller wins by ${margin}`);
}

console.log("\n— The decline option is what breaks the tie —");
// Two equal long chains: a draw if both players naively eat everything offered;
// a controller win once the double-cross (declining the last two) is available.
for (const L of [3, 4, 5]) {
  const { b, mask } = corridors(2, L);
  eq(solveNaive(b, mask), 0, `two chains of ${L}, naive take-all play: drawn`);
  eq(solveFrom(b, mask), -(2 * L - 4), `two chains of ${L}, with the double-cross: controller wins by ${2 * L - 4}`);
}

console.log("\n— Loops cost twice as much to keep control (concede 4, not 2) —");
// loop of 4: 2x2 board, outer perimeter drawn, the central cross left open.
function loop4() {
  const b = makeBoard(2, 2);
  let mask = 0;
  for (const e of [b.H(0,0),b.H(0,1),b.H(2,0),b.H(2,1),b.V(0,0),b.V(0,2),b.V(1,0),b.V(1,2)]) mask |= 1 << e;
  return { b, mask };
}
{
  const { b, mask } = loop4();
  eq(solveFrom(b, mask), -4, "single loop of 4: opener loses all 4");
}
// two loops of 4 (2x4 board, two 2x2 blocks each with its cross open):
function twoLoops4() {
  const b = makeBoard(2, 4);
  let mask = 0;
  const drawn = [
    b.H(0,0),b.H(0,1),b.H(2,0),b.H(2,1),b.V(0,0),b.V(1,0),b.V(0,2),b.V(1,2), // left block perimeter
    b.H(0,2),b.H(0,3),b.H(2,2),b.H(2,3),b.V(0,4),b.V(1,4),                    // right block perimeter (mid wall shared)
  ];
  for (const e of drawn) mask |= 1 << e;
  return { b, mask };
}
{
  const { b, mask } = twoLoops4();
  // two chains of 4 -> controller +4; two loops of 4 -> drawn, because each loop
  // double-cross concedes 4. The contrast IS the theorem.
  eq(solveFrom(b, mask), 0, "two loops of 4: drawn (the loop double-cross concedes 4)");
  eq(solveFrom(corridors(2,4).b, corridors(2,4).mask), -4, "  vs two CHAINS of 4: controller wins by 4");
}

if (process.argv.includes("--full")) {
  console.log("\n— The full 3x3-box board (4x4 dots), perfect play (~22s, 16.7M states) —");
  const t = Date.now();
  const v = solve(makeBoard(3, 3)).value;
  eq(v, -3, `3x3 boxes: second player wins by 3  [${((Date.now() - t) / 1000).toFixed(1)}s]`);
}

console.log(`\n${fail === 0 ? "ALL PASS" : "FAILED"} — ${pass}/${pass + fail} checks` +
  (process.argv.includes("--full") ? "" : "  (run with --full to also recompute 3x3)"));
process.exit(fail === 0 ? 0 : 1);
