#!/usr/bin/env node
// verify.mjs — the sliding-block puzzle's parity invariant, checked exactly.
//
// The claim of the stratum "The Half You Can Never Reach":
//
//   Sliding tiles can only ever reach EXACTLY HALF of a puzzle's arrangements.
//   Which half is fixed by one parity bit that no slide can flip:
//
//       J = sign(perm) · (−1)^(taxicab distance of the blank from its home cell)
//
//   A position is solvable (reachable from the goal by sliding) iff J = +1.
//
// The exhaustive counts below are exact integers; the auxiliary 4x4 sample
// uses a floating-point fraction. The three exhaustive checks are:
//   §1  Full breadth-first search of the 3×3 (8-puzzle): the reachable set has
//       EXACTLY 9!/2 = 181440 states, i.e. exactly half of all 362880.
//   §2  The graph and the arithmetic agree, state for state: over ALL 362880
//       arrangements, {J = +1} is exactly the BFS-reachable set. The invariant
//       is provably necessary AND sufficient on the 8-puzzle.
//   §3  J is preserved by every single slide (exhaustively, on the 8-puzzle),
//       and the reachable group with the blank home is exactly the even
//       permutations A_n — so you can never swap just two tiles. Sam Loyd's
//       famous 14–15 swap has J = −1: unsolvable with the blank home. The
//       textbook "inversions + blank row" rule agrees with J everywhere.
//
// Run:  node research/fifteen-puzzle/verify.mjs

import { execSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
const HERE = dirname(fileURLToPath(import.meta.url));

let PASS = 0, FAIL = 0;
const log = (ok, msg) => { (ok ? PASS++ : FAIL++); console.log(`  ${ok ? "✓" : "✗ FAIL"}  ${msg}`); };
const eq  = (a, b, msg) => log(a === b, `${msg}  (got ${a}${a === b ? "" : `, want ${b}`})`);

// ── core arithmetic, shared with the page ───────────────────────────────────

// sign of the permutation taking `cur` to `goal`, via cycle decomposition.
// returns +1 (even) or −1 (odd). blank is just another symbol here.
function permSign(cur, goal) {
  const n = cur.length;
  const goalIndex = new Map();
  for (let i = 0; i < n; i++) goalIndex.set(goal[i], i);
  // p[i] = where cur[i] belongs in goal
  const p = cur.map(v => goalIndex.get(v));
  const seen = new Array(n).fill(false);
  let transpositions = 0;
  for (let i = 0; i < n; i++) {
    if (seen[i]) continue;
    let len = 0, j = i;
    while (!seen[j]) { seen[j] = true; j = p[j]; len++; }
    transpositions += len - 1;            // an L-cycle = L−1 transpositions
  }
  return (transpositions % 2 === 0) ? 1 : -1;
}

// the invariant J. cols = grid width. blank symbol = 0.
function invariantJ(cur, goal, cols) {
  const n = cur.length;
  const blankCell = cur.indexOf(0);
  const blankHome = goal.indexOf(0);
  const taxicab = Math.abs((blankCell % cols) - (blankHome % cols))
                + Math.abs(Math.floor(blankCell / cols) - Math.floor(blankHome / cols));
  return permSign(cur, goal) * (taxicab % 2 === 0 ? 1 : -1);
}
const solvable = (cur, goal, cols) => invariantJ(cur, goal, cols) === 1;

// the textbook rule, independent of permSign, for cross-checking:
// count inversions among the tiles (blank ignored), add the blank's row
// counted FROM THE BOTTOM; solvable iff (for even width) the sum is even,
// (for odd width) the inversions alone are even.
function textbookSolvable(cur, goal, cols) {
  const rows = cur.length / cols;
  // map each tile to its goal rank so "order" means "goal order"
  const rank = new Map();
  let r = 0;
  for (const v of goal) if (v !== 0) rank.set(v, r++);
  const tiles = cur.filter(v => v !== 0).map(v => rank.get(v));
  let inv = 0;
  for (let i = 0; i < tiles.length; i++)
    for (let j = i + 1; j < tiles.length; j++)
      if (tiles[i] > tiles[j]) inv++;
  if (cols % 2 === 1) return inv % 2 === 0;
  const blankRowFromTop = Math.floor(cur.indexOf(0) / cols);
  const blankRowFromBottom = rows - blankRowFromTop;     // 1-indexed from bottom
  // even width (goal blank at lower-right): solvable iff (inv + blank row from
  // the bottom) is ODD — e.g. the solved board has inv 0, blank on row 1, sum 1.
  return (inv + blankRowFromBottom) % 2 === 1;
}

// legal slides: blank swaps with an orthogonal neighbour.
function neighbours(board, cols) {
  const rows = board.length / cols;
  const b = board.indexOf(0), br = Math.floor(b / cols), bc = b % cols;
  const out = [];
  const tryMove = (nr, nc) => {
    if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) return;
    const nb = nr * cols + nc;
    const copy = board.slice();
    copy[b] = copy[nb]; copy[nb] = 0;
    out.push(copy);
  };
  tryMove(br - 1, bc); tryMove(br + 1, bc); tryMove(br, bc - 1); tryMove(br, bc + 1);
  return out;
}

