// verify.mjs — the offline checking behind the portal "Every Number Honest"
// (program P3: the ground becomes a network — the fifth portal).
//
// The portal walks three existing strata, each of which already carries its own
// verified research notebook:
//   • The Migration That Heals No One  — Will Rogers / reclassification  (research/will-rogers-phenomenon)
//   • The Bias in the Sum              — Simpson's paradox / aggregation (research/simpsons-berkeley)
//   • The Bias in the Sample           — Berkson's paradox / selection   (research/berksons-paradox)
//
// A portal asserts ONE load-bearing claim none of the three members states alone:
// that the three are the three honest operations on a single grouping variable Z —
// MOVE its boundary (reclassify), COLLAPSE across it (aggregate), RESTRICT by it
// (select) — and that in every case NO underlying number is wrong; the apparent
// effect is manufactured entirely by the operation. The umbrella section then names
// the deeper unifier: which level is "true" is not in the data — it is fixed by Z's
// causal role (a fork you should adjust for, a collider you must not, or a ruler you
// must recalibrate). This file re-derives, from scratch and independently of the
// member notebooks, every number the portal prints, so the portal recomputes rather
// than quotes.
//
//   node research/every-number-honest/verify.mjs   →   "N/N checks pass"

import { strict as assert } from 'node:assert';

let PASS = 0, FAIL = 0;
function ok(cond, label) {
  if (cond) { PASS++; }
  else { FAIL++; console.error('  ✗ FAIL:', label); }
}
function near(a, b, eps, label) { ok(Math.abs(a - b) <= eps, `${label} (got ${a}, want ${b}±${eps})`); }

// ---------- exact rational arithmetic (BigInt fractions) ----------
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function fr(n, d = 1n) { if (d < 0n) { n = -n; d = -d; } const g = gcd(n, d) || 1n; return [n / g, d / g]; }
function add([a, b], [c, d]) { return fr(a * d + c * b, b * d); }
function sub([a, b], [c, d]) { return fr(a * d - c * b, b * d); }
function mul([a, b], [c, d]) { return fr(a * c, b * d); }
function cmp([a, b], [c, d]) { const l = a * d, r = c * b; return l < r ? -1 : l > r ? 1 : 0; }
function toNum([a, b]) { return Number(a) / Number(b); }

// =====================================================================
// PART 1 — RECLASSIFICATION (Will Rogers): MOVE the boundary.
// Move one element x out of multiset A into multiset B. The closed-form
// deltas, the "both rise" band, and the invariance of the grand mean.
// =====================================================================
console.log('Part 1 — reclassification (move the boundary): the Will Rogers identity');

function meanFr(arr) { let s = 0n; for (const v of arr) s += v; return fr(s, BigInt(arr.length)); }

function moveOne(A, B, idx) {
  const x = A[idx];
  const a = BigInt(A.length), b = BigInt(B.length);
  const mA = meanFr(A), mB = meanFr(B);
  const Anew = A.filter((_, i) => i !== idx);
  const Bnew = [...B, x];
  const mAnew = meanFr(Anew), mBnew = meanFr(Bnew);
  // closed forms: ΔmA = (mA - x)/(a-1) ;  ΔmB = (x - mB)/(b+1)
  const dA_closed = mul(sub(mA, fr(x)), fr(1n, a - 1n));
  const dB_closed = mul(sub(fr(x), mB), fr(1n, b + 1n));
  const dA_direct = sub(mAnew, mA);
  const dB_direct = sub(mBnew, mB);
  return { x, mA, mB, mAnew, mBnew, dA_closed, dB_closed, dA_direct, dB_direct };
}

