// verify.mjs — "Nowhere New to Go" (a portal across the functional-graph spine).
//
// The portal's one claim: the-shape-of-the-rho (x²+c mod n), topswops-machine (flip
// the top cards of a deck) and the-longest-way-home (Bulgarian solitaire) are three
// faces of ONE theorem — a deterministic map on a finite set is eventually periodic,
// so every orbit is a ρ (a tail draining into a cycle) and the state space is a
// functional graph. We prove it the honest way: build each stratum's REAL map, run
// the single generic engine (fgraph.mjs) on all three, and show
//   (a) the generic engine reproduces each stratum's own bespoke analyzer exactly,
//   (b) Floyd's O(1) cycle detector (the heart of Pollard's rho) agrees with the
//       O(N) seen-set reference on all three maps,
//   (c) the three faces have genuinely DIFFERENT signatures, so "three faces" is real.
//
// Run: node research/nowhere-new-to-go/verify.mjs   (exit 0 ⇔ all green)

import { analyzeGraph, orbitRef, floyd } from './fgraph.mjs';
import { mapFn, analyze as rhoAnalyze, expectedRhoLen } from '../pollard-rho/engine.mjs';
import { partitions, move, analyze as bulgAnalyze, maxTailForward } from '../bulgarian-solitaire/engine.mjs';
import { perms, rank, flipOnce, factorials, gardenIE, gardenDirect } from '../topswops/engine.mjs';

let pass = 0, fail = 0;
const ok = (cond, label) => { (cond ? pass++ : (fail++, 0)); console.log(`  ${cond ? 'ok  ' : 'FAIL'}  ${label}`); };
const eqArr = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

// ── Build the three real maps as (N, next) functional graphs ──────────────────

// 1. THE RHO — residues 0..n-1 under x ↦ x²+c (mod n).
function rhoGraph(n, c) {
  const f = mapFn(n, c);
  const next = new Int32Array(n);
  for (let x = 0; x < n; x++) next[x] = f(x);
  return next;
}

// 2. TOPSWOPS — permutations of {1..m} under "reverse the first a[0] cards"; a deck
//    with 1 on top is terminal, which we model as a fixed point (self-loop).
function topswopsGraph(m) {
  const fact = factorials(m);
  const base = Array.from({ length: m }, (_, i) => i + 1);
  const next = new Int32Array(fact[m]);
  for (const p of perms(base)) {
    const r = rank(p, m, fact);
    next[r] = p[0] === 1 ? r : rank(flipOnce(p), m, fact);
  }
  return next;
}

// 3. BULGARIAN SOLITAIRE — partitions of N under "deal one from every pile, gather".
function bulgarianGraph(N) {
  const parts = partitions(N);
  const idx = new Map(); parts.forEach((p, i) => idx.set(p.join(','), i));
  const next = new Int32Array(parts.length);
  parts.forEach((p, i) => { next[i] = idx.get(move(p).join(',')); });
  return next;
}

console.log('\nNOWHERE NEW TO GO — the functional-graph spine\n');

// ── A. The pigeonhole law holds on all three maps ─────────────────────────────
console.log('A · eventual periodicity — every orbit repeats within |S| steps');
for (const [name, N, next] of [
  ['rho   x²+1 mod 1009', 1009, rhoGraph(1009, 1)],
  ['topswops  m=6 (720 decks)', 720, topswopsGraph(6)],
  ['bulgarian N=20 (627 parts)', null, bulgarianGraph(20)],
]) {
  const n = N ?? next.length;
  let worstVisited = 0, allClose = true, anyRepeat = false;
  for (let s = 0; s < n; s++) {
    const { tail, cycle, visited } = orbitRef(n, next, s);
    if (visited > worstVisited) worstVisited = visited;
    if (tail + cycle !== visited || visited > n) allClose = false;
    if (cycle >= 1) anyRepeat = true;
  }
  ok(allClose && worstVisited <= n && anyRepeat,
     `${name}: every start visits ≤${n} distinct states, then loops (worst ρ = ${worstVisited})`);
}

