// research/what-the-average-throws-away/verify.mjs
// The portal's offline verifier. Three guards:
//   (A) re-derive every number from the members' own formulas, from scratch,
//       then assert data.mjs agrees;
//   (B) re-run the three members' own verifiers — the portal only stands if they pass;
//   (C) drift-guard: the built page must literally carry every number, formula,
//       source token, and member slug.
//   node research/what-the-average-throws-away/verify.mjs
'use strict';
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DATA } from './data.mjs';
import { deltaHat } from '../shakespeare-vocabulary/estimator.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '../..');
const PAGE = join(ROOT, 'public/strata', DATA.META.slug, 'index.html');

let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
function ok(name, cond, got) {
  if (cond) { pass++; console.log('  ok   ' + name + (got !== undefined ? '   ' + got : '')); }
  else { fail++; console.error('  FAIL ' + name + (got !== undefined ? '   got: ' + got : '')); }
}

const T = DATA.movements.tanks, S = DATA.movements.shakespeare, L = DATA.movements.luria;

// =================================================================== (A)
console.log('(A) re-derive every number from the members’ formulas, from scratch');

// -- Tanks: order statistics of a uniform draw without replacement from 1..N.
(() => {
  const N = T.N, k = T.k, m = T.m;
  const mvue = m * (k + 1) / k - 1;
  ok('tanks MVUE = m(k+1)/k − 1 = 258.2', approx(mvue, 258.2, 1e-9) && approx(T.mvue, 258.2, 1e-9), mvue);
  ok('tanks MVUE identity m+(m−k)/k == m(k+1)/k−1', approx(m + (m - k) / k, m * (k + 1) / k - 1, 1e-12));
  const eMax = k * (N + 1) / (k + 1);
  ok('tanks E[max] = k(N+1)/(k+1) = 254.06', approx(eMax, 254.0625, 1e-9) && approx(T.eMax, 254.06, 0.01), eMax);
  const mleBias = -(N - k) / (k + 1);
  ok('tanks MLE bias = −(N−k)/(k+1) = −15.94', approx(mleBias, -15.9375, 1e-9) && approx(T.mleBias, -15.94, 0.01), mleBias);
  const varMvue = (N - k) * (N + 1) / (k * (k + 2));
  const varTwice = (N + 1) * (N - k) / (3 * k);
  ok('tanks Var(MVUE) = 271, SD ≈ 16.46', approx(varMvue, 271, 1e-6) && approx(T.sdMvue, Math.sqrt(varMvue), 0.02), Math.sqrt(varMvue).toFixed(2));
  ok('tanks Var(2·mean−1) SD ≈ 39.19', approx(T.sdTwiceMean, Math.sqrt(varTwice), 0.02), Math.sqrt(varTwice).toFixed(2));
  const eff = (k + 2) / 3;
  ok('tanks efficiency (k+2)/3 = 5.667 (free of N)', approx(eff, 5.6667, 1e-3) && approx(T.efficiency, eff, 1e-3), eff.toFixed(4));
  // efficiency really is free of N:
  const effAtOtherN = varTwiceFor(5000) / varMvueFor(5000);
  function varMvueFor(NN){ return (NN - k) * (NN + 1) / (k * (k + 2)); }
  function varTwiceFor(NN){ return (NN + 1) * (NN - k) / (3 * k); }
  ok('tanks efficiency identical at N=5000', approx(effAtOtherN, eff, 1e-6), effAtOtherN.toFixed(4));
  const postMean = (m - 1) * (k - 1) / (k - 2);
  ok('tanks Bayesian posterior mean (m−1)(k−1)/(k−2) = 260.6', approx(postMean, 260.615, 1e-3) && approx(T.postMean, 260.6, 0.1), postMean.toFixed(2));
})();

// -- Shakespeare: Euler-accelerated Delta_hat(1) on the E&T spectrum.
(() => {
  const eul = deltaHat(S.etSpectrum, 1, 30);
  ok('shakespeare Δ̂(1) via Euler = 11434.5 (published 11430)', approx(eul, 11434.5, 0.5), eul.toFixed(2));
  ok('shakespeare data.mjs etReproduced matches', approx(S.etReproduced, eul, 0.5), S.etReproduced);
  ok('shakespeare within 0.05% of published 11,430', Math.abs(eul - S.etPublished) / S.etPublished < 0.0006, ((eul - S.etPublished) / S.etPublished * 100).toFixed(3) + '%');
  // On the truncated 12-term published spectrum Δ̂(2) already runs away upward
  // (18,263 vs 11,434, and climbing with each term); the member's full-spectrum
  // verifier shows the true blow-up to 661,406. Either way the method is past its
  // honest horizon at t=2 — the instrument flags t>1.3.
  const div = deltaHat(S.etSpectrum, 2, S.etSpectrum.length);
  ok('shakespeare Δ̂(2) runs away above Δ̂(1) — past the honest horizon', div > 1.4 * eul, div.toFixed(0));
  ok('shakespeare hapax ≈ 38% of vocabulary', approx(S.etN1 / S.etV, 0.456, 0.02) || approx(S.oursN1 / S.oursV, 0.38, 0.01), (S.oursN1 / S.oursV * 100).toFixed(1) + '%');
  ok('shakespeare our tokeniser gives a DIFFERENT count (same method)', S.oursDelta1 !== S.etPublished && S.oursDelta1 === 7643, S.oursDelta1);
})();