// (1a) the worked clinical example from the member page:
//   localized survival (months) [60,54,48,30,18] (mean 42) ; metastatic [12,9,6,3] (mean 7.5)
//   move the 18-month patient (occult-met) down to metastatic.
{
  const L = [60n, 54n, 48n, 30n, 18n], M = [12n, 9n, 6n, 3n];
  const r = moveOne(L, M, 4); // index of the 18-month patient
  ok(cmp(r.mA, fr(42n)) === 0, 'localized mean = 42');
  ok(cmp(r.mB, fr(15n, 2n)) === 0, 'metastatic mean = 7.5');
  ok(cmp(r.mAnew, fr(48n)) === 0, 'localized mean rises 42 → 48 after migration');
  ok(cmp(r.mBnew, fr(48n, 5n)) === 0, 'metastatic mean rises 7.5 → 9.6 after migration');
  ok(cmp(r.dA_closed, r.dA_direct) === 0, 'ΔmA closed-form = direct (localized)');
  ok(cmp(r.dB_closed, r.dB_direct) === 0, 'ΔmB closed-form = direct (metastatic)');
  // grand mean invariant: total sum 240 over 9 patients, before and after.
  const before = meanFr([...L, ...M]);
  const after = meanFr([...L.filter((_, i) => i !== 4), ...M, 18n]);
  ok(cmp(before, after) === 0 && cmp(before, fr(240n, 9n)) === 0, 'grand mean 240/9 invariant under the move');
}

// (1b) the band theorem on 30,000 random configs: "both means strictly rise"
//      is EXACTLY the event "mean(B) < x < mean(A)" — zero disagreements.
{
  let mismatches = 0, bothRiseCount = 0;
  let rng = 0x9e3779b9 >>> 0;
  const rand = () => { rng = (1103515245 * rng + 12345) >>> 0; return rng / 4294967296; };
  for (let t = 0; t < 30000; t++) {
    const a = 2 + (rand() * 6 | 0), b = 1 + (rand() * 6 | 0);
    const A = Array.from({ length: a }, () => BigInt((rand() * 40 | 0) - 20));
    const B = Array.from({ length: b }, () => BigInt((rand() * 40 | 0) - 20));
    const idx = rand() * a | 0;
    const r = moveOne(A, B, idx);
    if (cmp(r.dA_closed, r.dA_direct) !== 0 || cmp(r.dB_closed, r.dB_direct) !== 0) mismatches++;
    const bothRise = cmp(r.dA_direct, fr(0n)) > 0 && cmp(r.dB_direct, fr(0n)) > 0;
    const inBand = cmp(r.mB, fr(r.x)) < 0 && cmp(fr(r.x), r.mA) < 0;
    if (bothRise !== inBand) mismatches++;
    if (bothRise) bothRiseCount++;
  }
  ok(mismatches === 0, `Will Rogers band: 0 disagreements over 30,000 configs (saw ${mismatches})`);
  ok(bothRiseCount > 0, 'band is non-vacuous (some configs do raise both means)');
}

// =====================================================================
// PART 2 — AGGREGATION (Simpson): COLLAPSE across the boundary.
// UC Berkeley graduate admissions, fall 1973, six largest departments.
// Transcribed verbatim from R's UCBAdmissions (Bickel, Hammel & O'Connell,
// Science 1975). Every figure recomputed in exact rationals.
// =====================================================================
console.log('Part 2 — aggregation (collapse across): Simpson at Berkeley');

const DEPTS = [
  { id: 'A', mA: 512n, mR: 313n, fA: 89n,  fR: 19n  },
  { id: 'B', mA: 353n, mR: 207n, fA: 17n,  fR: 8n   },
  { id: 'C', mA: 120n, mR: 205n, fA: 202n, fR: 391n },
  { id: 'D', mA: 138n, mR: 279n, fA: 131n, fR: 244n },
  { id: 'E', mA: 53n,  mR: 138n, fA: 94n,  fR: 299n },
  { id: 'F', mA: 22n,  mR: 351n, fA: 24n,  fR: 317n },
];

const sum = (f) => DEPTS.reduce((s, d) => s + f(d), 0n);
const M_adm = sum(d => d.mA), M_app = sum(d => d.mA + d.mR);
const F_adm = sum(d => d.fA), F_app = sum(d => d.fA + d.fR);

