#!/usr/bin/env node
// verify-leapers-on-a-torus.mjs — recompute EVERY count shown on
// /strata/leapers-on-a-torus/ from first principles, with no dependencies.
//
//   node verify-leapers-on-a-torus.mjs           # queen anchor (n=1..13) + 4 leapers (n=1..12)
//                                                #   + scaling theorem + negative control + orbit coincidences
//   DEEP=1 node verify-leapers-on-a-torus.mjs    # also recompute the four n=13 leaper terms (minutes)
//
// A placement is a permutation pi of {0..n-1}: the piece in row i sits in column pi(i).
// Two pieces attack iff ((i-j) mod n, (pi(i)-pi(j)) mod n) is an attack offset:
//   QUEEN    : (dr-dc)%n==0 || (dr+dc)%n==0          (the two toroidal diagonals)
//   LEAPER a,b : one of (+-a,+-b),(+-b,+-a) mod n    (the eight leaps)
// Exits 0 on all-pass, 1 on any mismatch. Prints "<pass>/<total> PASS".

const mod = (x, n) => ((x % n) + n) % n;

// generic backtracker with pluggable attack predicate (reference path)
function countGeneric(n, attacks) {
  if (n <= 0) return 0;
  const col = new Int32Array(n), used = new Uint8Array(n);
  let total = 0;
  (function place(i) {
    if (i === n) { total++; return; }
    for (let c = 0; c < n; c++) {
      if (used[c]) continue;
      let ok = true;
      for (let j = 0; j < i; j++) {
        if (attacks(mod(i - j, n), mod(c - col[j], n), n)) { ok = false; break; }
      }
      if (!ok) continue;
      used[c] = 1; col[i] = c; place(i + 1); used[c] = 0;
    }
  })(0);
  return total;
}
const queenAttack = (dr, dc, n) => (dr - dc) % n === 0 || (dr + dc) % n === 0;
function leaperAttack(a, b) {
  return (dr, dc, n) => {
    const A = mod(a, n), B = mod(b, n), na = mod(-a, n), nb = mod(-b, n);
    const S = [[A, B], [A, nb], [na, B], [na, nb], [B, A], [B, na], [nb, A], [nb, na]];
    for (const [r, c] of S) if (dr === r && dc === c) return true;
    return false;
  };
}
// optimized leaper counter (independent second path): only rows j=i-d for relevant d can conflict
function countLeaper(n, a, b) {
  if (n <= 0) return 0;
  const A = mod(a, n), B = mod(b, n);
  const forb = Array.from({ length: n }, () => null);
  const add = (d, v) => { if (d === 0) return; (forb[d] || (forb[d] = new Set())).add(mod(v, n)); };
  for (let d = 1; d < n; d++) {
    if (d === A || d === mod(-a, n)) { add(d, b); add(d, -b); }
    if (d === B || d === mod(-b, n)) { add(d, a); add(d, -a); }
  }
  const rel = []; for (let d = 1; d < n; d++) if (forb[d]) rel.push(d);
  const col = new Int32Array(n), used = new Uint8Array(n);
  let total = 0;
  (function place(i) {
    if (i === n) { total++; return; }
    for (let c = 0; c < n; c++) {
      if (used[c]) continue;
      let ok = true;
      for (let k = 0; k < rel.length; k++) { const d = rel[k]; if (d > i) continue; if (forb[d].has(mod(c - col[i - d], n))) { ok = false; break; } }
      if (!ok) continue;
      used[c] = 1; col[i] = c; place(i + 1); used[c] = 0;
    }
  })(0);
  return total;
}

// ─── expected values (exactly what the page shows) ──────────────────────────
const EXPECT = {
  queen:   [1, 0, 0, 0, 10, 0, 28, 0, 0, 0, 88, 0, 4524],                                  // OEIS A051906 (nonzero odd-board terms 1,0,10,28,0,88,4524 are A007705)
  knight:  [1, 2, 0, 8, 10, 72, 210, 1408, 8334, 67400, 603372, 6576936, 80329522],
  camel:   [1, 0, 6, 0, 10, 120, 210, 720, 6156, 41020, 395252, 4855968, 63368344],
  zebra:   [1, 2, 6, 8, 10, 144, 210, 1408, 6156, 61900, 395252, 5353728, 64241086],
  giraffe: [1, 2, 0, 24, 10, 72, 210, 4864, 8334, 61900, 395252, 5586840, 63368344],
};
const AB = { knight: [1, 2], camel: [1, 3], zebra: [2, 3], giraffe: [1, 4] };
const DEEP = !!process.env.DEEP;
const NMAX_LEAP = DEEP ? 13 : 12;