// ── encode a 3×3 board (perm of 0..8) to its Lehmer rank 0..362879 ──────────
const FACT = [1, 1, 2, 6, 24, 120, 720, 5040, 40320];
function rank9(board) {
  let r = 0;
  for (let i = 0; i < 9; i++) {
    let smaller = 0;
    for (let j = i + 1; j < 9; j++) if (board[j] < board[i]) smaller++;
    r += smaller * FACT[8 - i];
  }
  return r;
}
function unrank9(r) {
  const avail = [0, 1, 2, 3, 4, 5, 6, 7, 8], out = [];
  for (let i = 0; i < 9; i++) {
    const f = FACT[8 - i], idx = Math.floor(r / f);
    r %= f;
    out.push(avail[idx]); avail.splice(idx, 1);
  }
  return out;
}

console.log("\nThe Half You Can Never Reach — exact verification\n");

// ── §1  full BFS of the 8-puzzle: exactly half is reachable ─────────────────
console.log("§1 · Breadth-first search of the 3×3 — count the reachable half");

const GOAL3 = [1, 2, 3, 4, 5, 6, 7, 8, 0];
const COLS3 = 3;
const visited = new Uint8Array(362880);
const startRank = rank9(GOAL3);
visited[startRank] = 1;
let frontier = [GOAL3];
let reachable = 1;
let maxDepth = 0, depth = 0;
const depthCount = [];                          // states at each BFS depth (God's-number profile)
depthCount[0] = 1;
while (frontier.length) {
  const next = [];
  for (const board of frontier) {
    for (const nb of neighbours(board, COLS3)) {
      const rk = rank9(nb);
      if (!visited[rk]) { visited[rk] = 1; reachable++; next.push(nb); }
    }
  }
  if (next.length) { depth++; depthCount[depth] = next.length; maxDepth = depth; }
  frontier = next;
}
eq(reachable, 181440, "reachable states from the solved 3×3");
eq(362880 - reachable, 181440, "UNreachable states (the other exact half)");
eq(362880 / reachable, 2, "reachable is exactly one half of 9! arrangements");
eq(maxDepth, 31, "hardest 8-puzzle is 31 slides away (its diameter / 'God's number')");
const deepest = depthCount[maxDepth];
eq(deepest, 2, "exactly 2 positions sit at the maximum distance of 31");
log(depthCount.reduce((a, b) => a + b, 0) === 181440, "BFS depth profile sums to the reachable count");

// ── §2  the arithmetic agrees with the graph, state for state ───────────────
console.log("\n§2 · The invariant J = +1 is EXACTLY the reachable set (necessary & sufficient)");

let jPlus = 0, mismatches = 0;
for (let r = 0; r < 362880; r++) {
  const board = unrank9(r);
  const j = solvable(board, GOAL3, COLS3);   // J == +1 ?
  if (j) jPlus++;
  if (j !== (visited[r] === 1)) mismatches++; // does the parity bit match graph-reachability?
}
eq(jPlus, 181440, "arrangements with J = +1");
eq(mismatches, 0, "states where the parity bit DISAGREES with actual reachability");
log(true, "→ the single parity bit J decides solvability perfectly on the 3×3");