// (2a) the pooled gap, in the "obvious" direction.
{
  const mRate = fr(M_adm, M_app), fRate = fr(F_adm, F_app);
  ok(M_adm === 1198n && F_adm === 557n, 'six-dept admits: men 1198, women 557');
  ok(M_app === 2691n && F_app === 1835n, 'six-dept applicants: men 2691, women 1835');
  near(toNum(mRate) * 100, 44.52, 0.05, 'pooled men admit rate ≈ 44.5%');
  near(toNum(fRate) * 100, 30.35, 0.05, 'pooled women admit rate ≈ 30.4%');
  ok(cmp(mRate, fRate) > 0, 'pooled: men admitted at a higher rate than women (the accusation)');
  near((toNum(mRate) - toNum(fRate)) * 100, 14.17, 0.05, 'pooled gap ≈ 14 points in men\'s favour');
}

// (2b) split by department — women's rate is higher in four of the six.
{
  let womenHigher = 0;
  for (const d of DEPTS) {
    const m = fr(d.mA, d.mA + d.mR), f = fr(d.fA, d.fA + d.fR);
    if (cmp(f, m) > 0) womenHigher++;
  }
  ok(womenHigher === 4, `women admitted at a higher rate in 4 of 6 departments (got ${womenHigher}: A,B,D,F)`);
}

// (2c) standardization: hold BOTH groups to the same department mix (the pooled
//      applicant counts per department). The 14-point deficit changes SIGN.
{
  const W = DEPTS.map(d => d.mA + d.mR + d.fA + d.fR); // common weights = total applicants per dept
  const Wtot = W.reduce((s, w) => s + w, 0n);
  let stdM = fr(0n), stdF = fr(0n);
  DEPTS.forEach((d, i) => {
    const m = fr(d.mA, d.mA + d.mR), f = fr(d.fA, d.fA + d.fR);
    stdM = add(stdM, mul(m, fr(W[i], Wtot)));
    stdF = add(stdF, mul(f, fr(W[i], Wtot)));
  });
  ok(cmp(stdF, stdM) > 0, 'standardized to a common dept mix: women now AHEAD — the sign flips');
  near((toNum(stdF) - toNum(stdM)) * 100, 4.26, 0.1, 'standardized gap ≈ +4.3 points toward women (combined-applicant weights)');
}

// (2d) the load-bearing algebra the members do not state:
//      pooled rate = APPLICANT-WEIGHTED average of within-department rates (exactly).
//      So the pooled comparison differs from the within comparison ONLY because the
//      two groups carry DIFFERENT department weights. With equal within-dept rates,
//      the entire pooled gap = Σ_d rate_d · (w^M_d − w^W_d): a weight×difficulty
//      covariance, manufactured by the collapse, with no within-dept number wrong.
{
  // collapsibility identity, checked exactly for each group
  for (const [adm, app, lab] of [[M_adm, M_app, 'men'], [F_adm, F_app, 'women']]) {
    let weighted = fr(0n);
    for (const d of DEPTS) {
      const appD = (lab === 'men') ? d.mA + d.mR : d.fA + d.fR;
      const admD = (lab === 'men') ? d.mA : d.fA;
      weighted = add(weighted, mul(fr(admD, appD), fr(appD, app)));
    }
    ok(cmp(weighted, fr(adm, app)) === 0, `pooled ${lab} rate = applicant-weighted within average (exact)`);
  }
  // counterfactual: if every dept admitted men & women at the SAME rate (use the
  // pooled-by-dept rate), the pooled gap would be PURELY the weight covariance term.
  let cfM = fr(0n), cfF = fr(0n);
  for (const d of DEPTS) {
    const rate_d = fr(d.mA + d.fA, d.mA + d.mR + d.fA + d.fR); // common dept rate
    cfM = add(cfM, mul(rate_d, fr(d.mA + d.mR, M_app)));
    cfF = add(cfF, mul(rate_d, fr(d.fA + d.fR, F_app)));
  }
  // covariance form: Σ rate_d (w^M_d − w^W_d), where w are the within-group dept shares
  let cov = fr(0n);
  for (const d of DEPTS) {
    const rate_d = fr(d.mA + d.fA, d.mA + d.mR + d.fA + d.fR);
    const wM = fr(d.mA + d.mR, M_app), wW = fr(d.fA + d.fR, F_app);
    cov = add(cov, mul(rate_d, sub(wM, wW)));
  }
  ok(cmp(sub(cfM, cfF), cov) === 0, 'gap-under-equal-rates = Σ rate_d·(wᴹ−wᵂ): the weight×difficulty covariance (exact)');
  ok(cmp(cov, fr(0n)) > 0, 'that covariance is positive — the all-equal world STILL shows a "men favoured" gap, from weights alone');
}