// -- Luria–Delbrück: p0 = e^-m; the compound-Poisson variance signature.
(() => {
  const p0 = Math.exp(-L.m);
  ok('luria p₀ = e^(−m), m=2 → 0.1353', approx(p0, 0.13533528, 1e-6) && approx(L.p0, 0.1353, 1e-4), p0.toFixed(4));
  ok('luria estimator m = −ln(p₀) recovers m', approx(-Math.log(p0), L.m, 1e-9) && approx(L.mFromP0, L.m, 1e-3), (-Math.log(p0)).toFixed(3));
  // clone-size law P(k)=1/(k(k+1)) telescopes to 1
  let s = 0; for (let k = 1; k <= 200000; k++) s += 1 / (k * (k + 1));
  ok('luria clone-size law Σ1/(k(k+1)) → 1', approx(s, 1, 1e-4), s.toFixed(6));
  // a small seeded compound-Poisson sim reproduces the qualitative split
  function rng(seed){ let x = seed >>> 0; return () => { x = (x * 1664525 + 1013904223) >>> 0; return x / 4294967296; }; }
  function pois(rand, lam){ const Lp = Math.exp(-lam); let k = 0, p = 1; do { k++; p *= rand(); } while (p > Lp); return k - 1; }
  function clone(rand){ let u = rand(); if (u >= 0.999999) u = 0.999999; return Math.max(1, Math.ceil(u / (1 - u))); }
  const rand = rng(99); const m = 2, cul = 4000; const indu = [], spon = [];
  for (let c = 0; c < cul; c++) { indu.push(pois(rand, m)); let nm = pois(rand, m), tot = 0; for (let j = 0; j < nm; j++) tot += clone(rand); spon.push(tot); }
  const vm = (a) => { const mean = a.reduce((x, y) => x + y, 0) / a.length; const v = a.reduce((x, y) => x + (y - mean) ** 2, 0) / a.length; return v / mean; };
  const vmI = vm(indu), vmS = vm(spon);
  ok('luria INDUCED var/mean ≈ 1 (Poisson)', vmI > 0.7 && vmI < 1.4, vmI.toFixed(2));
  ok('luria SPONTANEOUS var/mean ≫ 1 (jackpots)', vmS > 20, Math.round(vmS));
  ok('luria fluctuation test: spontaneous ≥ 20× induced', vmS / vmI >= 20, (vmS / vmI).toFixed(0) + '×');
})();

// -- The reading: three distinct edges, three distinct kinds of unknown.
ok('the synthesis has 3 rows, edges max/singletons/variance',
  DATA.synthesis.length === 3 &&
  /MAXIMUM/.test(DATA.synthesis[0].edge) &&
  /SINGLETONS/.test(DATA.synthesis[1].edge) &&
  /VARIANCE/.test(DATA.synthesis[2].edge));
ok('the three hidden kinds are count / richness / rate',
  /COUNT/.test(DATA.synthesis[0].hidden) && /RICHNESS/.test(DATA.synthesis[1].hidden) && /RATE/.test(DATA.synthesis[2].hidden));

// =================================================================== (B)
console.log('(B) the three members’ own verifiers still pass');
const members = [
  ['the-tanks-that-counted-themselves', 'research/the-tanks-that-counted-themselves/verify.mjs'],
  ['how-many-words-did-shakespeare-know', 'research/shakespeare-vocabulary/verify.mjs'],
  ['luria-delbruck', 'research/luria-delbruck/verify.mjs'],
];
for (const [name, rel] of members) {
  let good = true, out = '';
  try { out = execFileSync('node', [join(ROOT, rel)], { cwd: ROOT, stdio: 'pipe', encoding: 'utf8' }); }
  catch (e) { good = false; out = (e.stdout || '') + (e.stderr || ''); }
  ok('member verifier passes: ' + name, good);
}

// =================================================================== (C)
console.log('(C) the built page carries the exact numbers, formulas, sources');
let html = '';
try { html = readFileSync(PAGE, 'utf8'); } catch { /* stays empty */ }
ok('built page exists', html.length > 5000, html.length + ' bytes');
const need = [
  // tanks
  'N̂ = m + (m−k)/k = m(k+1)/k − 1', String(T.efficiency) + '×', 'true production N', 'average gap',
  // shakespeare
  'new-words(t) = n₁t − n₂t² + n₃t³ − …', S.etPublished.toLocaleString(), 'hapax', 'Efron', 'Thisted',
  // luria
  'P(size = k) = 1 / (k(k+1))', 'p_n ∼ m / n²', 'm = −ln(p₀)', 'Luria', 'fluctuation test',
  // the reading + chrome
  'What the Average Throws Away', 'a hidden count', 'a hidden richness', 'a hidden rate',
  'home-banner.js', 'https://artwaste.land/strata/' + DATA.META.slug + '/', DATA.META.date,
  // members present as links
  '/strata/the-tanks-that-counted-themselves/', '/strata/how-many-words-did-shakespeare-know/', '/strata/luria-delbruck/',
  // disclosed overlaps
  'The Signal Never Sent', 'The Man Lightning Kept Finding',
];
for (const s of need) ok('page carries: ' + JSON.stringify(s.length > 40 ? s.slice(0, 40) + '…' : s), html.includes(s));
const m = html.match(/<script id="portal-data" type="application\/json">([\s\S]*?)<\/script>/);
ok('portal-data JSON present + parses', !!m && (() => { try { JSON.parse(m[1].replace(/\\u003c/g, '<')); return true; } catch { return false; } })());

// =================================================================== report
const total = pass + fail;
console.log('\n' + (fail === 0 ? '✓' : '✗') + ' ' + pass + '/' + total + ' checks pass');
if (fail > 0) { console.error(fail + ' FAILED'); process.exit(1); }
