#!/usr/bin/env node
// verify.mjs — recompute the Berkeley 1973 Simpson's-paradox claims from the
// primary six-department admissions table, exactly (BigInt rationals where the
// verdict depends on it), and assert every figure the page states.
//
//   node research/simpsons-berkeley/verify.mjs
//
// The page (public/strata/the-bias-in-the-sum/index.html) re-runs the same
// arithmetic live in the browser; this is the offline ground truth it must match.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const DATA = JSON.parse(readFileSync(join(here, 'data.json'), 'utf8'));
const D = DATA.depts;

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

let pass = 0, fail = 0;
const ok = (cond, msg) => { (cond ? pass++ : fail++); console.log(`  ${cond ? '✓' : '✗ FAIL'}  ${msg}`); if (!cond) process.exitCode = 1; };

console.log('\nBERKELEY 1973 — SIX LARGEST GRADUATE DEPARTMENTS (Bickel–Hammel–O’Connell 1975)\n');

// ---- per-department rates --------------------------------------------------
const rows = D.map(d => {
  const mApp = d.m_admit + d.m_reject, fApp = d.f_admit + d.f_reject;
  const mRate = fr(BigInt(d.m_admit), BigInt(mApp));
  const fRate = fr(BigInt(d.f_admit), BigInt(fApp));
  return { id: d.id, mApp, fApp, mAdm: d.m_admit, fAdm: d.f_admit, mRate, fRate,
           womenLead: cmp(fRate, mRate) >= 0, womenStrictLead: cmp(fRate, mRate) > 0 };
});

console.log(' dept   men adm/app  rate     women adm/app  rate     who leads');
for (const r of rows) {
  console.log(`   ${r.id}   ${String(r.mAdm).padStart(4)}/${String(r.mApp).padEnd(4)}  ${pct(r.mRate).padStart(7)}   ${String(r.fAdm).padStart(4)}/${String(r.fApp).padEnd(4)}  ${pct(r.fRate).padStart(7)}   ${cmp(r.fRate,r.mRate)>0?'women':cmp(r.fRate,r.mRate)<0?'men':'tie'}`);
}

// ---- aggregate over the six departments ------------------------------------
const mAdmT = D.reduce((s, d) => s + d.m_admit, 0);
const fAdmT = D.reduce((s, d) => s + d.f_admit, 0);
const mAppT = D.reduce((s, d) => s + d.m_admit + d.m_reject, 0);
const fAppT = D.reduce((s, d) => s + d.f_admit + d.f_reject, 0);
const mRateAgg = fr(BigInt(mAdmT), BigInt(mAppT));
const fRateAgg = fr(BigInt(fAdmT), BigInt(fAppT));
const aggGap = sub(fRateAgg, mRateAgg); // women - men

console.log('\nAGGREGATE (six departments pooled, the naive total)');
console.log(`   men   : ${mAdmT}/${mAppT} = ${pct(mRateAgg)}`);
console.log(`   women : ${fAdmT}/${fAppT} = ${pct(fRateAgg)}`);
console.log(`   gap (women - men): ${pct(aggGap)}  — appears to disfavour women`);

ok(mAdmT === 1198 && fAdmT === 557, `admitted totals match UCBAdmissions (men 1198, women 557): ${mAdmT}, ${fAdmT}`);
ok(mAppT === 2691 && fAppT === 1835, `applicant totals match (men 2691, women 1835): ${mAppT}, ${fAppT}`);
ok(Math.abs(num(mRateAgg) - 0.445) < 0.001 && Math.abs(num(fRateAgg) - 0.304) < 0.001, `aggregate rates match R docs (44.5% / 30.4%): ${pct(mRateAgg)} / ${pct(fRateAgg)}`);
ok(cmp(aggGap, [0n, 1n]) < 0, `aggregate gap is negative (looks like bias against women): ${pct(aggGap)}`);

// ---- the reversal: within-department, women lead in most -------------------
const womenLead = rows.filter(r => r.womenStrictLead).map(r => r.id);
const menLead = rows.filter(r => cmp(r.fRate, r.mRate) < 0).map(r => r.id);
console.log('\nDISAGGREGATED');
console.log(`   women's rate strictly higher in: ${womenLead.join(', ')} (${womenLead.length}/6)`);
console.log(`   men's   rate strictly higher in: ${menLead.join(', ')} (${menLead.length}/6)`);
ok(womenLead.length === 4 && womenLead.join('') === 'ABDF', `women lead in exactly 4 of 6 departments (A,B,D,F): ${womenLead.join(',')}`);
ok(menLead.length === 2 && menLead.join('') === 'CE', `men lead in exactly 2 (C,E): ${menLead.join(',')}`);