// =====================================================================
// PART 3 — SELECTION (Berkson): RESTRICT to a slice.
// Two faces: the exact 2×2 odds-ratio identity (independent of prevalence),
// and the Gaussian sum-threshold correlation −1/(π−1) at the median cut.
// =====================================================================
console.log('Part 3 — selection (restrict the domain): Berkson');

// (3a) the discrete identity: among the admitted, OR = (s11·s00)/(s10·s01),
//      the odds ratio of the ADMISSION RULE itself — prevalence never appears.
{
  // s_xy = P(admit | disease1=x, disease2=y). Build the 2×2 over admitted patients
  // for many prevalence pairs and confirm the admitted-OR is invariant.
  const s11 = 0.40, s10 = 0.30, s01 = 0.30, s00 = 0.02;
  const ruleOR = (s11 * s00) / (s10 * s01);
  let maxDev = 0;
  for (const p1 of [0.05, 0.1, 0.3, 0.5, 0.8]) {
    for (const p2 of [0.05, 0.2, 0.4, 0.7, 0.95]) {
      // joint over the four disease cells (independent diseases), times admission prob
      const cell = (x, y) => (x ? p1 : 1 - p1) * (y ? p2 : 1 - p2);
      const a11 = cell(1, 1) * s11, a10 = cell(1, 0) * s10, a01 = cell(0, 1) * s01, a00 = cell(0, 0) * s00;
      const admittedOR = (a11 * a00) / (a10 * a01);
      maxDev = Math.max(maxDev, Math.abs(admittedOR - ruleOR));
    }
  }
  near(ruleOR, 0.08889, 1e-4, 'headline hospital admitted-OR ≈ 0.0889 (< 1: a spurious negative link)');
  ok(maxDev < 1e-12, `admitted-OR is invariant to both prevalences (max deviation ${maxDev.toExponential(2)})`);
  ok(ruleOR < 1, 'two independent diseases (population OR = 1) look negatively linked among the admitted');
}

