/* ============================================================================
 * verify.mjs — offline check for "Built to Be Misread"
 *
 * Loads the SAME model the page ships (public/strata/built-to-be-misread/model.js)
 * and re-checks every claim the page can make:
 *   1. the codon table really is the standard code (independent biochemistry checks);
 *   2. the mutation graph has the right shape;
 *   3. the published property scales are loaded verbatim;
 *   4. the error-cost / randomisation result — where the natural code falls among
 *      a million block-preserving random codes — under each metric and mutation
 *      model, with FIXED seeds, so the figures the page prints are reproduced here
 *      bit-for-bit.
 *
 * Run:  node research/built-to-be-misread/verify.mjs
 * ==========================================================================*/
import { fileURLToPath, pathToFileURL } from "node:url";
import { dirname, join } from "node:path";

const here = dirname(fileURLToPath(import.meta.url));
await import(pathToFileURL(
  join(here, "..", "..", "public", "strata", "built-to-be-misread", "model.js")
).href);
const G = globalThis.GeneticCode;

let pass = 0, fail = 0;
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? "  — " + detail : ""}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? "  — " + detail : ""}`); }
}
function eq(a, b) { return a === b; }
function near(a, b, tol) { return Math.abs(a - b) <= tol; }

console.log("\nBuilt to Be Misread — verifier\n");

// ── 1. The codon table is the standard code ────────────────────────────────
console.log("The standard code (independent biochemistry checks)");
ok("64 codons enumerated", eq(G.CODONS.length, 64) && eq(G.AA.length, 64));
ok("all 64 codons distinct", new Set(G.CODONS).size === 64);
const senseCount = G.AA.filter((x) => x !== "*").length;
ok("61 sense codons + 3 stops", eq(senseCount, 61) && eq(G.STOPS.length, 3));
const stopCodons = G.STOPS.map((i) => G.CODONS[i]).sort().join(",");
ok("stops are TAA, TAG, TGA", eq(stopCodons, "TAA,TAG,TGA"), stopCodons);
ok("start/Met is the sole ATG codon",
  G.AA[G.codonIndex["ATG"]] === "M" && G.AA.filter((x) => x === "M").length === 1);
ok("Trp is the sole TGG codon",
  G.AA[G.codonIndex["TGG"]] === "W" && G.AA.filter((x) => x === "W").length === 1);
// degeneracy pattern of the standard code: codon counts per amino acid
const counts = {}; G.AMINOS.forEach((a) => { counts[a] = G.blocks[a].length; });
ok("Leu, Ser, Arg are 6-fold; Met, Trp 1-fold",
  counts.L === 6 && counts.S === 6 && counts.R === 6 && counts.M === 1 && counts.W === 1,
  `L${counts.L} S${counts.S} R${counts.R} M${counts.M} W${counts.W}`);
ok("blocks partition the 61 sense codons",
  G.AMINOS.reduce((s, a) => s + counts[a], 0) === 61);
ok("20 amino acids present", G.AMINOS.length === 20 && new Set(G.AMINOS).size === 20);
// a few spot codons most people can recall
ok("UUU→Phe, AUG→Met, GGN→Gly, UGA=stop",
  G.AA[G.codonIndex["TTT"]] === "F" &&
  G.AA[G.codonIndex["ATG"]] === "M" &&
  G.AA[G.codonIndex["GGG"]] === "G" &&
  G.AA[G.codonIndex["TGA"]] === "*");

// ── 2. The single-base mutation graph ──────────────────────────────────────
console.log("\nThe mutation graph (sense → sense single substitutions)");
// 61 sense codons × 9 substitutions = 549 directed point mutations total;
// remove those that hit a stop codon; the remainder is what the cost averages.
let toStop = 0;
for (let i = 0; i < 64; i++) {
  if (G.AA[i] === "*") continue;
  const c = G.CODONS[i];
  for (let p = 0; p < 3; p++) for (const b of G.ORDER) {
    if (b === c[p]) continue;
    if (G.AA[G.codonIndex[c.slice(0, p) + b + c.slice(p + 1)]] === "*") toStop++;
  }
}
ok("549 single substitutions from sense codons", 61 * 9 === 549);
ok(`${toStop} of them create a stop (excluded as nonsense)`, toStop > 0, `${toStop} excluded`);
ok("model keeps exactly the sense→sense substitutions",
  G.subs.length === 549 - toStop, `${G.subs.length} kept`);
const ts = G.subs.filter((s) => s.type === "ts").length;
const tv = G.subs.filter((s) => s.type === "tv").length;
ok("transitions + transversions account for all kept subs", ts + tv === G.subs.length,
  `${ts} ts + ${tv} tv`);

// ── 3. The property scales are the published values ─────────────────────────
console.log("\nProperty scales (published measurements, loaded verbatim)");
ok("polar requirement: Asp 13.0 (max), Cys 4.8 (min), 20 values",
  G.SCALES.polar.D === 13.0 && G.SCALES.polar.C === 4.8 &&
  Object.keys(G.SCALES.polar).length === 20);
ok("residue volume: Gly 60.1 (min), Trp 227.8 (max)",
  G.SCALES.volume.G === 60.1 && G.SCALES.volume.W === 227.8);
ok("hydropathy: Ile +4.5 (most), Arg −4.5 (least)",
  G.SCALES.hydro.I === 4.5 && G.SCALES.hydro.R === -4.5);
ok("each scale defined for all 20 amino acids",
  ["polar", "volume", "hydro"].every((m) => G.AMINOS.every((a) => typeof G.SCALES[m][a] === "number")));

// ── 4. The experiment — where the natural code falls ───────────────────────
// One million block-preserving random codes; fixed seed; per metric & model.
// The page prints exactly these figures (same model, same seed, same N).
console.log("\nThe experiment — 1,000,000 random codes, seed 12345");
const N = 1_000_000, SEED = 12345;

function run(metric, tsWeight) { return G.experiment({ metric, tsWeight, N, seed: SEED }); }

const polar1   = run("polar", 1);
const polar2   = run("polar", 2);      // transitions weighted 2× (Freeland–Hurst direction)
const volume1  = run("volume", 1);
const hydro1   = run("hydro", 1);

function report(r, tag) {
  const pct = (r.percentile * 100);
  const oneIn = r.better > 0 ? Math.round(N / r.better) : ">" + N;
  console.log(`    ${tag}: natural=${r.natural.toFixed(4)}  mean=${r.mean.toFixed(4)}  z=${r.zScore.toFixed(2)}  ` +
    `beats ${pct.toFixed(4)}%  (${r.better} of ${N} better; ≈ 1 in ${oneIn})`);
  return { pct, oneIn, better: r.better, z: r.zScore };
}
const RP1 = report(polar1,  "polar,  ts=1");
const RP2 = report(polar2,  "polar,  ts=2");
const RV1 = report(volume1, "volume, ts=1");
const RH1 = report(hydro1,  "hydro,  ts=1");

console.log("\nClaims the page makes about the experiment");
// The headline: under polar requirement, the natural code is in the extreme tail.
ok("natural code is far better than the average random code (polar, ts=1)",
  polar1.zScore < -2.5, `z = ${polar1.zScore.toFixed(2)}`);
ok("under polar requirement, natural code beats > 99.9% of random codes (ts=1)",
  polar1.percentile > 0.999, `${(polar1.percentile * 100).toFixed(4)}%`);
ok("transition weighting (ts=2) makes the code rank even more extreme",
  polar2.better <= polar1.better, `${polar2.better} vs ${polar1.better} better`);
// The honest counterpoint: the result is metric-dependent.
ok("the effect is real but WEAKER under volume than under polar requirement",
  volume1.percentile < polar1.percentile && volume1.zScore > polar1.zScore,
  `volume z=${volume1.zScore.toFixed(2)} vs polar z=${polar1.zScore.toFixed(2)}`);
ok("the natural code is still below-average under all three metrics",
  polar1.zScore < 0 && volume1.zScore < 0 && hydro1.zScore < 0,
  `polar ${polar1.zScore.toFixed(2)}, volume ${volume1.zScore.toFixed(2)}, hydro ${hydro1.zScore.toFixed(2)}`);

// Determinism: the page reproduces these only if the PRNG is deterministic.
console.log("\nDeterminism (page and verifier must get identical figures)");
const again = run("polar", 1);
ok("same seed → identical result", again.better === polar1.better && again.natural === polar1.natural,
  `${again.better} === ${polar1.better}`);

// Sanity: a swap of two well-separated amino acids should change the cost.
const swapped = G.swap(G.NATURAL, "L", "K"); // Leu (hydrophobic) <-> Lys (charged)
const Wc = G.buildW(1);
const cN = G.costOf(G.NATURAL, G.Z.polar, Wc);
const cS = G.costOf(swapped, G.Z.polar, Wc);
ok("perturbing the code (swap Leu↔Lys) raises the polar-requirement cost",
  cS > cN, `${cN.toFixed(4)} → ${cS.toFixed(4)}`);

// ── The numbers the page hard-codes in prose (kept in sync here) ────────────
// If any of these change, update both the page copy AND this block.
// These EXACT counts (deterministic: fixed seed, fixed algorithm) are baked into
// the page's apparatus table. Asserting them here locks the page to the check.
console.log("\nExact figures baked into the page (locked to this check)");
ok("polar  ts=1 → 137 of 1,000,000 better, beats 99.9863%",
  polar1.better === 137 && near(polar1.percentile * 100, 99.9863, 0.0001));
ok("polar  ts=2 →  24 of 1,000,000 better, beats 99.9976%",
  polar2.better === 24 && near(polar2.percentile * 100, 99.9976, 0.0001));
ok("volume ts=1 → 70,031 better, beats 92.997%",
  volume1.better === 70031 && near(volume1.percentile * 100, 92.9969, 0.0001));
ok("hydro  ts=1 → 7,791 better, beats 99.221%",
  hydro1.better === 7791 && near(hydro1.percentile * 100, 99.2209, 0.0001));
ok("natural polar costs: 0.8659 (ts=1), 0.7774 (ts=2)",
  near(polar1.natural, 0.8659, 0.0001) && near(polar2.natural, 0.7774, 0.0001));
console.log(`    (page quotes: polar ts=1 ≈ 1 in ${RP1.oneIn}; polar ts=2 ≈ 1 in ${RP2.oneIn}; ` +
  `volume ts=1 ≈ 1 in ${RV1.oneIn}; hydro ts=1 ≈ 1 in ${RH1.oneIn})`);

// ── tally ──────────────────────────────────────────────────────────────────
console.log(`\n${pass} passed, ${fail} failed\n`);
process.exit(fail ? 1 : 0);
