// verify.mjs — the check behind the combine portal
// "Nothing Was Spacing Them Out" (/strata/nothing-was-spacing-them-out/).
//
// 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 each of the four headline numbers FROM SCRATCH here, so the
//       page and this file share one source of truth;
//   (B) re-runs all four member verifiers and confirms they still exit clean,
//       so the chips the portal lifts have not drifted under it.
//
// The four faces of the clustering illusion, and their headline numbers:
//   I.  COIN  (the-coin-you-cant-fake)      — P(longest run >= 6 in 100 fair flips) = 80.68%
//   II. V-1   (the-squares-that-werent-aimed)— Poisson empty squares = 576*e^(-537/576) = 226.74
//   III.ARCSINE(ahead-the-whole-game)        — lead-fraction density 1/(pi*sqrt(x(1-x))), min at 1/2
//   IV. LIGHTNING(the-man-lightning-kept-finding)— Poisson at m=7: P(>=7) ~ coin flip; survival 0.9^7 ~ 48%
//
// run:  node research/nothing-was-spacing-them-out/verify.mjs
// No dependencies. Deterministic.

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);

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. the four headline numbers, re-derived from scratch ──\n");

// ── I. COIN: exact distribution of the longest run in n fair flips ──
// dp[j] = P(current run has length j and no run has yet exceeded m), symbol-agnostic.
// Each flip extends the run (prob 1/2) or switches and restarts at length 1 (prob 1/2).
// sum(dp) after n flips = P(longest run <= m).
function pLongestLE(n, m) {
  let dp = new Array(m + 1).fill(0);
  dp[1] = 1;
  for (let i = 2; i <= n; i++) {
    const nd = new Array(m + 1).fill(0);
    let sw = 0;
    for (let j = 1; j <= m; j++) sw += dp[j];
    nd[1] = 0.5 * sw;
    for (let j = 1; j < m; j++) nd[j + 1] += 0.5 * dp[j];
    dp = nd;
  }
  return dp.reduce((a, b) => a + b, 0);
}
const pGE6 = 1 - pLongestLE(100, 5);
const pLE3 = pLongestLE(100, 3);
ok("I.  coin: P(longest run >= 6 in 100 flips) = 80.68%", approx(pGE6, 0.8068, 5e-4), `got ${(pGE6 * 100).toFixed(2)}%`);
ok("I.  coin: P(longest run <= 3 in 100 flips) = 0.03%", approx(pLE3, 0.0003, 3e-4), `got ${(pLE3 * 100).toFixed(2)}%`);

// independent cross-check: exact mean of the longest run from its PMF should be ~6.977
let meanL = 0;
for (let m = 1; m <= 100; m++) {
  const pmf = pLongestLE(100, m) - pLongestLE(100, m - 1); // P(longest == m); pLongestLE(.,0)=0
  meanL += m * pmf;
}
ok("I.  coin: exact mean longest run ~ 6.977", approx(meanL, 6.977, 0.01), `got ${meanL.toFixed(3)}`);

// ── II. V-1: Poisson empty-square expectation ──
const NB = 537, NSQ = 576;
const lambda = NB / NSQ;
const emptyExp = NSQ * Math.exp(-lambda);
ok("II. V-1: lambda = 537/576 = 0.9323", approx(lambda, 0.9323, 5e-5), `got ${lambda.toFixed(4)}`);
ok("II. V-1: 576*e^(-lambda) empty squares = 226.74", approx(emptyExp, 226.74, 0.05), `got ${emptyExp.toFixed(2)} (Feller 226.74, observed 229)`);
// full Feller fit row, to the second decimal, as the portal's table shows
const feller = [0, 1, 2, 3, 4].map(k => NSQ * Math.exp(-lambda) * Math.pow(lambda, k) / factorial(k));
const fellerExpect = [226.74, 211.39, 98.54, 30.62, 7.14];
let rowOk = feller.every((v, i) => approx(v, fellerExpect[i], 0.02));
ok("II. V-1: full Poisson row matches Feller [226.74,211.39,98.54,30.62,7.14]", rowOk,
  feller.map(v => v.toFixed(2)).join(", "));

// ── III. ARCSINE: lead-fraction density and CDF ──
const dens = x => 1 / (Math.PI * Math.sqrt(x * (1 - x)));
ok("III. arcsine: density is LOWEST at x = 1/2 (the least likely outcome)",
  dens(0.5) < dens(0.05) && dens(0.5) < dens(0.95),
  `dens(1/2)=${dens(0.5).toFixed(3)} < dens(0.05)=${dens(0.05).toFixed(3)}`);