// cross-check the textbook inversions rule against J on all 362880
let tbMismatch = 0;
for (let r = 0; r < 362880; r++) {
  const board = unrank9(r);
  if (textbookSolvable(board, GOAL3, COLS3) !== solvable(board, GOAL3, COLS3)) tbMismatch++;
}
eq(tbMismatch, 0, "textbook 'inversions' rule agrees with J on all 362880 (3×3)");

// ── §3  every slide preserves J; the home group is A_n; Loyd's swap fails ────
console.log("\n§3 · J is conserved by every slide, and you can never swap just two tiles");

// every legal slide from every arrangement keeps J unchanged
let slideBreaksJ = 0, slidesChecked = 0;
for (let r = 0; r < 362880; r++) {
  const board = unrank9(r);
  const j0 = invariantJ(board, GOAL3, COLS3);
  for (const nb of neighbours(board, COLS3)) {
    slidesChecked++;
    if (invariantJ(nb, GOAL3, COLS3) !== j0) slideBreaksJ++;
  }
}
eq(slideBreaksJ, 0, `slides (of ${slidesChecked.toLocaleString('en-US')} checked) that changed J`);

// among reachable states with the blank HOME, the tile permutation is always EVEN,
// the count is 8!/2, and NONE differs from the goal in exactly two tiles.
let homeReach = 0, homeOdd = 0, exactlyTwoSwapped = 0;
for (let r = 0; r < 362880; r++) {
  if (!visited[r]) continue;
  const board = unrank9(r);
  if (board[8] !== 0) continue;               // blank must be home (cell 8)
  homeReach++;
  if (permSign(board, GOAL3) !== 1) homeOdd++;
  let diff = 0;
  for (let i = 0; i < 9; i++) if (board[i] !== GOAL3[i]) diff++;
  if (diff === 2) exactlyTwoSwapped++;
}
eq(homeReach, 20160, "reachable states with the blank home  (= 8!/2, the group A₈)");
eq(homeOdd, 0, "reachable home states whose tile permutation is ODD");
eq(exactlyTwoSwapped, 0, "reachable home states that swap exactly two tiles (Loyd's dream)");
log(20160 * 2 === 40320, "A₈ is exactly half of S₈  (20160 of 8! = 40320)");

// the smallest real move with the blank home is a 3-cycle of tiles
const threeCycle = [3, 1, 2, 4, 5, 6, 7, 8, 0];   // tiles 1,2,3 rotated
eq(permSign(threeCycle, GOAL3), 1, "a 3-cycle of tiles is EVEN — so it is reachable");
log(solvable(threeCycle, GOAL3, COLS3), "the 3-cycle is solvable (the true minimal scramble)");

// ── Sam Loyd's 14–15 puzzle (4×4) ───────────────────────────────────────────
console.log("\n§4 · Loyd's 14–15 swap on the 4×4: every tile and the gap required home");

const GOAL4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0];
const COLS4 = 4;
const LOYD  = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 14, 0]; // 14 & 15 swapped
eq(invariantJ(LOYD, GOAL4, COLS4), -1, "J for Loyd's 14–15 swap");
log(!solvable(LOYD, GOAL4, COLS4), "Loyd's 14–15 swap is UNSOLVABLE — no slide sequence undoes it");
log(textbookSolvable(GOAL4, GOAL4, COLS4) && !textbookSolvable(LOYD, GOAL4, COLS4),
    "textbook rule agrees: goal solvable, Loyd's swap not");

// a random solvable scramble: apply random slides — must stay solvable (J=+1)
let scrambleBad = 0;
let rng = 12345;
const rand = (m) => { rng = (rng * 1103515245 + 12345) & 0x7fffffff; return rng % m; };
for (let trial = 0; trial < 5000; trial++) {
  let b = GOAL4.slice();
  for (let s = 0; s < 200; s++) { const nbs = neighbours(b, COLS4); b = nbs[rand(nbs.length)]; }
  if (!solvable(b, GOAL4, COLS4)) scrambleBad++;
}
eq(scrambleBad, 0, "random slide-scrambles (5000×200 moves) that ended unsolvable");

