#!/usr/bin/env node
// verify-did-not-state-his-reasons.mjs
//
// Re-derives every load-bearing number on /strata/did-not-state-his-reasons/
// from the committed case records, by a path that does not import a single line
// of analyse.mjs, and checks that the page and the stratum's dek actually print
// what came out. If the analysis and the verifier disagree, one of them is
// wrong and this exits 1.
//
//   node verify-did-not-state-his-reasons.mjs
//   node verify-did-not-state-his-reasons.mjs --verbose
//
// The source of truth is research/the-vote-you-were-allowed-to-see/data/
// cases-min.jsonl.gz — 329,995 records, one per case in the United States
// Reports, distilled from the Caselaw Access Project's static mirror. The
// verifier reimplements the definitions from the page's own prose rather than
// importing them, which is the whole point: if someone edits a predicate in
// analyse.mjs, this file keeps computing what the page claims and the numbers
// part company.

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

const ROOT = dirname(fileURLToPath(import.meta.url));
const RES = join(ROOT, 'research', 'the-vote-you-were-allowed-to-see');
const DATA = join(RES, 'data');
const PAGE = join(ROOT, 'public', 'strata', 'did-not-state-his-reasons', 'index.html');
const MD = join(ROOT, 'src', 'content', 'strata', 'did-not-state-his-reasons.md');
const VERBOSE = process.argv.includes('--verbose');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const eq = (name, got, want) => ok(name, got === want, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (name, got, want, tol) => ok(name, Math.abs(got - want) <= tol, `got ${got}, want ${want} ±${tol}`);

// ---------------------------------------------------------------------------
console.log('verify-did-not-state-his-reasons — the United States Reports, recounted\n');

for (const p of [join(DATA, 'cases-min.jsonl.gz'), join(DATA, 'findings.json'), join(DATA, 'typing-audit.json'), PAGE, MD]) {
  if (!existsSync(p)) { console.log(`  FAIL missing artifact: ${p}`); process.exit(1); }
}

const rows = gunzipSync(readFileSync(join(DATA, 'cases-min.jsonl.gz')))
  .toString('utf8').split('\n').filter(Boolean).map(JSON.parse);
const F = JSON.parse(readFileSync(join(DATA, 'findings.json'), 'utf8'));
const AUDIT = JSON.parse(readFileSync(join(DATA, 'typing-audit.json'), 'utf8'));
const html = readFileSync(PAGE, 'utf8');
const md = readFileSync(MD, 'utf8');

// --- the definitions, restated from the page's own prose ---------------------
// "a case counts as decided if its lead opinion carries an author line and the
//  case runs to at least 400 words"
// "separate opinion means an opinion after the first typed dissent,
//  concurrence, concurrence-in-part, or plurality"
const SEP = ['dissent', 'concurrence', 'concurring-in-part-and-dissenting-in-part', 'plurality'];
const recusal = s => /no par[it]\b/i.test(s) || /did not partic/i.test(s) || /no part in the consid/i.test(s);
const isCourt = r => r.court === 'Supreme Court of the United States';
const signed = r => r.ops.length > 0 && r.ops[0].author.length > 0 && !recusal(r.ops[0].author);
const yearOf = r => Number(String(r.date).slice(0, 4));
const isDecided = r => isCourt(r) && signed(r) && r.words >= 400 && Number.isFinite(yearOf(r)) && yearOf(r) > 0;
const separates = r => r.ops.filter((o, i) => i > 0 && SEP.indexOf(o.type) >= 0);

// --- 1. the universe --------------------------------------------------------
console.log('1. the universe');
eq('cases in the reporter', rows.length, F.corpus.casesInReporter);
eq('Supreme Court entries', rows.filter(isCourt).length, F.corpus.scotusCases);
eq('cases decided by other courts', rows.length - rows.filter(isCourt).length, F.corpus.nonScotusCasesInReporter);
const decided = rows.filter(isDecided);
eq('decided cases', decided.length, F.corpus.decidedCases);
eq('decided cases carrying a separate opinion', decided.filter(r => separates(r).length > 0).length, F.corpus.withSeparate);
eq('separate opinions in total', decided.reduce((a, r) => a + separates(r).length, 0), F.corpus.separateOpinions);
eq('first year', Math.min(...decided.map(yearOf)), F.corpus.firstYear);
eq('last year', Math.max(...decided.map(yearOf)), F.corpus.lastYear);
ok('the reporter really does carry other courts',
  new Set(rows.map(r => r.court)).size > 5,
  `${new Set(rows.map(r => r.court)).size} distinct courts appear in the us reporter`);

// --- 2. the decade series ---------------------------------------------------
console.log('\n2. the decade series');
const byDecade = new Map();
for (const r of decided) {
  const d = Math.floor(yearOf(r) / 10) * 10;
  const e = byDecade.get(d) || { n: 0, s: 0 };
  e.n++; if (separates(r).length) e.s++;
  byDecade.set(d, e);
}
eq('decades covered', byDecade.size, F.decades.length);
let decadeMismatch = 0;
for (const d of F.decades) {
  const mine = byDecade.get(d.decade);
  if (!mine || mine.n !== d.n || mine.s !== d.withSeparate) decadeMismatch++;
}
eq('every decade row agrees with findings.json', decadeMismatch, 0);
const dpct = y => { const e = byDecade.get(y); return 100 * e.s / e.n; };
near('1930s rate', +dpct(1930).toFixed(1), 11.7, 0.05);
near('1940s rate', +dpct(1940).toFixed(1), 40.8, 0.05);
near('1950s rate', +dpct(1950).toFixed(1), 59.7, 0.05);
ok('the 1940s rate is more than triple the 1930s rate', dpct(1940) > 3 * dpct(1930),
  `${dpct(1930).toFixed(1)}% -> ${dpct(1940).toFixed(1)}%`);
ok('no decade before 1940 exceeds 15%',
  [...byDecade].filter(([d]) => d < 1940).every(([, e]) => 100 * e.s / e.n < 15));
ok('no decade from 1950 on falls below 50%',
  [...byDecade].filter(([d]) => d >= 1950).every(([, e]) => 100 * e.s / e.n >= 50));

// --- 3. the two crossings ---------------------------------------------------
console.log('\n3. the two crossings');
const byYear = new Map();
for (const r of decided) {
  const y = yearOf(r);
  const e = byYear.get(y) || { n: 0, s: 0 };
  e.n++; if (separates(r).length) e.s++;
  byYear.set(y, e);
}
const solid = [...byYear.entries()].filter(([, e]) => e.n >= 30)
  .map(([y, e]) => ({ year: y, pct: 100 * e.s / e.n, n: e.n }))
  .sort((a, b) => a.year - b.year);
const firstOver50 = solid.find(e => e.pct > 50);
const lastUnder10 = [...solid].filter(e => e.year < firstOver50.year).reverse().find(e => e.pct < 10);
eq('first year over 50%', firstOver50.year, 1946);
eq('last year under 10%', lastUnder10.year, 1936);
eq('the gap between them, in years', firstOver50.year - lastUnder10.year, 10);
eq('first-over-50 agrees with findings.json', firstOver50.year, F.crossings.firstOver50.year);
eq('last-under-10 agrees with findings.json', lastUnder10.year, F.crossings.lastUnder10.year);
ok('no year after the crossing ever returns below 10%',
  !solid.filter(e => e.year > firstOver50.year).some(e => e.pct < 10));

// --- 4. the sensitivity sweep: the break must not be a choice ----------------
console.log('\n4. the break survives every denominator');
for (const w of [0, 100, 200, 400, 800, 1600, 3200]) {
  const set = rows.filter(r => isCourt(r) && signed(r) && r.words >= w && yearOf(r) > 0);
  const dd = new Map();
  for (const r of set) {
    const d = Math.floor(yearOf(r) / 10) * 10;
    const e = dd.get(d) || { n: 0, s: 0 };
    e.n++; if (separates(r).length) e.s++;
    dd.set(d, e);
  }
  const rate = d => { const e = dd.get(d); return 100 * e.s / e.n; };
  const pre = Math.max(...[...dd].filter(([d]) => d >= 1800 && d < 1940).map(([d]) => rate(d)));
  const post = Math.min(...[...dd].filter(([d]) => d >= 1950 && d < 2010).map(([d]) => rate(d)));
  ok(`minWords=${w}: every pre-1940 decade is below every post-1950 decade`, pre < post,
    `worst pre-1940 decade ${pre.toFixed(1)}%, best-case post-1950 decade ${post.toFixed(1)}%`);
  const row = F.sensitivity.find(s => s.minWords === w);
  eq(`minWords=${w}: case count matches findings.json`, set.length, row.cases);
}

// --- 5. the longest silence -------------------------------------------------
console.log('\n5. the longest silence');
const auditSet = new Set(AUDIT.hitKeys);
function longestRun(alsoBroken) {
  const list = decided.slice().sort((a, b) => (a.vol - b.vol) || a.file.localeCompare(b.file));
  let best = { len: 0 }, run = [];
  for (const r of list) {
    const broken = separates(r).length > 0 || (alsoBroken && auditSet.has(`${r.vol}:${r.file}`));
    if (broken) { if (run.length > best.len) best = { len: run.length, a: run[0], b: run[run.length - 1] }; run = []; }
    else run.push(r);
  }
  if (run.length > best.len) best = { len: run.length, a: run[0], b: run[run.length - 1] };
  return best;
}
const strict = longestRun(true);
const loose = longestRun(false);
eq('longest fully silent run, in cases', strict.len, 105);
eq('  it begins at', strict.a.cite, '8 U.S. 421');
eq('  it ends at', strict.b.cite, '11 U.S. 366');
eq('  first case name', strict.a.name, 'Pollard v. Dwight');
eq('  last case name', strict.b.name, 'Lee v. Munroe');
const days = Math.round((Date.parse(strict.b.date) - Date.parse(strict.a.date)) / 86400000);
eq('  span in days', days, 1809);
ok('  that is more than four years', days > 4 * 365);
eq('longest run with no written separate opinion', loose.len, 175);
eq('strict run agrees with findings.json', strict.len, F.trueSilence.length);
eq('loose run agrees with findings.json', loose.len, F.silence.length);

// --- 6. the typing audit ----------------------------------------------------
console.log('\n6. the typing audit');
eq('cases re-read', AUDIT.scanned, decided.filter(r => separates(r).length === 0).length);
eq('headings found', AUDIT.hits, AUDIT.hitKeys.length);
near('miss rate', +(100 * AUDIT.hits / AUDIT.scanned).toFixed(2), AUDIT.missRate, 0.01);
const missByDecade = new Map(AUDIT.decades.map(d => [d.decade, d.missRate]));
const preMax = Math.max(...[...missByDecade].filter(([d]) => d >= 1800 && d < 1940).map(([, v]) => v));
const postMax = Math.max(...[...missByDecade].filter(([d]) => d >= 1940).map(([, v]) => v));
ok('the typing misses MORE in the modern era than the old, so the audit cannot be manufacturing the finding',
  postMax > preMax, `worst pre-1940 decade ${preMax}%, worst post-1940 decade ${postMax}%`);
// The correction has to widen the gap, not close it. This is the claim the page
// makes about its own audit, so it is checked rather than asserted.
const corr = new Map(F.corrected.map(c => [c.decade, c]));
ok('after adding every missed heading, the 1930s stay far below the 1950s',
  corr.get(1930).upperPct < corr.get(1950).upperPct - 40,
  `${corr.get(1930).upperPct}% vs ${corr.get(1950).upperPct}%`);
for (const c of F.corrected) ok(`  ${c.decade}s upper bound >= typed`, c.upperPct >= c.typedPct);

// --- 7. the quotations are really in the record -----------------------------
console.log('\n7. the quotations');
// The title. Higginson v. Mein, 8 U.S. 415 (1808) — the page quotes the last
// line of the Court's opinion. cases-min carries no text, so this is checked
// against the audit's own stored snippet, which was cut from the full scan.
const hig = AUDIT.examples.find(e => /Higginson/.test(e.name));
ok('Higginson v. Mein is in the audit examples', !!hig);
ok('  and its text carries the page\'s title phrase',
  !!hig && /dissented from this opinion, but did not state his reasons/.test(hig.snippet),
  hig ? JSON.stringify(hig.snippet.slice(-70)) : '');
eq('  its citation', hig && hig.cite, '8 U.S. 415');
eq('  its date', hig && hig.date, '1808-03-14');
ok('the page prints that sentence verbatim',
  html.includes('Livingston, J., dissented from this opinion, but did not state his reasons.'));
ok('the same formula recurs in 1813 (Herbert v. Wren), as the page says',
  AUDIT.examples.some(e => /Herbert/.test(e.name) && /did not state his reasons/.test(e.snippet)));
// Every example the page prints must be an audit hit, verbatim.
let quoted = 0, quotedBad = 0;
for (const e of F.audit.examples.slice(0, 6)) {
  const body = e.snippet.replace(/^\S*\s/, '');
  quoted++;
  if (!html.includes(body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'))
    && !html.includes(body)) quotedBad++;
}
eq('every quoted scan passage appears on the page verbatim', quotedBad, 0);
ok('  and there are some', quoted === 6);

// --- 8. the page and the dek print what was computed ------------------------
console.log('\n8. the page prints the computed numbers');
const nfmt = x => x.toLocaleString('en-US');
const mustAppear = [
  ['decided cases', nfmt(decided.length)],
  ['cases in the reporter', nfmt(rows.length)],
  ['Supreme Court entries', nfmt(rows.filter(isCourt).length)],
  ['separate opinions', nfmt(decided.reduce((a, r) => a + separates(r).length, 0))],
  ['audit scanned', nfmt(AUDIT.scanned)],
  ['audit hits', nfmt(AUDIT.hits)],
  ['silence length', '105'],
  ['silence days', nfmt(1809)],
  ['last year under ten per cent', '1936'],
  ['first year over half', '1946'],
];
for (const [label, s] of mustAppear) ok(`page prints the ${label} (${s})`, html.includes(s));
// The dek is a summary, so it carries a subset. Each of these is a number it
// actually states, and each must be the recomputed one.
const dekMust = ['decided cases', 'cases in the reporter', 'audit scanned', 'audit hits',
  'silence length', 'silence days', 'last year under ten per cent', 'first year over half'];
for (const [label, s] of mustAppear) {
  if (dekMust.includes(label)) ok(`dek prints the ${label} (${s})`, md.includes(s));
}
eq('dek states the count of cases decided by other courts',
  md.includes(nfmt(F.corpus.nonScotusCasesInReporter)), true);
eq('dek states the volume count', md.includes(String(F.source.volumesFetched)), true);

// The dek's own rates.
for (const s of ['11.7%', '59.7%']) ok(`dek prints ${s}`, md.includes(s));
ok('page carries the canonical way out', /aw-wayout/.test(html));
ok('page carries the shared top bar', /home-banner\.js/.test(html));
ok('page declares its canonical url',
  html.includes('href="https://artwaste.land/strata/did-not-state-his-reasons/"'));
ok('page names its source', html.includes('static.case.law'));
ok('page states the coverage end year', html.includes(String(F.corpus.lastYear)));
ok('page discloses the seriatim limit', /seriatim era is not resolved here/.test(html));
ok('page discloses the shared surnames', /two Justices/.test(html));
ok('page refuses to assert a cause', /This page takes no\s+side/.test(html));

// --- 8b. checked against two counts made by hand ----------------------------
// These are the page's external controls, so the verifier recomputes both sides
// of each comparison rather than trusting findings.json's copy.
console.log('\n8b. the external comparisons');
const E = F.external;
const waiteWindow = decided.filter(r => yearOf(r) >= 1874 && yearOf(r) <= 1888);
const waiteTyped = waiteWindow.filter(r => separates(r).length > 0).length;
const waiteNoted = waiteWindow.filter(r => separates(r).length === 0 && auditSet.has(`${r.vol}:${r.file}`)).length;
eq('Waite window case count', waiteWindow.length, E.waite.ourCases);
near('Waite window, typed separate opinions', +(100 * waiteTyped / waiteWindow.length).toFixed(1), E.waite.ourTypedPct, 0.05);
near('Waite window, plus the notes the audit recovered',
  +(100 * (waiteTyped + waiteNoted) / waiteWindow.length).toFixed(1), E.waite.ourWithNotesPct, 0.05);
ok('  and that lands within 1.5 points of the 9% Epstein, Segal & Spaeth read off the same Reports',
  Math.abs(E.waite.ourWithNotesPct - E.waite.theirReportedPct) <= 1.5,
  `ours ${E.waite.ourWithNotesPct}%, theirs ${E.waite.theirReportedPct}%`);
ok('  the published conference figure is far above the published print figure',
  E.waite.theirConferencePct > 4 * E.waite.theirReportedPct,
  `${E.waite.theirConferencePct}% at conference vs ${E.waite.theirReportedPct}% in the Reports`);

// Walker, Epstein & Dixon Table 1, recomputed and re-correlated here.
const WED = E.wed.published;
const years12 = Object.keys(WED).map(Number).sort();
eq('the compared window is twelve Terms', years12.length, 12);
const mineSeries = years12.map(y => {
  const set = decided.filter(r => yearOf(r) === y);
  const d = set.reduce((a, r) => a + r.ops.filter((o, i) => i > 0 && o.type === 'dissent').length, 0);
  return d / set.length;
});
let seriesMismatch = 0;
years12.forEach((y, i) => { if (Math.abs(mineSeries[i] - E.wed.ours[y].perOpinion) > 0.0015) seriesMismatch++; });
eq('every Term in the compared series is reproduced', seriesMismatch, 0);
const mean = a => a.reduce((p, q) => p + q, 0) / a.length;
const th = years12.map(y => WED[y]);
const mA = mean(mineSeries), mB = mean(th);
const r = mineSeries.reduce((a, v, i) => a + (v - mA) * (th[i] - mB), 0) /
  (Math.sqrt(mineSeries.reduce((a, v) => a + (v - mA) ** 2, 0)) * Math.sqrt(th.reduce((a, v) => a + (v - mB) ** 2, 0)));
near('Pearson r against the 1988 hand-coded series', +r.toFixed(4), E.wed.pearsonR, 0.0002);
ok('  and it is a strong positive correlation', r > 0.8, `r = ${r.toFixed(4)}`);
ok('  ours runs lower than theirs, as the page says it does', mA < mB,
  `ours ${mA.toFixed(3)}, theirs ${mB.toFixed(3)}`);
ok('the page prints the correlation', html.includes(String(E.wed.pearsonR)));
ok('the page prints both Waite figures', html.includes(String(E.waite.ourWithNotesPct)) && html.includes('>40%<'));

// --- 8c. the correction offered to Kelsh ------------------------------------
console.log('\n8c. the correction');
ok('the page quotes Kelsh footnote 65 verbatim',
  html.includes('this period also saw the first dissent'));
ok('the page names the earlier case and its date',
  /Higginson v. Mein<\/i>, 8 U.S./.test(html) && html.includes('14 March 1808'));
ok('Higginson really is earlier than Herbert in the corpus',
  Date.parse(rows.find(x => /Higginson/.test(x.name) && x.vol === 8).date)
  < Date.parse(rows.find(x => /Herbert v. Wren/.test(x.name) && x.vol === 11).date));
ok('the page states the correction is offered, not asserted as settled',
  /offered as a correction and not as a gotcha/.test(html));
ok('the page names the second, independent scan it was checked against',
  html.includes('usrep008415.pdf') && html.includes('usrep011370.pdf'));
ok('the page carries a works-cited list', /Works cited/.test(html));
ok('  naming the two comparison studies',
  html.includes('Norm of Consensus') && html.includes('Mysterious Demise'));

// --- 9. attribution ---------------------------------------------------------
console.log('\n9. who wrote separately');
const tally = new Map();
for (const r of decided) {
  for (const o of separates(r)) {
    const a = o.author.replace(/[^A-Za-z]+/g, ' ').toUpperCase();
    for (const name of ['STEVENS', 'DOUGLAS', 'BRENNAN']) {
      if (new RegExp(`\\b${name}\\b`).test(a)) {
        // credit the first surname on the line, as the page says
        const others = ['STEVENS', 'DOUGLAS', 'BRENNAN'].filter(x => new RegExp(`\\b${x}\\b`).test(a));
        const first = others.sort((x, y) => a.indexOf(x) - a.indexOf(y))[0];
        if (first === name) tally.set(name, (tally.get(name) || 0) + 1);
      }
    }
  }
}
ok('Stevens leads the roster, as the page shows', F.justices[0].justice === 'Stevens',
  `top of the published table is ${F.justices[0].justice} with ${F.justices[0].total}`);
ok('an independent count of Stevens lines is within 3% of the published one',
  Math.abs(tally.get('STEVENS') - F.justices[0].total) / F.justices[0].total < 0.03,
  `independent ${tally.get('STEVENS')}, published ${F.justices[0].total}`);
ok('the match rate is disclosed and below 100%',
  F.justiceMatch.rate < 1 && html.includes((100 * F.justiceMatch.rate).toFixed(1) + '%'));

// ---------------------------------------------------------------------------
console.log(`\n${pass}/${pass + fail} checks passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
