// verify.mjs — an INDEPENDENT recomputation of the original sequences collated by the
// "Made, Not Retold" portal, matched against the committed b-files. Written fresh for
// this page (no shared code with the member engines), so a match is a genuine second
// witness at small n — exactly the cross-check the 2026-07-20 coverage audit found
// missing at the large terms. It deliberately covers only the range it can recompute
// from scratch cheaply; the large terms rest on the member verifiers, and the page says
// so. Every assertion here is small-n and exact (integer / BigInt), never an estimate.
//
//   node research/made-not-retold/verify.mjs
//
// Exit 0 iff every recomputation matches the committed data.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const oeis = (p) => join(ROOT, 'oversight', 'oeis', p);

// read a b-file "n value" (skip # comments) -> Map(n -> value string)
function readB(path) {
  const m = new Map();
  for (const line of readFileSync(path, 'utf8').split('\n')) {
    const t = line.trim();
    if (!t || t.startsWith('#')) continue;
    const sp = t.split(/\s+/);
    if (sp.length >= 2) m.set(Number(sp[0]), sp[1]);
  }
  return m;
}

let PASS = 0, FAIL = 0;
const results = [];
function check(name, got, want) {
  const ok = String(got) === String(want);
  ok ? PASS++ : FAIL++;
  if (!ok) results.push(`  FAIL ${name}: got ${got}, want ${want}`);
  return ok;
}
function section(title) { results.push(`\n== ${title} ==`); }

// ───────────────────────────────────────────────────────────────────────────
// 1. Topswops — total flips over all n! decks (the one I over-reported earlier)
// ───────────────────────────────────────────────────────────────────────────
function topswopsTotal(n) {
  const used = new Array(n + 1).fill(false), cur = [];
  let sum = 0;
  const steps = (deck) => {
    const d = deck.slice(); let s = 0;
    while (d[0] !== 1) { const k = d[0]; let i = 0, j = k - 1; while (i < j) { const t = d[i]; d[i] = d[j]; d[j] = t; i++; j--; } s++; }
    return s;
  };
  (function rec() {
    if (cur.length === n) { sum += steps(cur); return; }
    for (let v = 1; v <= n; v++) if (!used[v]) { used[v] = true; cur.push(v); rec(); cur.pop(); used[v] = false; }
  })();
  return sum;
}
section('Topswops total-flips (independent flip simulation over all n! decks)');
{
  const b = readB(oeis('topswops-total-flips/b-file.txt'));
  for (let n = 1; n <= 8; n++) check(`topswops a(${n})`, topswopsTotal(n), b.get(n));
}

// ───────────────────────────────────────────────────────────────────────────
// 2. Lucas–Lehmer map  x -> x^2 - 2 (mod n): cycles / periodic / fixed / longest
// ───────────────────────────────────────────────────────────────────────────
function llStats(n) {
  const f = new Array(n);
  for (let x = 0; x < n; x++) f[x] = (((x * x - 2) % n) + n) % n;
  const onCycle = new Array(n).fill(false), color = new Array(n).fill(0);
  for (let s = 0; s < n; s++) {
    if (color[s]) continue;
    const path = []; let x = s;
    while (color[x] === 0) { color[x] = 1; path.push(x); x = f[x]; }
    if (color[x] === 1) { let y = x; do { onCycle[y] = true; y = f[y]; } while (y !== x); }
    for (const p of path) color[p] = 2;
  }
  let F = 0; for (let x = 0; x < n; x++) if (f[x] === x) F++;
  const seen = new Array(n).fill(false); let C = 0, L = 0;
  for (let x = 0; x < n; x++) if (onCycle[x] && !seen[x]) { C++; let len = 0, y = x; do { seen[y] = true; len++; y = f[y]; } while (y !== x); if (len > L) L = len; }
  return { C, P: onCycle.filter(Boolean).length, F, L };
}
section('Lucas-Lehmer map x^2-2 (mod n): graph statistics C/P/F/L');
{
  const bC = readB(oeis('lucas-lehmer-map/b-file-C.txt')), bP = readB(oeis('lucas-lehmer-map/b-file-P.txt'));
  const bF = readB(oeis('lucas-lehmer-map/b-file-F.txt')), bL = readB(oeis('lucas-lehmer-map/b-file-L.txt'));
  for (let n = 1; n <= 30; n++) { const s = llStats(n); check(`LL C(${n})`, s.C, bC.get(n)); check(`LL P(${n})`, s.P, bP.get(n)); check(`LL F(${n})`, s.F, bF.get(n)); check(`LL L(${n})`, s.L, bL.get(n)); }
}