const cdfHalf = (2 / Math.PI) * Math.asin(Math.sqrt(0.5));
ok("III. arcsine: CDF(1/2) = (2/pi)*arcsin(sqrt(1/2)) = 1/2 (symmetry)", approx(cdfHalf, 0.5, 1e-12), `got ${cdfHalf}`);
// the density integrates to 1 over (0,1): numeric check (avoid the integrable endpoints)
let area = 0; const STEPS = 2_000_00;
for (let i = 1; i < STEPS; i++) { const x = i / STEPS; area += dens(x) / STEPS; }
ok("III. arcsine: density integrates to ~1 over (0,1)", approx(area, 1, 0.02), `got ${area.toFixed(3)}`);
// direct discrete enumeration on a small game: fraction-of-time-positive is U-shaped.
// Enumerate all 2^(2m) paths for m=6 (2N=12 steps); the extreme lead-counts must
// beat the middle. Uses the "positive segment" count (segment i positive if S_{i-1}+S_i>0).
{
  const twoN = 12, counts = new Array(twoN + 1).fill(0);
  for (let mask = 0; mask < (1 << twoN); mask++) {
    let prev = 0, s = 0, pos = 0;
    for (let i = 0; i < twoN; i++) { s = prev + ((mask >> i) & 1 ? 1 : -1); if (prev + s > 0) pos++; prev = s; }
    counts[pos]++;
  }
  const mid = counts[twoN / 2];
  const edge = Math.min(counts[0], counts[twoN]);
  ok("III. arcsine: enumerated 4096 paths — edge lead-counts exceed the middle (U shape)",
    edge > mid, `edge=${edge} > middle=${mid}`);
}

// ── IV. LIGHTNING: Poisson strike model and survival ──
function factorial(k) { let f = 1; for (let i = 2; i <= k; i++) f *= i; return f; }
function poissonPMF(m, k) { return Math.exp(-m) * Math.pow(m, k) / factorial(k); }
const m = 7; // lambda=7/35 per year over 35 years => expected 7 strikes
let pStrikeGE7 = 1; for (let k = 0; k <= 6; k++) pStrikeGE7 -= poissonPMF(m, k);
pStrikeGE7 = Math.max(0, pStrikeGE7);
ok("IV. lightning: lambda=7/35 over 35yr => m=7", approx((7 / 35) * 35, 7, 1e-12), `m=${(7 / 35) * 35}`);
ok("IV. lightning: Poisson P(>=7 | m=7) is about a coin flip (44-56%)", pStrikeGE7 > 0.44 && pStrikeGE7 < 0.56, `got ${(pStrikeGE7 * 100).toFixed(1)}%`);
const pGE1 = 1 - poissonPMF(m, 0);
ok("IV. lightning: P(at least one strike | m=7) is a near-certainty", pGE1 > 0.999, `got ${(pGE1 * 100).toFixed(3)}%`);
const survive = Math.pow(0.9, 7);
ok("IV. lightning: survival 0.9^7 ~ 48%", approx(survive, 0.478, 0.01), `got ${(survive * 100).toFixed(1)}%`);
// the fallacy figure: multiplying an average annual strike risk (~1/1.22M in a given
// year, a commonly quoted US figure) seven times gives an astronomically small number,
// which is exactly the wrong model the record's "4.15 in 10^32" repeats.
const pYear = 1 / 1_220_000;
const naive = Math.pow(pYear, 7);
ok("IV. lightning: the naive independence-multiplication gives an absurd ~1e-42 (the wrong model)",
  naive < 1e-40, `p_year^7 = ${naive.toExponential(2)}`);

console.log("\n── B. re-run all four member verifiers (chips must not have drifted) ──\n");

const members = [
  ["the-coin-you-cant-fake", "verify.mjs"],
  ["the-squares-that-werent-aimed", "verify.mjs"],
  ["arcsine-law", "verify.mjs"],                 // the ahead-the-whole-game layer's research dir
  ["the-man-lightning-kept-finding", "verify.mjs"],
];
for (const [dir, file] of members) {
  const p = join(RESEARCH, dir, file);
  if (!existsSync(p)) { ok(`member verifier present: ${dir}/${file}`, false, "MISSING"); continue; }
  let clean = true, tail = "";
  try {
    const outp = execFileSync("node", [p], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
    tail = outp.trim().split("\n").slice(-1)[0].slice(0, 72);
  } catch (e) {
    clean = false; tail = String(e.message || e).slice(0, 72);
  }
  ok(`member verifier re-runs clean: ${dir}`, clean, tail);
}

console.log("\n" + "─".repeat(60));
console.log(`  ${pass}/${pass + fail} checks passed  —  ${fail === 0 ? "all green" : "SEE FAILURES ABOVE"}`);
console.log("─".repeat(60) + "\n");
process.exit(fail === 0 ? 0 : 1);
