// verify.mjs — the check behind the combine portal
// "The Auditor That Wants Nothing" (/strata/the-auditor-that-wants-nothing/).
//
// PORTAL LAW. A combine adds no new fact. Every number the portal displays is
// verbatim from a member layer's own byte-checked verifier. This script does two
// jobs:
//   (A) re-derives from scratch every headline number the page shows, so the page
//       and this file share one source of truth and can never silently drift;
//   (B) re-runs each member's own verifier and confirms it exits clean, so the
//       chips the portal lifts still hold under it.
//
// THE SPINE. A claim is trusted here not because it is argued well but because a
// CHECK stands behind it that would turn red if it were false. But not all reds
// are equal. A red's authority scales with how LITTLE the checker shares with the
// mind that wants the claim true. The portal ranks four members up that axis:
//   Rung 0 — the-cold-read            : another mind LIKE yours (max shared priors) — weakest
//   Rung 1 — the-trip-that-flips-the-fear : arithmetic on shared data (shares your math, not your answer)
//   Rung 2 — the-coin-you-cant-fake   : a probability law with no stake in your story
//   Rung 3 — check-digits             : a mindless guard, machine-checked for ALL cases — no mind at all
//
// The one rung with NO recomputable number is Rung 0 — and that is the point:
// a mind's reading cannot be re-derived, which is exactly why it is the weakest.
//
// run:  node research/the-auditor-that-wants-nothing/verify.mjs
// No dependencies. Deterministic. Part B runs the member scripts (a few seconds).

import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));
const RESEARCH = dirname(HERE);
const ROOT = dirname(RESEARCH);