// J and textbook rule agree on 200000 random 4×4 arrangements
let bigMismatch = 0;
for (let trial = 0; trial < 200000; trial++) {
  const b = GOAL4.slice();
  for (let i = b.length - 1; i > 0; i--) { const j = rand(i + 1); [b[i], b[j]] = [b[j], b[i]]; }
  if (textbookSolvable(b, GOAL4, COLS4) !== solvable(b, GOAL4, COLS4)) bigMismatch++;
}
eq(bigMismatch, 0, "J vs textbook rule disagreements on 200000 random 4×4 arrangements");

// half of all 4×4 arrangements are solvable (statistical, exact would be 16!/2)
let solv = 0, N = 400000;
for (let trial = 0; trial < N; trial++) {
  const b = GOAL4.slice();
  for (let i = b.length - 1; i > 0; i--) { const j = rand(i + 1); [b[i], b[j]] = [b[j], b[i]]; }
  if (solvable(b, GOAL4, COLS4)) solv++;
}
const frac = solv / N;
log(Math.abs(frac - 0.5) < 0.01, `≈ half of random 4×4 arrangements are solvable  (${(frac * 100).toFixed(2)}%)`);

// ── §L  the kernel proof (Lean): the invariant for boards of EVERY size ─────
// The BFS above DECIDES the 3×3 completely, but only samples the 4×4 (10^13 boards)
// and can never reach an arbitrary width. lean/FifteenPuzzle.lean hands Lean's kernel
// the universal statement (zero imports): every legal slide preserves the parity bit,
// so the two-tile swap is unreachable on a board of ANY size. Here we (a) re-implement
// the Lean bit in JS and confirm its solvability partition is EXACTLY the page's
// operated invariant — so the predicate the kernel reasons about is the one the page
// runs — and (b) when `lean` is on PATH, typecheck the file live and assert its axiom
// footprint; otherwise we check the source statically.
console.log("\n§L · The kernel proof (Lean) — the invariant, for every board size");

// (a) The Lean bit, in JS. Board in RANK space: rank(v) = its index in the goal.
// leanJbit = (inversions of the rank sequence) + (blank row + blank col), mod 2.
// This mirrors invCount + cellSum in FifteenPuzzle.lean exactly.
function leanJbit(board, goal, cols) {
  const rankOf = new Map();
  for (let i = 0; i < goal.length; i++) rankOf.set(goal[i], i);
  const rank = board.map((v) => rankOf.get(v));
  let inv = 0;
  for (let i = 0; i < rank.length; i++)
    for (let j = i + 1; j < rank.length; j++)
      if (rank[i] > rank[j]) inv++;
  const b = board.indexOf(0);
  const cellSum = Math.floor(b / cols) + (b % cols);
  return (inv + cellSum) % 2;
}

// The Lean bit's solvability class (leanJbit == leanJbit(goal)) must equal the page's
// operated verdict `solvable` (sign × taxicab), state for state, over ALL 362880 of
// the 3×3. This is the "provably about the operated scheme" cross-check.
{
  const gJ3 = leanJbit(GOAL3, GOAL3, COLS3);
  let disagree = 0;
  for (let r = 0; r < 362880; r++) {
    const board = unrank9(r);
    const leanSolvable = leanJbit(board, GOAL3, COLS3) === gJ3;
    if (leanSolvable !== solvable(board, GOAL3, COLS3)) disagree++;
  }
  eq(disagree, 0, "MODEL=OPERATED: Lean bit's class matches invariant J on all 362880 boards (3×3)");
}
// and on a large 4×4 sweep (valid arrangements + slide-scrambles), same partition.
{
  const gJ4 = leanJbit(GOAL4, GOAL4, COLS4);
  let disagree = 0, tested = 0, rng4 = 99991;
  const rnd = (m) => { rng4 = (rng4 * 1103515245 + 12345) & 0x7fffffff; return rng4 % m; };
  for (let trial = 0; trial < 200000; trial++) {
    const b = GOAL4.slice();
    for (let i = b.length - 1; i > 0; i--) { const j = rnd(i + 1); [b[i], b[j]] = [b[j], b[i]]; }
    tested++;
    if ((leanJbit(b, GOAL4, COLS4) === gJ4) !== solvable(b, GOAL4, COLS4)) disagree++;
  }
  // Loyd's board specifically: Lean bit must call it UNsolvable, matching J = −1.
  const lJ = leanJbit(LOYD, GOAL4, COLS4) === gJ4;
  eq(disagree, 0, `MODEL=OPERATED: Lean bit matches J on ${tested.toLocaleString('en-US')} random 4×4 arrangements`);
  log(lJ === false, "MODEL=OPERATED: Lean bit calls Loyd's 14–15 swap unsolvable (matches J = −1)");
}