// ── B. The one generic engine reproduces each stratum's BESPOKE analyzer ───────
console.log('\nB · one engine — generic fgraph == each stratum’s own analyzer');
{
  // rho: bespoke analyze(n,c) returns {cycles, periodic, fixed, longest, spectrum, tailSum}
  const n = 2003, c = 1;
  const g = analyzeGraph(n, rhoGraph(n, c)), b = rhoAnalyze(n, c);
  ok(g.cycles === b.cycles && g.periodic === b.periodic && g.fixedPoints === b.fixed &&
     g.longestCycle === b.longest && g.tailSum === b.tailSum && eqArr(g.cycleLens, b.spectrum),
     `rho n=${n}: cycles=${g.cycles} periodic=${g.periodic} fixed=${g.fixedPoints} longestCyc=${g.longestCycle} — match`);
}
for (const N of [18, 23, 28]) {
  // bulgarian: bespoke analyze(N) returns {fixed, numCycles, recurrent, goe, longest, maxTail, totalSettle, cycleLens}
  const g = analyzeGraph(partitions(N).length, bulgarianGraph(N)), b = bulgAnalyze(N);
  ok(g.cycles === b.numCycles && g.periodic === b.recurrent && g.fixedPoints === b.fixed &&
     g.gardenOfEden === b.goe && g.longestCycle === b.longest && g.longestTail === b.maxTail &&
     g.tailSum === b.totalSettle && eqArr(g.cycleLens, b.cycleLens),
     `bulgarian N=${N}: parts=${g.N} cycles=${g.cycles} GoE=${g.gardenOfEden} longestTail=${g.longestTail} — match bespoke`);
  // independent forward-iteration cross-check of the worst tail
  ok(g.longestTail === maxTailForward(N), `bulgarian N=${N}: longestTail == forward-iteration maxTail (${g.longestTail})`);
}

// ── C. Floyd (O(1) memory) == seen-set reference (O(N)) on all three maps ──────
console.log('\nC · one detector — Floyd’s tortoise & hare == seen-set, on every map');
for (const [name, n, next] of [
  ['rho   x²+1 mod 5003', 5003, rhoGraph(5003, 1)],
  ['topswops m=6', 720, topswopsGraph(6)],
  ['bulgarian N=24', partitions(24).length, bulgarianGraph(24)],
]) {
  let agree = true;
  for (let s = 0; s < n; s++) {
    const r = orbitRef(n, next, s), fl = floyd(n, next, s);
    if (r.tail !== fl.tail || r.cycle !== fl.cycle || r.enters !== fl.enters) { agree = false; break; }
  }
  ok(agree, `${name}: Floyd finds the same μ (tail), λ (cycle) and entry for all ${n} seeds`);
}

