#!/usr/bin/env node
// verify-the-error-they-share.mjs — the offline check behind
// /strata/the-error-they-share/.
//
// Everything the page states about the experiment is re-derived here from the
// committed transcript, by rules RE-IMPLEMENTED from their written description
// in research/myth-consensus/README.md rather than imported from score.mjs.
// Where score.mjs computes a p-value exactly, this file computes it again by
// Monte Carlo, so an error in either method shows up as a disagreement.
//
//   node verify-the-error-they-share.mjs
//
// Exit 0 iff every check passes.

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

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = (p) => join(ROOT, p);
const SLUG = 'the-error-they-share';
const N_ITEMS = 21;
const PAGE = R(`public/strata/${SLUG}/index.html`);

let pass = 0, fail = 0;
const fails = [];
function check(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok    ${name}`); }
  else { fail++; fails.push(name + (detail ? ` — ${detail}` : '')); console.log(`  FAIL  ${name}${detail ? ' — ' + detail : ''}`); }
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

const items = JSON.parse(readFileSync(R('research/myth-consensus/items.json'), 'utf8'));
const models = JSON.parse(readFileSync(R('research/myth-consensus/models.json'), 'utf8'));
const results = JSON.parse(readFileSync(R('research/myth-consensus/results.json'), 'utf8'));
const rows = readFileSync(R('research/myth-consensus/asks.jsonl'), 'utf8')
  .split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l));

console.log('\n1 · the item bank says only what its sources say');
// Re-implemented normaliser: render the file the way a reader sees it, then
// require each evidence quote to be present verbatim.
function flatten(s) {
  return s.replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'")
    .replace(/[‘’]/g, "'").replace(/[“”]/g, '"')
    .replace(/\s+/g, ' ')
    .replace(/\s+([,.;:!?%)\]])/g, '$1').replace(/([(\[])\s+/g, '$1')
    .trim();
}
let quoteChecks = 0, quoteBad = 0;
for (const it of items) {
  for (const kind of ['checked', 'myth']) {
    const e = it.evidence[kind];
    const src = flatten(readFileSync(R(e.file), 'utf8'));
    for (const seg of flatten(e.quote).split(/\s*(?:…|\.\.\.)\s*/).filter((s) => s.length > 12)) {
      quoteChecks++;
      if (!src.includes(seg)) { quoteBad++; console.log(`        missing: ${it.id}/${kind} in ${e.file}`); }
    }
  }
}
check(`all ${quoteChecks} evidence quotes present in the files they name`, quoteBad === 0, `${quoteBad} missing`);
check(`${N_ITEMS} items`, items.length === N_ITEMS);
check('every item offers 5 distinct options',
  items.every((it) => new Set(['checked', 'myth', 'd1', 'd2', 'd3'].map((r) => it.options[r].toLowerCase())).size === 5));

console.log('\n2 · the transcript is internally consistent');
// The permutation rule, re-implemented from the README: FNV-1a over
// "item|model|condition" seeds a mulberry32; a Fisher-Yates shuffle consumes it.
function fnv(s) { let h = 0x811c9dc5; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return h >>> 0; }
function rng(a) { return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
function order(n, seed) { const r = rng(seed); const ix = Array.from({ length: n }, (_, i) => i); for (let i = n - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [ix[i], ix[j]] = [ix[j], ix[i]]; } return ix; }
const roleSet = (c) => (c === 'A' ? ['checked', 'myth', 'd1', 'd2'] : ['checked', 'd3', 'd1', 'd2']);
const byId = new Map(items.map((i) => [i.id, i]));
let permBad = 0, labelBad = 0, slotBad = 0;
for (const r of rows) {
  // A row with no item is a bookkeeping marker for a mind the tier stopped
  // serving. It is not an ask and must not be checked as one.
  if (r.unserved) continue;
  const it = byId.get(r.item); if (!it) { permBad++; continue; }
  const roles = roleSet(r.condition);
  const labels = roles.map((x) => it.options[x]);
  const seed = fnv(`${r.item}|${r.model}|${r.condition}`);
  if (seed !== r.seed) { permBad++; continue; }
  const ix = order(4, seed);
  if (JSON.stringify(ix.map((i) => roles[i])) !== JSON.stringify(r.shownRoles)) permBad++;
  if (JSON.stringify(ix.map((i) => labels[i])) !== JSON.stringify(r.shown)) labelBad++;
  if (r.shownRoles.indexOf('checked') + 1 !== r.checkedSlot) slotBad++;
}
check(`all ${rows.length} asks carry the permutation their (item, model, condition) implies`, permBad === 0, `${permBad} wrong`);
check('every ask shows the option text its roles imply', labelBad === 0, `${labelBad} wrong`);
check('every recorded checkedSlot matches its own shownRoles', slotBad === 0, `${slotBad} wrong`);
check('no ask offers the myth in condition B',
  rows.every((r) => r.condition !== 'B' || !r.shownRoles.includes('myth')));
check('every condition-A ask offers exactly one myth option',
  rows.every((r) => r.condition !== 'A' || r.shownRoles.filter((x) => x === 'myth').length === 1));

console.log('\n3 · the parse rule, re-implemented from its written description');
function readChoice(raw, shown) {
  if (typeof raw !== 'string' || !raw.trim()) return null;
  // R1: last "ANSWER: n"
  let last = null, m;
  const re = /ANSWER\s*[:：]\s*\(?\[?\s*([1-6])/gi;
  while ((m = re.exec(raw)) !== null) last = parseInt(m[1], 10);
  if (last !== null) return last;
  // R2: last line that is nothing but an integer
  const lines = raw.split('\n').map((s) => s.trim()).filter(Boolean);
  for (let i = lines.length - 1; i >= 0; i--) {
    const mm = /^[([]?\s*([1-6])\s*[)\]]?\s*[.:]?$/.exec(lines[i]);
    if (mm) return parseInt(mm[1], 10);
  }
  // R3: last line is exactly one of the options
  if (lines.length) {
    const tail = lines[lines.length - 1].replace(/\.$/, '').trim().toLowerCase();
    const k = shown.findIndex((s) => s.replace(/\.$/, '').trim().toLowerCase() === tail);
    if (k >= 0) return k + 1;
  }
  return null;
}
const parsed = [];
let readable = 0, silent = 0, unreadable = 0;
for (const r of rows) {
  if (r.unserved) continue;
  if (r.throttled || r.upstream) { continue; }   // never reached a mind; not scored
  if (r.silent) { silent++; continue; }
  const slot = readChoice(r.raw, r.shown);
  if (!slot || slot > 4) { unreadable++; continue; }
  readable++;
  parsed.push({ item: r.item, model: r.model, condition: r.condition, slot, role: r.shownRoles[slot - 1] });
}
check('attempts counted match the transcript, excluding bookkeeping rows',
  results.tally.asked === rows.filter((r) => !r.unserved).length,
  `${results.tally.asked} vs ${rows.filter((r) => !r.unserved).length}`);
check('distinct questions put is at most the attempt count',
  results.tally.cells <= results.tally.asked, `${results.tally.cells} vs ${results.tally.asked}`);
check('no ask that never reached a mind is counted as a silence',
  results.tally.silent === rows.filter((r) => r.silent && !r.upstream && !r.throttled && !r.unserved).length);
check('silences agree with score.mjs', results.tally.silent === silent, `${results.tally.silent} vs ${silent}`);
check('readable count agrees with score.mjs', results.tally.readable === readable, `${results.tally.readable} vs ${readable}`);
check('unreadable count agrees with score.mjs', results.tally.unreadable === unreadable, `${results.tally.unreadable} vs ${unreadable}`);
check('a silent mind is never scored', rows.filter((r) => r.silent).every((r) => r.raw === undefined));
check('the dropped item is absent from the bank', !items.some((i) => i.id === 'closest-planet'));
check('every item declares whether its myth is evidenced as held or only corrected',
  items.every((i) => i.mythEvidence === 'held' || i.mythEvidence === 'corrected'));

console.log('\n4 · the numbers the page states');
const A = parsed.filter((p) => p.condition === 'A');
const B = parsed.filter((p) => p.condition === 'B');
const accA = A.filter((p) => p.role === 'checked').length / A.length;
const accB = B.filter((p) => p.role === 'checked').length / B.length;
check('condition A accuracy', close(accA, results.accuracy.A.rate, 1e-12), `${accA} vs ${results.accuracy.A.rate}`);
check('condition B accuracy', close(accB, results.accuracy.B.rate, 1e-12), `${accB} vs ${results.accuracy.B.rate}`);

const wrongA = A.filter((p) => p.role !== 'checked');
const nMyth = wrongA.filter((p) => p.role === 'myth').length;
check('wrong answers in A counted the same way', wrongA.length === results.errorCompositionA.n, `${wrongA.length} vs ${results.errorCompositionA.n}`);
check('myth count in A', nMyth === results.errorCompositionA.myth, `${nMyth} vs ${results.errorCompositionA.myth}`);

// The exact binomial tail in score.mjs, recomputed by Monte Carlo here.
function mcBinomGE(k, n, p, iters = 300000, seed = 7) {
  const r = rng(seed); let ge = 0;
  for (let t = 0; t < iters; t++) { let s = 0; for (let i = 0; i < n; i++) if (r() < p) s++; if (s >= k) ge++; }
  return (ge + 1) / (iters + 1);
}
if (results.errorCompositionA.test) {
  const mc = mcBinomGE(nMyth, wrongA.length, 1 / 3);
  const exact = results.errorCompositionA.test.pGreater;
  const agree = (exact < 1e-4 && mc < 1e-3) || close(mc, exact, 0.01);
  check('myth-share p-value: exact and Monte Carlo agree', agree, `exact ${exact.toExponential(2)} vs MC ${mc.toExponential(2)}`);
}

// McNemar
const key = (p) => `${p.item}|${p.model}`;
const mA = new Map(A.map((p) => [key(p), p])), mB = new Map(B.map((p) => [key(p), p]));
let ab = 0, ba = 0;
for (const [k, a] of mA) { const b = mB.get(k); if (!b) continue; const ar = a.role === 'checked', br = b.role === 'checked'; if (ar && !br) ab++; else if (!ar && br) ba++; }
check('McNemar discordants: A-right/B-wrong', ab === results.pull.aRightBWrong, `${ab} vs ${results.pull.aRightBWrong}`);
check('McNemar discordants: A-wrong/B-right', ba === results.pull.aWrongBRight, `${ba} vs ${results.pull.aWrongBRight}`);

// The independence prediction for majority voting, by simulation rather than
// by the exact Poisson-binomial convolution score.mjs uses.
const rate = {};
for (const m of models) { const rs = A.filter((p) => p.model === m.id); if (rs.length) rate[m.id] = rs.filter((p) => p.role === 'checked').length / rs.length; }
const r2 = rng(99);
let sim = 0; const ITER = 20000;
for (let t = 0; t < ITER; t++) {
  for (const it of items) {
    const rs = A.filter((p) => p.item === it.id); if (!rs.length) continue;
    let c = 0; for (const p of rs) if (r2() < rate[p.model]) c++;
    if (c > rs.length / 2) sim++;
  }
}
sim /= ITER;
check('majority-under-independence: exact and simulated agree',
  close(sim, results.ensemble.majorityExpectedUnderIndependence, 0.35),
  `sim ${sim.toFixed(2)} vs exact ${results.ensemble.majorityExpectedUnderIndependence.toFixed(2)}`);

console.log('\n5 · the page says what the record says');
if (!existsSync(PAGE)) {
  check('page exists', false, PAGE);
} else {
  const html = readFileSync(PAGE, 'utf8');
  // Checking that a bare number appears somewhere in a 40 KB document proves
  // nothing: "22" occurs in dates, hex colours and CSS. Each fact is checked in
  // the sentence that carries it, so the check fails when the page drifts.
  const facts = [
    ['attempts recorded', new RegExp(`<b>${results.tally.asked}</b>\\s*attempts are recorded`)],
    ['distinct questions put', new RegExp(`<b>${results.tally.cells}</b>\\s*distinct`)],
    ['readable answers', new RegExp(`<b>${results.tally.readable}</b>\\s*produced a readable`)],
    ['upstream-plus-throttle count', new RegExp(`<b>${results.tally.upstream + results.tally.throttled}</b>\\s*never reached a mind`)],
    ['myth-share numerator', new RegExp(`<td class="num">${results.errorCompositionA.myth}</td>`)],
    ['arm A accuracy', new RegExp(`${(100 * results.accuracy.A.rate).toFixed(1)}%`)],
    ['the bootstrap interval', new RegExp(`${(100 * results.bootstrap.lo95).toFixed(1)}%\\s*to\\s*${(100 * results.bootstrap.hi95).toFixed(1)}%`)],
    ['the sign-test item count', new RegExp(`at least one wrong answer</td><td class="num">${results.signTest ? results.signTest.items : 0}</td>`)],
  ];
  for (const [label, re] of facts) check(`page states the ${label} in its own sentence`, re.test(html));
  check('page does not claim every mind saw every question', !/Every mind saw every question/.test(html));
  check('page names the dropped item and why', /dropped before the run/.test(html));
  // The roster leans on one maker, and the page is required to SAY so with the
  // real number rather than leave a reader to count the table.
  const byMaker = {};
  for (const m of models) byMaker[m.maker] = (byMaker[m.maker] || 0) + 1;
  const top = Object.entries(byMaker).sort((a, b) => b[1] - a[1])[0];
  check(`page states the roster's concentration (${top[0]}: ${top[1]} of ${models.length})`,
    html.includes(top[0]) && new RegExp(`${top[1]}\\s*of\\s*(the\\s*)?\\n?\\s*${models.length}`).test(html));
  check('page publishes the parse rule', /ANSWER/.test(html));
}

console.log(`\n${pass} passed, ${fail} failed`);
if (fail) { console.log('\nfailures:'); for (const f of fails) console.log('  · ' + f); }
process.exit(fail ? 1 : 0);