// (b) The Lean file: present, states the theorems, no sorry / native_decide, and —
// when `lean` is on PATH — typechecks with the expected axiom footprint.
const leanFile = join(HERE, 'lean', 'FifteenPuzzle.lean');
log(existsSync(leanFile), 'Lean proof file present (lean/FifteenPuzzle.lean)');
if (existsSync(leanFile)) {
  const src = readFileSync(leanFile, 'utf8');
  const code = src.replace(/\/-[\s\S]*?-\//g, '').replace(/--.*$/gm, '');
  const wanted = ['swap_flips', 'slide_preserves_J', 'reachable_preserves_J',
                  'two_swap_unreachable', 'loyd_unreachable'];
  for (const t of wanted) log(new RegExp(`theorem ${t}\\b`).test(src), `Lean states theorem ${t}`);
  log(!/\bsorry\b/.test(code) && !/native_decide/.test(code), 'Lean source has no sorry / native_decide');

  const candidates = ['lean', join(homedir(), '.elan', 'bin', 'lean'), join(homedir(), '.nix-profile', 'bin', 'lean')];
  let leanBin = null;
  for (const c of candidates) {
    try { execSync(`${c} --version`, { stdio: 'ignore' }); leanBin = c; break; } catch { /* keep trying */ }
  }
  if (leanBin) {
    let out = '', typechecked = true;
    try {
      out = execSync(`${leanBin} ${JSON.stringify(leanFile)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
    } catch (e) { out = (e.stdout || '') + (e.stderr || ''); typechecked = false; }
    log(typechecked, 'Lean typechecks with no errors' + (typechecked ? '' : ' — ' + out.split('\n').slice(0, 4).join(' | ')));
    const reports = [...out.matchAll(/^'([^'\n]+)' (?:depends on axioms:\s*\[([^\]]*)\]|does not depend on any axioms)[ \t]*$/gm)];
    const reported = new Set(reports.map((m) => m[1]));
    const complete = wanted.every((t) => reported.has(`FP.${t}`));
    log(complete, `Lean emitted axiom footprints for all five named theorems (${reports.length} reports)`);
    const allowed = new Set(['propext', 'Quot.sound']);
    const badAxiom = reports.find((m) => (m[2] || '').split(',').map((a) => a.trim()).filter(Boolean).some((a) => !allowed.has(a)));
    log(complete && !badAxiom, 'every kernel theorem is [propext, Quot.sound] or tighter (no other axioms allowed)' + (badAxiom ? ' : ' + badAxiom[0] : ''));
    for (const m of reports) console.log('   ', m[0]);
  } else {
    console.log('  ..  lean not on PATH — model-fidelity + static checks only');
    console.log('      (run research/fifteen-puzzle/lean/install-lean-nix.sh to typecheck the kernel proof)');
  }
}

// ── tally ───────────────────────────────────────────────────────────────────
console.log(`\n${FAIL === 0 ? "✓ all" : "✗"} ${PASS} checks passed${FAIL ? `, ${FAIL} FAILED` : ""}.\n`);
process.exit(FAIL === 0 ? 0 : 1);
