#!/usr/bin/env node
// research/rock-paper-lizard/verify.mjs — offline verifier for "Rock, Paper, Lizard".
//
//   node research/rock-paper-lizard/verify.mjs
//
// Re-derives, from first principles, everything the page asserts:
//   I.   THE CYCLES ARE REAL CYCLES — the dominance relations the two papers record
//        (orange→blue→yellow→orange; C→S→R→C) are intransitive 3-cycles: no node
//        beats every other, so no Condorcet champion exists. (A structural check on
//        the SOURCED edge directions — no invented magnitudes.)
//   II.  NO RANKING CAN SEE A CYCLE — the Hodge/Helmholtz decomposition of a pure
//        3-cycle's pairwise-margin field is 100% curl and 0% gradient, so a scalar
//        rating (the gradient part) captures exactly 0% of it; a true ranking (a
//        difference of scores) is 100% gradient and 0% curl. The same lens that
//        'No King of the Hill' aims at AI leaderboards, here aimed at a lizard.
//   III. THE CYCLE KEEPS ALL THREE ALIVE — the symmetric zero-sum replicator
//        dynamics have their only interior rest point at (1/3,1/3,1/3); the product
//        x_O·x_B·x_Y is an exact constant of motion, so trajectories are closed
//        orbits that never converge and never go extinct; and the time-average of an
//        orbit is the centre (the honest 'ranking' of a cycle is a distribution, not
//        a winner). Hofbauer & Sigmund (1998), ch. 7.
//   IV.  THE TILT DECIDES THE FATE — break the zero-sum symmetry and the centre turns
//        into a spiral; the SIGN of the perturbation (equivalently the real part of
//        the Jacobian's complex eigenvalues) decides whether it spirals inward
//        (coexistence) or outward (toward the boundary cycle).
//   V.   THE LEDGER IS HONEST — the bibliography is complete and the page embeds these
//        sources; every model is labelled a model, not field data.
//
// "Show the check": the facts are sourced in sources.mjs; the mathematics is here,
// dependency-free.

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { BIB, LIZARD, COLICIN } from "./sources.mjs";