// ── D. The three faces are genuinely DIFFERENT signatures ─────────────────────
console.log('\nD · three faces — the signatures differ, so the portal isn’t three copies');
{
  // TOPSWOPS: Conway proved it always halts ⇒ every recurrent state is a FIXED POINT.
  for (const m of [4, 5, 6]) {
    const g = analyzeGraph(factorials(m)[m], topswopsGraph(m));
    const allFixed = g.cycleLens.every(L => L === 1) && g.longestCycle <= 1;
    const expectedFixed = factorials(m)[m - 1]; // (m-1)! decks have 1 on top
    ok(allFixed && g.fixedPoints === expectedFixed,
       `topswops m=${m}: a pure FOREST — every cycle length 1; ${g.fixedPoints} fixed points == (m-1)! = ${expectedFixed}`);
  }
  // TOPSWOPS Garden of Eden, the FUNCTIONAL-GRAPH way the bench shows it: states with
  // in-degree 0 (nothing maps to them). NOTE this is a different slicing from the
  // stratum's published "decks that are not a flip-image" = A000255(m−1): that count also
  // includes halted decks, which here self-loop and so are never in-degree 0. We keep ONE
  // definition across all three maps and check it by an independent image-set recount.
  for (const m of [5, 6, 7]) {
    const fact = factorials(m), Nn = fact[m], next = topswopsGraph(m), g = analyzeGraph(Nn, next);
    const isImage = new Uint8Array(Nn);
    for (const p of perms(Array.from({ length: m }, (_, i) => i + 1))) isImage[p[0] === 1 ? rank(p, m, fact) : rank(flipOnce(p), m, fact)] = 1;
    let goe = 0; for (let i = 0; i < Nn; i++) if (!isImage[i]) goe++;
    ok(g.gardenOfEden === goe && goe > 0,
      `topswops m=${m}: ${goe} Garden-of-Eden states (in-degree 0) — image-set recount agrees`);
  }
  // (sanity: the stratum's own A000255(m−1) count is internally consistent — a different object)
  ok(gardenIE(5) === gardenDirect(5) && gardenIE(5) === 53, "topswops: the stratum's 'not-a-flip-image' count is self-consistent (A000255, distinct from the above)");

  // BULGARIAN: real cycles of length > 1 exist (so NOT a pure forest), and a single
  // fixed point (the staircase) appears exactly when N is triangular.
  const g8 = analyzeGraph(partitions(8).length, bulgarianGraph(8));
  ok(g8.longestCycle > 1 && eqArr(g8.cycleLens, [...g8.cycleLens].sort((a, b) => a - b)) && g8.cycleLens.includes(2),
     `bulgarian N=8: genuine loops — cycle lengths ${JSON.stringify(g8.cycleLens)} (not all 1)`);
  const tri = new Set([1, 3, 6, 10, 15, 21, 28, 36, 45]);
  let triOK = true;
  for (let N = 1; N <= 30; N++) { const f = analyzeGraph(partitions(N).length, bulgarianGraph(N)).fixedPoints; if ((f === 1) !== tri.has(N)) triOK = false; }
  ok(triOK, 'bulgarian: exactly one fixed point (the staircase) ⇔ N is triangular (checked N=1..30)');
  ok(analyzeGraph(partitions(45).length, bulgarianGraph(45)).longestTail === 9 * 9 - 9,
     'bulgarian N=45: worst tail = 72 = k²−k for k=9 (T₉=45)  [Igusa/Étienne, tight]');

  // RHO: a generic map — cycles of many lengths, and a ρ length that scales like √n.
  const gA = analyzeGraph(1009, rhoGraph(1009, 1)), gB = analyzeGraph(8009, rhoGraph(8009, 1));
  ok(gA.longestCycle > 1 && gB.longestCycle > 1, 'rho: real loops of length > 1 (a generic map, not a forest)');
}

// ── E. The √n birthday law that makes Pollard’s rho fast (labelled: statistical) ─
console.log('\nE · the √n birthday law (statistical comparison, not an exact claim)');
{
  // mean ρ length over all seeds, vs the random-map expectation √(πn/2).
  const meanRho = (n, c) => {
    let s = 0; for (let x = 0; x < n; x++) { const o = orbitRef(n, next_cache(n, c), x); s += o.tail + o.cycle; } return s / n;
  };
  const cache = new Map();
  function next_cache(n, c) { const k = n + ':' + c; if (!cache.has(k)) cache.set(k, rhoGraph(n, c)); return cache.get(k); }
  const m1 = meanRho(1009, 1), m2 = meanRho(8009, 1);
  const e1 = expectedRhoLen(1009), e2 = expectedRhoLen(8009);
  ok(m2 > m1, `mean ρ grows with n: ${m1.toFixed(1)} (n=1009) → ${m2.toFixed(1)} (n=8009)`);
  ok(m1 / e1 > 0.5 && m1 / e1 < 2 && m2 / e2 > 0.5 && m2 / e2 < 2,
     `mean ρ within a factor 2 of √(πn/2): ratios ${(m1 / e1).toFixed(2)}, ${(m2 / e2).toFixed(2)} (x²+c is near-random, not exactly)`);
}

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