// ───────────────────────────────────────────────────────────────────────────
// 3. Gardens of Eden of an elementary CA rule on a ring (GoE = 2^n - |image|)
// ───────────────────────────────────────────────────────────────────────────
function goe(rule, n) {
  const N = 1 << n, tt = []; for (let p = 0; p < 8; p++) tt[p] = (rule >> p) & 1;
  const seen = new Set();
  for (let s = 0; s < N; s++) {
    let out = 0;
    for (let i = 0; i < n; i++) {
      const l = (s >> ((i - 1 + n) % n)) & 1, c = (s >> i) & 1, r = (s >> ((i + 1) % n)) & 1;
      out |= (tt[(l << 2) | (c << 1) | r] << i);
    }
    seen.add(out);
  }
  return N - seen.size;
}
section('Gardens of Eden of elementary CA on a ring (rules 30, 110, 184)');
{
  for (const [rule, file] of [[30, 'b-rule30-goe.txt'], [110, 'b-rule110-goe.txt'], [184, 'b-rule184-goe.txt']]) {
    let b; try { b = readB(oeis('ca-garden-of-eden/' + file)); } catch { continue; }
    for (let n = 1; n <= 16; n++) if (b.has(n)) check(`rule${rule} GoE(${n})`, goe(rule, n), b.get(n));
  }
}