let pass = 0, fail = 0;
const ok = (name, cond, extra = "") => {
  if (cond) pass++; else fail++;
  console.log(`${cond ? "  ok  " : "FAIL  "}${name}${extra ? "   " + extra : ""}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ============================================================================
console.log("\n── A. every headline number the portal shows, re-derived from scratch ──\n");
// ============================================================================

// ── RUNG 1 · the-trip-that-flips-the-fear — arithmetic forced by raw counts ──
// NHTSA FARS 2023: 40,901 road deaths; FHWA VMT 3,247 billion vehicle-miles.
{
  const DEATHS = 40901, VMT_B = 3247;                 // billions of vehicle-miles
  const ratePer100M = DEATHS / (VMT_B * 10);          // = DEATHS / (VMT_B*1e9) * 1e8
  const milesPerMicromort = (VMT_B * 1e3) / DEATHS;   // = VMT_miles / DEATHS / 1e6
  ok("R1. road rate = 1.26 deaths per 100M VMT (published headline)",
     approx(ratePer100M, 1.26, 0.005), `got ${ratePer100M.toFixed(3)}`);
  ok("R1. ~79 miles per micromort at the 2023 all-road rate",
     approx(milesPerMicromort, 79.4, 0.1), `got ${milesPerMicromort.toFixed(2)}`);
  // the folk "240 miles per micromort" is a DIFFERENT, kinder number
  const FOLK = 240;
  const folkRate = 1e8 / (FOLK * 1e6);                // implied deaths-per-100M
  ok("R1. folk '240 mi/micromort' implies only 0.42 per 100M (~1/3 the real rate)",
     approx(folkRate, 0.4167, 0.001), `got ${folkRate.toFixed(4)}`);
  ok("R1. the folk figure is ~3x kinder than the recomputed one",
     approx(FOLK / milesPerMicromort, 3.0, 0.1), `got ${(FOLK / milesPerMicromort).toFixed(2)}x`);
  // per-passenger-mile: car 0.53 vs air 0.003 per 100M pax-mi
  const safety = 0.53 / 0.003;
  ok("R1. flying ~177x safer per passenger-mile (0.53 / 0.003)",
     approx(safety, 176.67, 0.1), `got ${safety.toFixed(1)}x`);
}

// ── RUNG 2 · the-coin-you-cant-fake — a law with no stake in your story ──
// Exact DP for the longest run in n fair flips. dp[j] = P(current run length j,
// no run has exceeded m). After n flips, sum(dp) = P(longest run <= m).
function pLongestRunAtMost(n, m) {
  let dp = new Array(m + 1).fill(0);
  dp[1] = 1;                                   // first flip: a run of length 1
  for (let i = 2; i <= n; i++) {
    const nd = new Array(m + 1).fill(0);
    let switchMass = 0;
    for (let j = 1; j <= m; j++) switchMass += dp[j];
    nd[1] = 0.5 * switchMass;                  // switch symbol -> new run of 1
    for (let j = 1; j < m; j++) nd[j + 1] = 0.5 * dp[j]; // extend the run
    dp = nd;
  }
  return dp.reduce((a, b) => a + b, 0);
}
{
  const pGE6 = 1 - pLongestRunAtMost(100, 5);  // P(longest streak >= 6) in 100 fair flips
  ok("R2. a real 100-flip sequence throws a streak of >=6 about 80% of the time",
     approx(pGE6, 0.80, 0.02), `got ${(pGE6 * 100).toFixed(1)}%`);
  // Wald-Wolfowitz: expected number of runs at n1=n2=50 is 51 (switches ~ 50%).
  const n1 = 50, n2 = 50, n = 100;
  const ER = 1 + (2 * n1 * n2) / n;
  ok("R2. a fair 100-flip coin averages 51 runs (~50% switches) — the machine baseline a fake misses",
     approx(ER, 51, 1e-9), `got ${ER}`);
}

// ── RUNG 3 · check-digits — a mindless guard, and its ONE blind spot ──
// Luhn weights alternate 1,2 from the right. A weight-1 digit contributes x; a
// weight-2 digit contributes s(x) = x<5 ? 2x : 2x-9. Single-error detection asks:
// does every digit give a distinct contribution mod 10? Adjacent-swap detection
// asks: for g(x) = (s(x)-x) mod 10, are all g(x) distinct?
{
  const s = (x) => (x < 5 ? 2 * x : 2 * x - 9);
  const contribW1 = [...Array(10)].map((_, x) => x % 10);
  const contribW2 = [...Array(10)].map((_, x) => s(x) % 10);
  const distinct = (a) => new Set(a).size === 10;
  ok("R3. Luhn catches EVERY single-digit error (both weights are bijections mod 10)",
     distinct(contribW1) && distinct(contribW2));
  // adjacent transposition blind pairs: {a,b} with a + s(b) == b + s(a) (mod 10)
  const g = [...Array(10)].map((_, x) => (((s(x) - x) % 10) + 10) % 10);
  const blind = [];
  for (let a = 0; a < 10; a++) for (let b = a + 1; b < 10; b++)
    if (g[a] === g[b]) blind.push(`${a}${b}`);
  ok("R3. Luhn's ONLY adjacent-transposition blind spot is 0<->9",
     blind.length === 1 && blind[0] === "09", `got {${blind.join(",") || "none"}}`);
  // Verhoeff/Damm close even this one (member's Lean-checked claim); we only assert
  // here that a non-commutative structure is REQUIRED — mod-10 arithmetic commutes,
  // so it cannot separate 0<->9, which is why the guarantee needs a group/quasigroup.
  ok("R3. mod-10 arithmetic commutes, so it cannot separate 0<->9 (why a group is needed)",
     (0 + s(9)) % 10 === (9 + s(0)) % 10);
}

// ── RUNG 0 · the-cold-read — the rung with NO recomputable number ──
// A peer's reading is prior-dependent: it cannot be re-derived from the world.
// That is not a gap in this verifier; it is the whole reason Rung 0 sits lowest.
console.log("\n  --  R0. the-cold-read carries no headline number to re-derive:");
console.log("        a mind's verdict is not forced by the world, so it cannot be");
console.log("        recomputed — which is exactly why it is the weakest rung. --");

// ============================================================================
console.log("\n── B. re-run each member's own verifier; confirm it exits clean ──\n");
// ============================================================================
const members = [
  ["the-trip-that-flips-the-fear",
   "research/the-trip-that-flips-the-fear/verify-the-trip-that-flips-the-fear.mjs"],
  ["the-coin-you-cant-fake", "research/the-coin-you-cant-fake/verify.mjs"],
  ["check-digits", "research/check-digits/verify.mjs"],
];
for (const [name, rel] of members) {
  const abs = join(ROOT, rel);
  if (!existsSync(abs)) { ok(`B. ${name}: verifier present`, false, rel); continue; }
  try {
    execFileSync("node", [abs], { stdio: "pipe", timeout: 120000 });
    ok(`B. ${name}: own verifier re-runs clean (exit 0)`, true);
  } catch (e) {
    ok(`B. ${name}: own verifier re-runs clean (exit 0)`, false, String(e.status ?? e.message));
  }
}
// the-cold-read is a measurement program (P20), not a numeric verifier: assert only
// that the member stratum exists on the ground.
ok("B. the-cold-read: member stratum present (a measurement, no numeric verifier)",
   existsSync(join(ROOT, "src/content/strata/the-cold-read.md")));

// ============================================================================
console.log(`\n${fail === 0 ? "ALL CHECKS PASSED" : fail + " CHECK(S) FAILED"}  (${pass} ok, ${fail} fail)\n`);
process.exit(fail === 0 ? 0 : 1);