let PASS = 0, FAIL = 0;
const log = [];
function check(name, cond, got, want) {
  if (cond) { PASS++; log.push(`  ok   ${name}`); }
  else { FAIL++; log.push(`  FAIL ${name}\n         got:  ${got}\n         want: ${want}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── I · the cycles are genuine intransitive cycles ───────────────────────────
log.push("I. THE CYCLES — sourced dominance edges form a true 3-cycle (no champion)");

// Turn a list of [winner,loser] edges over 3 named nodes into a tournament and
// test: every node has exactly one win and one loss (the signature of a 3-cycle),
// and there is no node that beats both others (no Condorcet winner).
function analyseTournament(name, nodes, edges) {
  const ids = Object.keys(nodes);
  check(`${name}: exactly 3 morphs/strains`, ids.length === 3, ids.length, 3);
  check(`${name}: exactly 3 dominance edges`, edges.length === 3, edges.length, 3);
  const wins = Object.fromEntries(ids.map((k) => [k, 0]));
  const losses = Object.fromEntries(ids.map((k) => [k, 0]));
  for (const [w, l] of edges) { wins[w]++; losses[l]++; }
  const everyOneOne = ids.every((k) => wins[k] === 1 && losses[k] === 1);
  check(`${name}: every node wins once and loses once (a 3-cycle)`, everyOneOne,
    JSON.stringify(wins), "each 1");
  const champion = ids.find((k) => wins[k] === 2);
  check(`${name}: no Condorcet champion (intransitive)`, champion === undefined,
    champion ?? "none", "none");
  // build the +1/-1 antisymmetric margin matrix used in part II
  const idx = Object.fromEntries(ids.map((k, i) => [k, i]));
  const Y = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
  for (const [w, l] of edges) { Y[idx[w]][idx[l]] = 1; Y[idx[l]][idx[w]] = -1; }
  return Y;
}

const Ylizard = analyseTournament("lizard", LIZARD.nodes, LIZARD.cycle.map((e) => [e[0], e[1]]));
const Ycolicin = analyseTournament("colicin", COLICIN.nodes, COLICIN.cycle.map((e) => [e[0], e[1]]));

// the two recorded cycles are the SAME abstract object up to relabelling
const sameShape = JSON.stringify(Ylizard) === JSON.stringify(Ycolicin)
  || JSON.stringify(Ylizard) === JSON.stringify(Ycolicin.map((r) => r.map((v) => -v)));
check("lizard and colicin are the same 3-cycle up to orientation", sameShape,
  "compared margin matrices", "identical or reversed");

// ── II · the Hodge decomposition — a ranking sees 0% of a cycle ───────────────
log.push("");
log.push("II. NO RANKING CAN SEE A CYCLE — Hodge/Helmholtz on the margin field");

// Helmholtz–Hodge on the complete graph K3: split an antisymmetric edge field Y_ij
// into a GRADIENT part grad(s)_ij = s_i - s_j (a pure ranking by scores s) plus a
// CURL/cyclic residual. The best-fit potential solves the graph-Laplacian normal
// equations; on K3 the Laplacian is L = 3I - J (J all-ones), and the gradient flow
// that best explains Y has scores s_i ∝ (row sum of Y)_i / 3 (the "net wins").
function hodge(Y) {
  const n = Y.length;
  // divergence d_i = sum_j Y_ij ; potential s = L^+ d, with s_i = d_i / n on K3
  const div = Y.map((row) => row.reduce((a, b) => a + b, 0));
  const s = div.map((d) => d / n);
  // gradient field and curl residual
  let normY = 0, normCurl = 0;
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
    const g = s[i] - s[j];
    const curl = Y[i][j] - g;
    normY += Y[i][j] * Y[i][j];
    normCurl += curl * curl;
  }
  return { cyclicFraction: normCurl / normY, scores: s };
}

const hCycle = hodge(Ylizard);
check("a pure 3-cycle is 100% curl (cyclic fraction = 1)", near(hCycle.cyclicFraction, 1, 1e-12),
  hCycle.cyclicFraction, 1);
check("a pure 3-cycle has flat best-fit scores (ranking is blind to it)",
  hCycle.scores.every((v) => near(v, 0, 1e-12)), JSON.stringify(hCycle.scores), "all 0");

// a genuine ranking (margins that ARE a difference of scores) is the opposite: 0% curl
const r = [3, 1, 0]; // arbitrary distinct scores → a transitive ladder
const Yladder = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) Yladder[i][j] = r[i] - r[j];
const hLadder = hodge(Yladder);
check("a ranking (difference of scores) is 0% curl", near(hLadder.cyclicFraction, 0, 1e-12),
  hLadder.cyclicFraction, 0);
check("the gradient part recovers the score gaps", near(hLadder.scores[0] - hLadder.scores[2], r[0] - r[2], 1e-9),
  hLadder.scores[0] - hLadder.scores[2], r[0] - r[2]);

// ── III · the cycle keeps all three alive — symmetric zero-sum replicator ─────
log.push("");
log.push("III. COEXISTENCE — the symmetric replicator: closed orbits, conserved product");

// payoff matrix for the canonical rock–paper–scissors (win +1, lose -1, tie 0),
// with strategy 0 beats 1 beats 2 beats 0.
const A = [[0, 1, -1], [-1, 0, 1], [1, -1, 0]];
function matvec(M, x) { return M.map((row) => row.reduce((a, m, j) => a + m * x[j], 0)); }
function dot(a, b) { return a.reduce((s, v, i) => s + v * b[i], 0); }
function replicatorRHS(M, x) {
  const f = matvec(M, x);
  const phi = dot(x, f);
  return x.map((xi, i) => xi * (f[i] - phi));
}
function rk4step(M, x, dt) {
  const k1 = replicatorRHS(M, x);
  const k2 = replicatorRHS(M, x.map((v, i) => v + 0.5 * dt * k1[i]));
  const k3 = replicatorRHS(M, x.map((v, i) => v + 0.5 * dt * k2[i]));
  const k4 = replicatorRHS(M, x.map((v, i) => v + dt * k3[i]));
  let y = x.map((v, i) => v + (dt / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]));
  const sum = y.reduce((a, b) => a + b, 0); // renormalise to the simplex (guards drift)
  return y.map((v) => v / sum);
}

// the centre is a rest point
const centre = [1 / 3, 1 / 3, 1 / 3];
const rhsCentre = replicatorRHS(A, centre);
check("the centre (1/3,1/3,1/3) is a rest point", rhsCentre.every((v) => near(v, 0, 1e-15)),
  JSON.stringify(rhsCentre.map((v) => +v.toFixed(15))), "0,0,0");

// mean fitness is identically zero (antisymmetric payoff)
let meanMax = 0;
for (let t = 0; t < 200; t++) {
  const x = [0.2 + 0.6 * Math.random(), 0, 0];
  x[1] = (1 - x[0]) * Math.random(); x[2] = 1 - x[0] - x[1];
  meanMax = Math.max(meanMax, Math.abs(dot(x, matvec(A, x))));
}
check("mean fitness x·Ax is identically 0 on the whole simplex", near(meanMax, 0, 1e-12),
  meanMax, 0);

// the product V = x0·x1·x2 is a constant of motion, so orbits are CLOSED
let x = [0.5, 0.3, 0.2];
const V0 = x[0] * x[1] * x[2];
let Vmax = V0, Vmin = V0;
const traj = [];
const dt = 0.01, steps = 60000;
for (let t = 0; t < steps; t++) {
  x = rk4step(A, x, dt);
  traj.push(x.slice());
  const V = x[0] * x[1] * x[2];
  Vmax = Math.max(Vmax, V); Vmin = Math.min(Vmin, V);
}
check("the product x_O·x_B·x_Y is conserved (orbit is closed, nothing goes extinct)",
  near(Vmax - Vmin, 0, 1e-6), `drift ${(Vmax - Vmin).toExponential(2)}`, "< 1e-6");
// no morph approaches extinction along the orbit
const minComponent = Math.min(...traj.map((p) => Math.min(...p)));
check("no morph approaches extinction (min frequency stays well above 0)",
  minComponent > 0.05, minComponent.toFixed(4), "> 0.05");

// the time-average of an orbit is the centre — the 'ranking' of a cycle is a
// distribution, not a winner (the same lesson as the maximal lottery)
const avg = [0, 0, 0];
for (const p of traj) for (let i = 0; i < 3; i++) avg[i] += p[i] / traj.length;
check("the time-average of the orbit is the centre (the honest 'winner' is the mix)",
  avg.every((v) => near(v, 1 / 3, 2e-3)), JSON.stringify(avg.map((v) => +v.toFixed(4))), "≈ 1/3 each");

// ── IV · the tilt decides the fate — generalised RPS spirals ──────────────────
log.push("");
log.push("IV. THE TILT — break zero-sum symmetry and the centre becomes a spiral");

// add a symmetric self-interaction e: A_e = A + e·(J - I)·... use the standard
// generalised RPS  payoff  win=1, lose=-1, plus a uniform bonus e to the winner.
// e>0 makes the interior point an attractor (spiral in); e<0 a repeller (spiral out).
function genA(e) { return [[0, 1 + e, -1], [-1, 0, 1 + e], [1 + e, -1, 0]]; }

function endProduct(e, x0) {
  let x = x0.slice();
  for (let t = 0; t < 40000; t++) x = rk4step(genA(e), x, dt);
  return x[0] * x[1] * x[2]; // → its max (1/27) if spiralling in, → 0 if spiralling out
}
const start = [0.45, 0.34, 0.21];
const Vin = endProduct(0.6, start);   // e>0 : inward
const Vout = endProduct(-0.6, start); // e<0 : outward
check("e > 0 spirals inward toward coexistence (product climbs toward 1/27)",
  Vin > 0.9 * (1 / 27), Vin.toFixed(5), "→ 1/27 ≈ 0.03704");
check("e < 0 spirals outward toward the boundary cycle (product tends to 0)",
  Vout < 1e-4, Vout.toExponential(2), "→ 0");

// the Jacobian's eigenvalues at the centre have real part of the sign of e
function jacobianRealPart(e) {
  // numerical Jacobian of the (2-D, simplex-reduced) replicator field at the centre
  const h = 1e-6;
  const f = (p) => {
    const x = [p[0], p[1], 1 - p[0] - p[1]];
    const r = replicatorRHS(genA(e), x);
    return [r[0], r[1]];
  };
  const p0 = [1 / 3, 1 / 3];
  const J = [[0, 0], [0, 0]];
  for (let j = 0; j < 2; j++) {
    const pp = p0.slice(); pp[j] += h; const pm = p0.slice(); pm[j] -= h;
    const fp = f(pp), fm = f(pm);
    for (let i = 0; i < 2; i++) J[i][j] = (fp[i] - fm[i]) / (2 * h);
  }
  return (J[0][0] + J[1][1]) / 2; // real part of the complex-conjugate eigenvalues = trace/2
}
check("Jacobian real part < 0 when e > 0 (stable focus)", jacobianRealPart(0.6) < -1e-4,
  jacobianRealPart(0.6).toFixed(5), "< 0");
check("Jacobian real part > 0 when e < 0 (unstable focus)", jacobianRealPart(-0.6) > 1e-4,
  jacobianRealPart(-0.6).toFixed(5), "> 0");
check("Jacobian real part = 0 when e = 0 (the neutral centre)", near(jacobianRealPart(0), 0, 1e-4),
  jacobianRealPart(0).toFixed(6), "≈ 0");

// ── V · the ledger is honest ──────────────────────────────────────────────────
log.push("");
log.push("V. THE LEDGER — bibliography complete, sources embedded, models labelled");

for (const [key, b] of Object.entries(BIB)) {
  const ok = b.authors && b.year && b.title && b.journal && (b.doi || b.volume);
  check(`bib '${key}' is complete`, !!ok, JSON.stringify(b), "authors/year/title/journal/doi");
}
check("Sinervo & Lively is Nature 380:240–243 (1996)",
  BIB.sinervo1996.volume === 380 && BIB.sinervo1996.pages === "240–243" && BIB.sinervo1996.year === 1996,
  `${BIB.sinervo1996.volume}:${BIB.sinervo1996.pages} (${BIB.sinervo1996.year})`, "380:240–243 (1996)");
check("Kerr et al. is Nature 418:171–174 (2002)",
  BIB.kerr2002.volume === 418 && BIB.kerr2002.pages === "171–174" && BIB.kerr2002.year === 2002,
  `${BIB.kerr2002.volume}:${BIB.kerr2002.pages} (${BIB.kerr2002.year})`, "418:171–174 (2002)");
check("Reichenbach et al. is Nature 448:1046–1049 (2007)",
  BIB.reichenbach2007.volume === 448 && BIB.reichenbach2007.pages === "1046–1049" && BIB.reichenbach2007.year === 2007,
  `${BIB.reichenbach2007.volume}:${BIB.reichenbach2007.pages} (${BIB.reichenbach2007.year})`, "448:1046–1049 (2007)");
check("the lizard period is recorded as ~6 years (Sinervo & Lively 1996)", LIZARD.periodYears === 6,
  LIZARD.periodYears, 6);

// drift guard — the published page must embed each DOI and the headline facts
try {
  const here = dirname(fileURLToPath(import.meta.url));
  const page = readFileSync(join(here, "..", "..", "public", "strata", "rock-paper-lizard", "index.html"), "utf8");
  for (const [key, b] of Object.entries(BIB)) {
    check(`page embeds DOI for '${key}'`, page.includes(b.doi), b.doi, "present in page");
  }
  check("page names the side-blotched lizard", /Uta stansburiana/.test(page), "—", "Uta stansburiana");
  check("page names colicin / E. coli", /colicin/i.test(page), "—", "colicin");
  check("page carries the '0%' ranking claim", /0%|0 %|zero/i.test(page), "—", "the 0% claim");
} catch (e) {
  check("page present for drift guard", false, String(e), "public/strata/rock-paper-lizard/index.html");
}

// ── report ────────────────────────────────────────────────────────────────────
console.log(log.join("\n"));
console.log(`\n${PASS}/${PASS + FAIL} checks pass${FAIL ? ` — ${FAIL} FAILED` : ""}.`);
process.exit(FAIL ? 1 : 0);