let pass = 0, total = 0;
const fails = [];
function check(name, got, want) {
  total++;
  if (got === want) { pass++; }
  else { fails.push(`${name}: got ${got}, want ${want}`); }
}

// 1) QUEEN anchor reproduces A051906 exactly, n=1..13 (its nonzero terms are the compressed entry A007705)
for (let n = 1; n <= 13; n++) check(`queen n=${n} (A051906)`, countGeneric(n, queenAttack), EXPECT.queen[n - 1]);

// 2) each leaper, n=1..NMAX_LEAP — and the two code paths must agree (checked up to n=9)
for (const name of ["knight", "camel", "zebra", "giraffe"]) {
  const [a, b] = AB[name];
  for (let n = 1; n <= NMAX_LEAP; n++) {
    const fast = countLeaper(n, a, b);
    check(`${name} n=${n}`, fast, EXPECT[name][n - 1]);
    if (n <= 9) check(`${name} n=${n} two-path agreement`, countGeneric(n, leaperAttack(a, b)), fast);
  }
}

// 3) unit-scaling theorem — POSITIVE: unit lambda preserves the count
check("scaling knight(1,2)*3 = (3,6) at n=8", countLeaper(8, 3, 6), countLeaper(8, 1, 2)); // 1408
check("scaling (3,6) at n=8 equals 1408", countLeaper(8, 3, 6), 1408);
check("scaling knight(1,2)*3 = (3,6) at n=11", countLeaper(11, 3, 6), countLeaper(11, 1, 2)); // 603372
check("scaling zebra(2,3)*5 = (10,15)=(10,4) at n=11", countLeaper(11, mod(10, 11), mod(15, 11)), countLeaper(11, 2, 3));

// 4) unit-scaling — NEGATIVE CONTROL: lambda=2 is NOT a unit mod 8, count is allowed to (and does) differ
check("neg-control (2,4) at n=8 = 6528", countLeaper(8, 2, 4), 6528);
check("neg-control (2,4) != knight at n=8", countLeaper(8, 2, 4) !== countLeaper(8, 1, 2) ? 1 : 0, 1);

// 5) ratio-orbit coincidences the page claims
// n=7: all four fairy leapers share orbit {2,3,4,5} -> all 210
for (const name of ["knight", "camel", "zebra", "giraffe"]) check(`n=7 ${name} = 210 (forced)`, countLeaper(7, ...AB[name]), 210);
// n=7: the (1,1) leaper is a DIFFERENT orbit {1,6} -> NOT 210 (so "all leapers coincide at primes" is false)
check("n=7 (1,1) = 322 (different orbit)", countLeaper(7, 1, 1), 322);
// n=11: knight splits away; camel=zebra=giraffe stay locked
check("n=11 knight = 603372", countLeaper(11, 1, 2), 603372);
check("n=11 camel=zebra (forced same orbit)", countLeaper(11, 1, 3), countLeaper(11, 2, 3));
check("n=11 zebra=giraffe (forced same orbit)", countLeaper(11, 2, 3), countLeaper(11, 1, 4));
check("n=11 knight != camel (different orbit)", countLeaper(11, 1, 2) !== countLeaper(11, 1, 3) ? 1 : 0, 1);
// n=13 camel=giraffe (DEEP only — these are the slow terms)
if (DEEP) {
  check("n=13 camel=giraffe (forced)", countLeaper(13, 1, 3), countLeaper(13, 1, 4));
  check("n=13 camel*9 = (9,1) (unit scaling)", countLeaper(13, 9, 1), countLeaper(13, 1, 3));
  check("n=13 knight != zebra (different orbit)", countLeaper(13, 1, 2) !== countLeaper(13, 2, 3) ? 1 : 0, 1);
}

// ─── report ─────────────────────────────────────────────────────────────────
if (fails.length) { console.error("FAILURES:"); for (const f of fails) console.error("  " + f); }
console.log(`${pass}/${total} PASS${DEEP ? " (DEEP: n=13 included)" : " (n<=12; run DEEP=1 for n=13)"}`);
process.exit(pass === total ? 0 : 1);