// ───────────────────────────────────────────────────────────────────────────
// 4. Streak-selection bias — exact rational E(n) (Miller–Sanjurjo)
// ───────────────────────────────────────────────────────────────────────────
function gcdBig(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function streakExact(n) {
  let L = 1n; for (let i = 1n; i <= BigInt(n - 1); i++) L = (L / gcdBig(L, i)) * i;
  let sumNum = 0n, defined = 0n, total = 1 << n;
  for (let mask = 0; mask < total; mask++) {
    let o = 0, h = 0;
    for (let t = 1; t < n; t++) if ((mask >> (t - 1)) & 1) { o++; if ((mask >> t) & 1) h++; }
    if (o > 0) { sumNum += BigInt(h) * (L / BigInt(o)); defined++; }
  }
  let num = sumNum, den = L * defined, g = gcdBig(num, den);
  return [num / g, den / g];
}
section('Streak-selection bias exact rationals (Miller-Sanjurjo)');
{
  const bn = readB(oeis('streak-selection-bias/b-file-numerators.txt')), bd = readB(oeis('streak-selection-bias/b-file-denominators.txt'));
  for (let n = 2; n <= 14; n++) { const [num, den] = streakExact(n); check(`streak num(${n})`, num, bn.get(n)); check(`streak den(${n})`, den, bd.get(n)); }
}

// ───────────────────────────────────────────────────────────────────────────
// 5. Bulgarian solitaire — total settling time S(n) over all partitions of n
// ───────────────────────────────────────────────────────────────────────────
function* partitions(n, max = n) {
  if (n === 0) { yield []; return; }
  for (let k = Math.min(n, max); k >= 1; k--) for (const rest of partitions(n - k, k)) yield [k, ...rest];
}
function bulgStep(p) { const k = p.length, np = []; for (const x of p) if (x - 1 > 0) np.push(x - 1); np.push(k); return np.sort((a, b) => b - a); }
function settling(p) {
  const seen = new Map(); let cur = p.slice().sort((a, b) => b - a), t = 0;
  for (; ;) { const key = cur.join(','); if (seen.has(key)) return seen.get(key); seen.set(key, t); cur = bulgStep(cur); t++; }
}
section('Bulgarian solitaire total settling time S(n)');
{
  const b = readB(oeis('bulgarian-solitaire-settling/b-file.txt'));
  for (let n = 1; n <= 16; n++) { let S = 0; for (const p of partitions(n)) S += settling(p); check(`bulgarian S(${n})`, S, b.get(n)); }
}

// ───────────────────────────────────────────────────────────────────────────
// 6. Graceful-labeling totals — fan F_n and helm H_n (backtracking with pruning)
// ───────────────────────────────────────────────────────────────────────────
const fanGraph = (n) => { const e = []; for (let i = 0; i < n - 1; i++) e.push([i, i + 1]); for (let i = 0; i < n; i++) e.push([i, n]); return { v: n + 1, e }; };
const helmGraph = (n) => { const e = []; const hub = n; for (let i = 0; i < n; i++) { e.push([i, (i + 1) % n]); e.push([i, hub]); e.push([i, n + 1 + i]); } return { v: 2 * n + 1, e }; };
function gracefulTotal(v, edges) {
  const m = edges.length, back = Array.from({ length: v }, () => []);
  for (const [a, b] of edges) back[Math.max(a, b)].push(Math.min(a, b));
  const label = new Array(v).fill(-1), usedL = new Array(m + 1).fill(false), usedD = new Array(m + 1).fill(false);
  let count = 0;
  (function rec(i) {
    if (i === v) { count++; return; }
    for (let L = 0; L <= m; L++) {
      if (usedL[L]) continue;
      let ok = true; const added = [];
      for (const nb of back[i]) { const d = Math.abs(L - label[nb]); if (d < 1 || d > m || usedD[d]) { ok = false; break; } usedD[d] = true; added.push(d); }
      if (ok) { usedL[L] = true; label[i] = L; rec(i + 1); label[i] = -1; usedL[L] = false; }
      for (const d of added) usedD[d] = false;
    }
  })(0);
  return count;
}
section('Graceful-labeling totals: fan F_n (n<=6), helm H_n (n=3)');
{
  const bf = readB(oeis('graceful-census/b-fan.txt')), bh = readB(oeis('graceful-census/b-helm.txt'));
  for (let n = 2; n <= 6; n++) { const g = fanGraph(n); check(`fan(${n})`, gracefulTotal(g.v, g.e), bf.get(n)); }
  { const g = helmGraph(3); check(`helm(3)`, gracefulTotal(g.v, g.e), bh.get(3)); }
}

// ───────────────────────────────────────────────────────────────────────────
// 7. Non-attacking leapers — FLAT board vs published OEIS, then Mobius/Klein vs b-files
// ───────────────────────────────────────────────────────────────────────────
function leaperOffsets(a, b) {
  const s = new Set(), out = [];
  for (const [x, y] of [[a, b], [b, a]]) for (const sx of [1, -1]) for (const sy of [1, -1]) {
    const k = (x * sx) + ',' + (y * sy); if (!s.has(k)) { s.add(k); out.push([x * sx, y * sy]); }
  }
  return out;
}
function leaperFlat(a, b, n) {
  const mv = leaperOffsets(a, b), colUsed = new Array(n).fill(false), col = new Array(n).fill(-1);
  let count = 0;
  const atk = (r1, c1, r2, c2) => mv.some(([dr, dc]) => r1 + dr === r2 && c1 + dc === c2);
  (function rec(r) {
    if (r === n) { count++; return; }
    for (let c = 0; c < n; c++) { if (colUsed[c]) continue; let ok = true; for (let pr = 0; pr < r; pr++) if (atk(r, c, pr, col[pr]) || atk(pr, col[pr], r, c)) { ok = false; break; } if (ok) { colUsed[c] = true; col[r] = c; rec(r + 1); colUsed[c] = false; } }
  })(0);
  return count;
}
function leaperSurface(topo, a, b, n) {
  const mv = leaperOffsets(a, b);
  const fold = (r, c, dr, dc) => {
    let R = r + dr, C = c + dc;
    if (topo === 'mobius') { while (C < 0) { C += n; R = n - 1 - R; } while (C >= n) { C -= n; R = n - 1 - R; } if (R < 0 || R >= n) return null; return [R, C]; }
    while (C < 0) C += n; while (C >= n) C -= n; while (R < 0) { R += n; C = n - 1 - C; } while (R >= n) { R -= n; C = n - 1 - C; } return [R, C];
  };
  const atk = (r1, c1, r2, c2) => mv.some(([dr, dc]) => { const t = fold(r1, c1, dr, dc); return t && t[0] === r2 && t[1] === c2; });
  const colUsed = new Array(n).fill(false), col = new Array(n).fill(-1); let count = 0;
  (function rec(r) {
    if (r === n) { count++; return; }
    for (let c = 0; c < n; c++) { if (colUsed[c]) continue; let ok = true; for (let pr = 0; pr < r; pr++) if (atk(r, c, pr, col[pr]) || atk(pr, col[pr], r, c)) { ok = false; break; } if (ok) { colUsed[c] = true; col[r] = c; rec(r + 1); colUsed[c] = false; } }
  })(0);
  return count;
}
section('Leapers: FLAT board reproduces published OEIS (calibration), then Mobius/Klein vs b-files');
{
  // published flat-board leaper permutation counts (external ground truth)
  const FLAT = {
    knight: [1, 2, 2, 8, 20, 94, 438, 2766],   // A137774
    camel: [1, 2, 6, 8, 24, 126, 524, 3072],   // A189358 (n>=1)
    zebra: [1, 2, 6, 12, 36, 174, 708, 4334],  // A189565
    giraffe: [1, 2, 6, 24, 48, 182, 868, 5752], // A189563
  };
  const V = { knight: [1, 2], camel: [1, 3], zebra: [2, 3], giraffe: [1, 4] };
  for (const name of Object.keys(FLAT)) for (let n = 1; n <= FLAT[name].length; n++) check(`flat ${name} n=${n}`, leaperFlat(V[name][0], V[name][1], n), FLAT[name][n - 1]);
  // surfaces vs committed b-files (kept only if the fold matches — honest either way)
  for (const topo of ['mobius', 'klein']) for (const name of Object.keys(V)) {
    let b; try { b = readB(oeis(`nonorientable-leapers/b-${topo}-${name}.txt`)); } catch { continue; }
    for (let n = 1; n <= 9; n++) if (b.has(n)) check(`${topo} ${name} n=${n}`, leaperSurface(topo, V[name][0], V[name][1], n), b.get(n));
  }
}

// ───────────────────────────────────────────────────────────────────────────
console.log(results.join('\n'));
console.log(`\n${PASS}/${PASS + FAIL} independent recomputations match the committed data.`);
process.exit(FAIL === 0 ? 0 : 1);