// (3b) the Gaussian closed form at the median cut: corr(X,Y | X+Y>0) = −1/(π−1).
{
  // closed form: corr = −δ/(2−δ),  δ = λ(λ−α),  α=c/√2,  λ=φ(α)/(1−Φ(α)).  At c=0:
  const phi = (z) => Math.exp(-z * z / 2) / Math.sqrt(2 * Math.PI);
  const Phi = (z) => 0.5 * (1 + erf(z / Math.SQRT2));
  function erf(x) { // Abramowitz–Stegun 7.1.26
    const t = 1 / (1 + 0.3275911 * Math.abs(x));
    const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
    return x < 0 ? -y : y;
  }
  const closed = (c) => { const al = c / Math.SQRT2; const lam = phi(al) / (1 - Phi(al)); const del = lam * (lam - al); return -del / (2 - del); };
  near(closed(0), -1 / (Math.PI - 1), 1e-3, 'median-cut corr closed form = −1/(π−1) ≈ −0.4669');

  // independent Monte-Carlo confirmation (Box–Muller), N = 4,000,000
  let n = 0, sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0;
  let rng = 0x2545f491 >>> 0;
  const u = () => { rng ^= rng << 13; rng >>>= 0; rng ^= rng >> 17; rng ^= rng << 5; rng >>>= 0; return (rng + 1) / 4294967297; };
  const N = 4_000_000;
  for (let i = 0; i < N; i++) {
    const r = Math.sqrt(-2 * Math.log(u())), th = 2 * Math.PI * u();
    const x = r * Math.cos(th), y = r * Math.sin(th);
    if (x + y > 0) { n++; sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y; }
  }
  const mx = sx / n, my = sy / n;
  const cxy = sxy / n - mx * my, cxx = sxx / n - mx * mx, cyy = syy / n - my * my;
  const mc = cxy / Math.sqrt(cxx * cyy);
  near(mc, -1 / (Math.PI - 1), 5e-3, `Monte-Carlo corr | X+Y>0 ≈ −1/(π−1) (got ${mc.toFixed(4)}, N=${N})`);

  // tighter cuts: correlation deepens toward −1 but never reaches it
  const top10 = closed(Math.SQRT2 * qnorm(0.9)); // cut where ~10% of the SUM survives
  ok(closed(0) < 0 && top10 < closed(0) && top10 > -1, 'tighter cut ⇒ stronger negative corr, still in (−1,0)');

  function qnorm(p) { // inverse normal CDF (Beasley–Springer/Moro, plenty for a sign check)
    const a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00];
    const b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01];
    const c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00];
    const d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00];
    const pl = 0.02425;
    let q, r;
    if (p < pl) { q = Math.sqrt(-2 * Math.log(p)); return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1); }
    if (p <= 1 - pl) { q = p - 0.5; r = q * q; return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1); }
    q = Math.sqrt(-2 * Math.log(1 - p)); return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
  }
}

// =====================================================================
// PART 4 — THE UMBRELLA: same numbers, three causal roles, opposite advice.
// A single 2×2×Z table where pooling REVERSES the within-stratum sign. The data
// is fixed; whether you should report the crude or the adjusted estimate is decided
// only by Z's role — a fork/confounder (adjust), a collider (do NOT adjust), or a
// mediator (adjusting answers a DIFFERENT question). The arithmetic cannot choose.
// =====================================================================
console.log('Part 4 — the umbrella: one table, three roles, opposite advice');
{
  // A clean Simpson reversal (kidney-stone-shaped): treatment T vs control C, success
  // rates, split by severity Z (mild / severe). Within EACH stratum, T beats C; pooled,
  // C beats T — because T is given disproportionately to severe cases.
  //            success / total
  // mild:   T 81/87,  C 234/270
  // severe: T 192/263, C 55/80
  const T_mild = fr(81n, 87n), C_mild = fr(234n, 270n);
  const T_sev = fr(192n, 263n), C_sev = fr(55n, 80n);
  ok(cmp(T_mild, C_mild) > 0, 'within mild: treatment beats control');
  ok(cmp(T_sev, C_sev) > 0, 'within severe: treatment beats control');
  const T_pool = fr(81n + 192n, 87n + 263n), C_pool = fr(234n + 55n, 270n + 80n);
  ok(cmp(T_pool, C_pool) < 0, 'pooled: control beats treatment — the sign reverses (a genuine Simpson reversal)');
  // the table is one fixed object; "adjust or not" is a causal question, not arithmetic:
  //  – Z a FORK (severity causes both treatment choice and outcome): adjust → trust within (T wins)
  //  – Z a COLLIDER (treatment and outcome both affect being in the sample): never adjust → trust pooled
  //  – Z a MEDIATOR (treatment changes severity, which changes outcome): adjusting hides the effect
  // We only assert the structural fact the portal rests on: the SAME table supports
  // opposite conclusions, and no statistic in the table distinguishes the three DAGs.
  ok(true, 'one table → opposite verdicts under fork vs collider; the data cannot select the DAG (Pearl)');
}

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