// ---- the mechanism: women applied to the harder departments ----------------
// rank departments by overall admit rate; show women's share of applicants.
console.log('\nMECHANISM — admit rate vs. share of applicants who are women');
const mech = rows.map(r => {
  const tot = r.mApp + r.fApp;
  const overall = fr(BigInt(r.mAdm + r.fAdm), BigInt(tot));
  const wShare = fr(BigInt(r.fApp), BigInt(tot));
  return { id: r.id, overall, wShare, tot };
}).sort((a, b) => cmp(b.overall, a.overall));
for (const m of mech) console.log(`   ${m.id}  admit ${pct(m.overall).padStart(7)}   women ${pct(m.wShare).padStart(7)} of ${m.tot} applicants`);
// the two easiest departments (A,B) are overwhelmingly male; the harder ones draw the women.
const easiest = mech.slice(0, 2).map(m => m.id);
ok(easiest.includes('A') && easiest.includes('B'), `the two easiest departments are A and B: ${easiest.join(',')}`);
const wShareAB = num(fr(BigInt(rows.find(r=>r.id==='A').fApp + rows.find(r=>r.id==='B').fApp),
                        BigInt(rows.find(r=>r.id==='A').mApp + rows.find(r=>r.id==='A').fApp + rows.find(r=>r.id==='B').mApp + rows.find(r=>r.id==='B').fApp)));
console.log(`   women were ${(wShareAB*100).toFixed(1)}% of applicants to the two easy departments (A+B)`);
ok(wShareAB < 0.13, `women were under 13% of applicants to the two easy departments: ${(wShareAB*100).toFixed(1)}%`);

// Pearson correlation between department admit rate and women's applicant share
const xs = mech.map(m => num(m.overall)), ys = mech.map(m => num(m.wShare));
const mean = a => a.reduce((s, v) => s + v, 0) / a.length;
const mx = mean(xs), my = mean(ys);
let sxy = 0, sxx = 0, syy = 0;
for (let i = 0; i < xs.length; i++) { sxy += (xs[i]-mx)*(ys[i]-my); sxx += (xs[i]-mx)**2; syy += (ys[i]-my)**2; }
const r_corr = sxy / Math.sqrt(sxx * syy);
console.log(`   corr(admit rate, women's share) = ${r_corr.toFixed(3)}  (negative: easy departments drew men, hard ones drew women)`);
ok(r_corr < -0.5, `admit rate and women's applicant share are strongly negatively correlated: r = ${r_corr.toFixed(3)}`);

// ---- the fix (1): direct standardization to the common applicant mix -------
// give both sexes the SAME department mix (each dept weighted by its total
// share of all applicants), then recompute each sex's overall rate.
const grand = rows.reduce((s, r) => s + r.mApp + r.fApp, 0);
let mStd = [0n, 1n], fStd = [0n, 1n];
for (const r of rows) {
  const w = fr(BigInt(r.mApp + r.fApp), BigInt(grand));
  mStd = add(mStd, mul(w, r.mRate));
  fStd = add(fStd, mul(w, r.fRate));
}
const stdGap = sub(fStd, mStd);
console.log('\nFIX (1) — DIRECT STANDARDIZATION (both sexes given the common department mix)');
console.log(`   men   : ${pct(mStd)}`);
console.log(`   women : ${pct(fStd)}`);
console.log(`   gap (women - men): ${pct(stdGap)}  — the sign has flipped`);
ok(cmp(stdGap, [0n, 1n]) > 0, `standardized gap is POSITIVE (now favours women): ${pct(stdGap)}`);
ok(cmp(aggGap, [0n,1n]) < 0 && cmp(stdGap, [0n,1n]) > 0, `SIMPSON REVERSAL: aggregate ${pct(aggGap)} (against women) -> standardized ${pct(stdGap)} (for women)`);

// ---- the fix (2): Mantel-Haenszel common odds ratio (women vs men) ---------
// per stratum 2x2:  a=F_adm b=F_rej / c=M_adm d=M_rej , n=total
let mhNum = [0n, 1n], mhDen = [0n, 1n];
for (const d of D) {
  const a = BigInt(d.f_admit), b = BigInt(d.f_reject), c = BigInt(d.m_admit), e = BigInt(d.m_reject);
  const n = a + b + c + e;
  mhNum = add(mhNum, fr(a * e, n));
  mhDen = add(mhDen, fr(b * c, n));
}
const mhOR = num(mhNum) / num(mhDen);
console.log('\nFIX (2) — MANTEL–HAENSZEL COMMON ODDS RATIO (women relative to men, pooled across departments)');
console.log(`   OR_MH = ${mhOR.toFixed(4)}  (>1: women have slightly higher within-department odds of admission)`);
ok(mhOR > 1 && mhOR < 1.25, `MH common odds ratio modestly favours women (1 < OR < 1.25): ${mhOR.toFixed(4)}`);

// ---- emit the exact figures the page hard-codes ----------------------------
console.log('\nFIGURES THE PAGE MUST MATCH (verbatim):');
const figs = {
  agg_men: pct(mRateAgg), agg_women: pct(fRateAgg), agg_gap: pct(aggGap),
  std_men: pct(mStd), std_women: pct(fStd), std_gap: pct(stdGap),
  mh_or: mhOR.toFixed(3), corr: r_corr.toFixed(3),
  women_lead: womenLead.length, men_lead: menLead.length
};
console.log('   ' + JSON.stringify(figs));

console.log(`\n${fail === 0 ? '✓ ALL CHECKS PASS' : '✗ ' + fail + ' CHECK(S) FAILED'} — ${pass} passed, ${fail} failed\n`);
