import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..', '..');
const pageDir = path.join(root, 'public', 'strata', 'semmelweis-before-the-washing');
const htmlPath = path.join(pageDir, 'index.html');
const dataPath = path.join(pageDir, 'data.js');
const pagePath = path.join(pageDir, 'page.js');
const frontmatterPath = path.join(root, 'src', 'content', 'strata', 'semmelweis-before-the-washing.md');
const readmePath = path.join(here, 'README.md');

const html = fs.readFileSync(htmlPath, 'utf8');
const dataCode = fs.readFileSync(dataPath, 'utf8');
const pageCode = fs.readFileSync(pagePath, 'utf8');
const frontmatter = fs.readFileSync(frontmatterPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');
const kitCode = fs.readFileSync(path.join(root, 'public', '_kit', 'hindsight.js'), 'utf8');

const context = { window: {}, console };
context.window.window = context.window;
vm.createContext(context);
new vm.Script(kitCode, { filename: 'hindsight.js' }).runInContext(context);
new vm.Script(dataCode, { filename: 'data.js' }).runInContext(context);
new vm.Script(pageCode, { filename: 'page.js' }).runInContext(context);

const H = context.window.AW.hindsight;
const D = context.window.AW.semmelweisData;
const P = context.window.AW.semmelweis;

let passed = 0;
let failed = 0;

function check(condition, label, detail = '') {
  if (condition) {
    passed += 1;
    console.log(`ok ${passed + failed} - ${label}`);
  } else {
    failed += 1;
    console.error(`not ok ${passed + failed} - ${label}${detail ? `: ${detail}` : ''}`);
  }
}

function close(actual, expected, tolerance = 1e-12) {
  return Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance * Math.max(1, Math.abs(expected));
}

function sum(rows, field) {
  return rows.reduce((total, row) => total + row[field], 0);
}

function stable(value) {
  return JSON.stringify(value);
}

function resourceAttr(tag, name) {
  const match = new RegExp(`\\b${name}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag);
  return match ? match[2].trim() : '';
}

function isRemote(value) {
  return /^(?:https?:)?\/\//i.test(value);
}

function automaticRequests(documentText, executableText = '') {
  const violations = [];
  const tags = documentText.match(/<[^>]+>/g) || [];
  for (const tag of tags) {
    const nameMatch = /^<\s*([a-z0-9]+)/i.exec(tag);
    if (!nameMatch) continue;
    const name = nameMatch[1].toLowerCase();
    if (['img', 'script', 'iframe', 'source', 'video', 'audio', 'embed'].includes(name)) {
      const value = resourceAttr(tag, 'src');
      if (isRemote(value)) violations.push(`${name}[src]=${value}`);
    }
    if (name === 'object') {
      const value = resourceAttr(tag, 'data');
      if (isRemote(value)) violations.push(`object[data]=${value}`);
    }
    if (name === 'form') {
      const value = resourceAttr(tag, 'action');
      if (isRemote(value)) violations.push(`form[action]=${value}`);
    }
    if (name === 'link') {
      const rel = resourceAttr(tag, 'rel').toLowerCase();
      const value = resourceAttr(tag, 'href');
      const fetched = /(?:stylesheet|icon|preload|modulepreload|prefetch|manifest)/.test(rel);
      if (fetched && isRemote(value)) violations.push(`link[rel=${rel}]=${value}`);
    }
  }
  if (/url\(\s*["']?(?:https?:)?\/\//i.test(documentText)) violations.push('remote CSS url()');
  const withoutJsonLd = documentText.replace(/<script\b[^>]*type=["']application\/ld\+json["'][^>]*>[\s\S]*?<\/script>/gi, '');
  const scriptBodies = [...withoutJsonLd.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].map((match) => match[1]).join('\n');
  const code = `${scriptBodies}\n${executableText}`;
  const networkApis = [
    /\bfetch\s*\(/,
    /\bXMLHttpRequest\b/,
    /\bWebSocket\s*\(/,
    /\bEventSource\s*\(/,
    /\bnavigator\s*\.\s*sendBeacon\s*\(/,
    /\bimportScripts\s*\(/
  ];
  for (const pattern of networkApis) if (pattern.test(code)) violations.push(`network API ${pattern}`);
  return violations;
}

function independentAnnual(rows) {
  const out = [];
  let b1 = 0;
  let d1 = 0;
  let b2 = 0;
  let d2 = 0;
  for (const year of [1841, 1842, 1843, 1844, 1845, 1846]) {
    for (const row of rows.filter((item) => item.year === year)) {
      if (row.clinic === 'I') { b1 += row.births; d1 += row.deaths; }
      if (row.clinic === 'II') { b2 += row.births; d2 += row.deaths; }
    }
    out.push((d1 / b1) / (d2 / b2));
  }
  return { ratios: out, b1, d1, b2, d2 };
}

function logFactorial(n) {
  let result = 0;
  for (let i = 2; i <= n; i += 1) result += Math.log(i);
  return result;
}

function independentBinomialTail(successes, n, p) {
  const logs = [];
  const lfN = logFactorial(n);
  for (let k = successes; k <= n; k += 1) {
    logs.push(lfN - logFactorial(k) - logFactorial(n - k) + k * Math.log(p) + (n - k) * Math.log(1 - p));
  }
  const max = Math.max(...logs);
  return Math.exp(max) * logs.reduce((total, value) => total + Math.exp(value - max), 0);
}

function independentMixture(successes, failures, p0) {
  let total = 0;
  for (let j = 1; j <= 19; j += 1) {
    const p1 = p0 + (1 - p0) * j / 20;
    const logValue = successes * Math.log(p1 / p0) + failures * Math.log((1 - p1) / (1 - p0));
    total += Math.exp(logValue) / 19;
  }
  return total;
}

check(fs.existsSync(htmlPath) && fs.existsSync(dataPath) && fs.existsSync(pagePath), 'all three shipped page files exist');
check(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'load-bearing closing tags are present');
check(html.includes('<script src="/_kit/hindsight.js"></script>') && html.indexOf('hindsight.js') < html.indexOf('data.js') && html.indexOf('data.js') < html.indexOf('page.js'), 'shared kit and page scripts load in dependency order');
check(html.includes('<link rel="canonical" href="https://artwaste.land/strata/semmelweis-before-the-washing/"') && html.includes('"datePublished":"2026-08-14"'), 'canonical and JSON-LD identify the shipped page');
check(html.includes('role="status"') && html.includes('aria-live="polite"') && html.includes(':focus-visible') && html.includes('prefers-reduced-motion') && html.includes('/fonts/fonts.css'), 'accessibility contract is visible in the page');

const ownedText = [html, dataCode, pageCode, frontmatter, readme].join('\n');
check(!ownedText.includes('\u2014'), 'owned prose contains no em dash');

const requestViolations = automaticRequests(html, `${dataCode}\n${pageCode}`);
check(requestViolations.length === 0, 'page makes no automatic third-party request', requestViolations.join(', '));
check(automaticRequests(`${html}<img src="https://example.com/plant.png">`, `${dataCode}\n${pageCode}`).some((item) => item.includes('img[src]')), 'request scanner catches a planted remote image');
check(automaticRequests(html, `${dataCode}\n${pageCode}\nconst endpoint = ['https:', '//example.com'].join(''); fetch(endpoint);`).some((item) => item.includes('fetch')), 'request scanner catches an indirect planted fetch');

const annualExpected = [
  [1841, 3036, 237, 2442, 86],
  [1842, 3287, 518, 2659, 202],
  [1843, 3060, 274, 2739, 164],
  [1844, 3157, 260, 2956, 68],
  [1845, 3492, 241, 3241, 66],
  [1846, 4010, 459, 3754, 105]
];
const annualObserved = annualExpected.map(([year]) => {
  const first = D.annual.find((row) => row.year === year && row.clinic === 'I');
  const second = D.annual.find((row) => row.year === year && row.clinic === 'II');
  return [year, first.births, first.deaths, second.births, second.deaths];
});
check(D.annual.length === 12 && stable(annualObserved) === stable(annualExpected), 'all 12 annual source rows match Table I');
check(new Set(D.annual.map((row) => row.id)).size === 12, 'annual record identifiers are unique');

const independent = independentAnnual(D.annual);
check(independent.b1 === 20042 && independent.d1 === 1989, 'Clinic I published anchor totals reproduce exactly');
check(close(independent.d1 / independent.b1 * 100, 9.924159265542361), 'Clinic I anchor recomputes to 9.924159 percent');
check(independent.b2 === 17791 && independent.d2 === 691, 'Clinic II published count totals reproduce exactly');
check(close(independent.d2 / independent.b2 * 100, 3.8839862852003826) && !close(independent.d2 / independent.b2 * 100, 3.38, 1e-4), 'Clinic II counts refute the printed 3.38 percent');

const expectedRatios = [2.216632962588473, 2.1148842629202034, 1.9021785775253495, 2.134100723837566, 2.286022025914042, 2.5551478653149657];
check(independent.ratios.every((value, index) => close(value, expectedRatios[index])), 'independent cumulative risk-ratio trajectory matches six published releases');
const pageAnnual = P.annualReplay(D.annual, 2);
check(pageAnnual.values.every((value, index) => close(value, independent.ratios[index])), 'page calculation matches the independent risk-ratio trajectory');
check(stable(pageAnnual.events.map((event) => [event.cutoff, event.kind])) === stable([['1841', 'enter'], ['1843', 'exit'], ['1844', 'enter']]), 'twofold rule reports every entry and exit');
check(stable(P.annualReplay(D.annual, 2.5).events.map((event) => [event.cutoff, event.kind])) === stable([['1846', 'enter']]), 'reader threshold sensitivity changes the crossing honestly');

for (const cutoff of D.annualCutoffs) {
  const gated = P.annualAtCutoff(D.annual, cutoff);
  check(H.violations(gated.used, cutoff, { dateField: 'observed' }).length === 0, `annual firewall has no leak at ${cutoff}`);
}
const plant = { id: 'PLANT-2099', observed: '2099', year: 2099, clinic: 'I', births: 999999, deaths: 999999 };
const runner = (rows) => P.annualAtCutoff(rows, '1841');
const audit = H.auditFirewall(runner, D.annual, '1841', plant, { dateField: 'observed' });
const poisoned = runner(D.annual.concat([plant]));
check(audit.pass && !audit.enteredFit && !audit.answerMoved && poisoned.later.some((item) => item.record.id === plant.id), 'planted future row is rejected, reported, and cannot move the answer');
const leakyRunner = (rows) => ({ used: rows, value: P.annualFit(rows) });
check(!H.auditFirewall(leakyRunner, D.annual, '1841', plant, { dateField: 'observed' }).pass, 'firewall negative control fails a deliberately leaky pipeline');

check(D.monthly.length === 98 && new Set(D.monthly.map((row) => row.id)).size === 98, 'monthly archive contains 98 unique printed records');
check(!D.monthly.some((row) => row.observed === '1841-12') && D.missingLabel === '1841-12', 'lost December 1841 record remains an explicit gap');
const faulty = D.monthly.find((row) => row.id === D.sourceFaultId);
check(faulty.births === 912 && faulty.deaths === 6 && faulty.printedRate === 1.92 && close(100 * faulty.deaths / faulty.births, 0.6578947368421053), 'February 1847 source literal is preserved and internally inconsistent');
check(D.correction.births === 312 && D.correction.deaths === 6 && close(100 * D.correction.deaths / D.correction.births, 1.9230769230769231), 'labelled February correction reproduces the printed rate');

const mayGate = P.monthlyAtCutoff(D.monthly, '1847-05', true);
check(stable(mayGate.counts) === stable({ used: 75, later: 22, excluded: 1, undated: 0 }), 'monthly firewall displays all four May 1847 buckets');
check(Object.values(mayGate.counts).reduce((a, b) => a + b, 0) === D.monthly.length, 'monthly May buckets balance the complete archive');
const fullMonthly = P.monthlyAtCutoff(D.monthly, '1849-03', true);
check(fullMonthly.value.births === 26166 && fullMonthly.value.deaths === 2202 && fullMonthly.counts.excluded === 1, 'corrected full monthly totals are recomputed from 97 source rows plus one labelled correction');
const literalBefore = P.monthlyAtCutoff(D.monthly, '1847-01', false);
const literalAfter = P.monthlyAtCutoff(D.monthly, '1847-02', false);
check(!literalBefore.refused && literalAfter.refused && literalAfter.value === null && /refuses/.test(literalAfter.refusal), 'literal mode verifies its refusal boundary');
const replayCorrected = P.monthlyReplay(D.monthly, true);
const replayLiteral = P.monthlyReplay(D.monthly, false);
check(replayCorrected.total === 98 && replayCorrected.nOk === 98 && replayCorrected.rows.at(-1).cutoff === '1849-03', 'corrected monthly replay runs to the archive end');
check(replayLiteral.nOk === 72 && replayLiteral.nFailed === 26 && replayLiteral.rows.at(-1).error.includes('source inconsistency'), 'literal replay records every downstream refusal through the archive end');

const evidence = P.evidenceTrack(D.monthly);
check(evidence.baseline.value.births === 19571 && evidence.baseline.value.deaths === 2060 && close(evidence.p0, 0.8947422206325686), 'prewashing point-null comparator is frozen at May 1847');
const last = evidence.points.at(-1);
check(last.label === '1849-03' && last.births === 6595 && last.deaths === 142 && evidence.points.length === 23, 'evidence trajectory includes all 22 post-washing month releases');
const independentE = independentMixture(last.survivors, last.deaths, evidence.p0);
const independentP = independentBinomialTail(last.survivors, last.births, evidence.p0);
check(close(last.e, independentE, 2e-11), 'final e-value matches an independent likelihood-ratio mixture');
check(close(last.p, independentP, 2e-10), 'final naive p-value matches an independent binomial tail');
check(evidence.eCrossings.entries === 1 && evidence.eCrossings.exits === 0 && evidence.naiveCrossings.entries === 1 && evidence.naiveCrossings.exits === 0, 'complete evidence tracks report all entries and exits');

const simulation = P.nullSimulation(2000, 1000, 184705);
check(stable(simulation.map((row) => [row.horizon, row.naiveCount, row.anytimeCount])) === stable([[10, 90, 17], [50, 306, 55], [250, 508, 70], [1000, 662, 72]]), 'seeded null simulation reproduces every displayed crossing count');
check(simulation.every((row, index) => index === 0 || row.naive >= simulation[index - 1].naive) && simulation.at(-1).naive > simulation[0].naive, 'naive ever-crossing rate rises as looks accumulate');
check(simulation.every((row) => row.anytime <= 0.05), 'simulated e-process ever-crossing rate stays below the Ville bound');

check(H.thin(D.monthly, 98).complete && H.thin(D.monthly, 98).drawn === 98 && H.thin(D.monthly, 98).total === 98, 'monthly chart caption truthfully reports 98 of 98 positions');
check(!html.includes('2.2166') && !html.includes('2.5551') && !html.includes('9.924159'), 'derived headline values are not hardcoded into the HTML');
check(html.includes('A numerical score between these unlike actions') && html.includes('cannot tell us how many deaths would have occurred'), 'counterfactual refusal and unobserved branch are stated on the page');
check(html.includes('What no diligence could recover in 1841') && html.includes('individual examiner contacts') && html.includes('mortality under chlorine washing'), 'unavailable quantities are visible and operable');
check(frontmatter.includes('date: 2026-08-14') && frontmatter.includes('seam: "groundtruth"') && frontmatter.includes('href: "/strata/semmelweis-before-the-washing/"') && frontmatter.includes('draft: false') && frontmatter.includes('relates:'), 'frontmatter publishes the requested seam, href, date, and edges');
check(readme.includes('public domain by age') && readme.includes('not redistributed') && readme.includes('CC BY-SA 4.0') && readme.includes('No third-party dataset file is shipped'), 'README states source and redistribution licences');

// ── the printed-percentage census ──────────────────────────────────────────
// Added after the supervisor read the Tabelle Nr. I scan directly (BSB bsb10860445_00013)
// rather than trusting either worker's transcription of the printed percentages.
const printedRows = D.annual.filter((r) => typeof r.printedPct === 'number');
check(printedRows.length === 12, 'all twelve annual cells carry the percentage printed beside them');

const cells = printedRows
  .map((r) => ({ name: `${r.year}-${r.clinic}`, actual: (100 * r.deaths) / r.births, printed: r.printedPct }))
  .concat([
    { name: 'Summa-I', actual: (100 * 1989) / 20042, printed: 9.92 },
    { name: 'Summa-II', actual: (100 * 691) / 17791, printed: 3.38 },
  ]);
const dec = (v) => { const s = String(v), i = s.indexOf('.'); return i < 0 ? 0 : s.length - i - 1; };
const roundsTo = (c) => { const f = 10 ** dec(c.printed); return Math.abs(Math.round(c.actual * f) / f - c.printed) < 1e-9; };
const truncsTo = (c) => { const f = 10 ** dec(c.printed); return Math.abs(Math.floor(c.actual * f) / f - c.printed) < 1e-9; };

check(cells.length === 14, 'the census covers all fourteen printed percentages');
check(cells.filter((c) => roundsTo(c) || truncsTo(c)).length === 11,
  'eleven of the fourteen printed cells reproduce under rounding or truncation');
check(cells.filter((c) => roundsTo(c)).length === 6 && cells.filter((c) => truncsTo(c)).length === 10,
  'the table mixes conventions: 6 cells round, 10 truncate');

const summaII = cells.find((c) => c.name === 'Summa-II');
const summaMiss = Math.abs(summaII.actual - summaII.printed);
const worstOther = Math.max(...cells.filter((c) => c.name !== 'Summa-II').map((c) => Math.abs(c.actual - c.printed)));
check(close(summaMiss, 0.5040, 5e-4), 'the Clinic II Summa misses its printed value by 0.504 points');
check(close(worstOther, 0.1063, 5e-4), 'no other cell misses by more than 0.107 points');
check(summaMiss > 4 * worstOther, 'the Clinic II Summa miss is more than four times any other cell');

// NEGATIVE CONTROL. If the anomaly were an artefact of how this check measures agreement, a
// repaired 3.88 would fail it too. It must not: the point is that 3.38 specifically does not fit.
check(roundsTo({ actual: summaII.actual, printed: 3.88 }) || truncsTo({ actual: summaII.actual, printed: 3.88 }),
  'NEGATIVE CONTROL: a corrected 3.88 does reproduce, so the anomaly is 3.38 and not the test');
check(!roundsTo({ actual: summaII.actual, printed: 3.38 }) && !truncsTo({ actual: summaII.actual, printed: 3.38 }),
  'and the printed 3.38 reproduces under neither convention');

// ── the three readings of "durchschnittlich dreimal" ───────────────────────
const risk = (b, d) => d / b;
const summedRatio = risk(20042, 1989) / risk(17791, 691);
const yearlyRatios = [1841, 1842, 1843, 1844, 1845, 1846].map((y) => {
  const a = D.annual.find((r) => r.year === y && r.clinic === 'I');
  const b = D.annual.find((r) => r.year === y && r.clinic === 'II');
  return risk(a.births, a.deaths) / risk(b.births, b.deaths);
});
const meanYearly = yearlyRatios.reduce((x, y) => x + y, 0) / yearlyRatios.length;
check(close(summedRatio, 2.5551, 5e-4), 'ratio of the summed risks is 2.5551');
check(close(meanYearly, 2.8080, 5e-4), 'mean of the six annual ratios is 2.8080');
check(close(9.92 / 3.38, 2.9349, 5e-4), 'the printed pair implies 2.9349');
check(meanYearly > summedRatio && (9.92 / 3.38) > meanYearly,
  'the printed pair sits furthest toward the threefold claim of the three readings');
check(html.includes('durchschnittlich dreimal'), 'the page quotes verbatim the claim it is testing');
check(!html.includes('2.8080') && !html.includes('0.5040'),
  'the census figures are computed in the page, not hardcoded into its prose');
check(html.includes('not evidence that Semmelweis massaged'),
  'the page states the limit of the finding rather than implying misconduct');

const totalChecks = passed + failed;
if (failed > 0) {
  console.error(`FAIL ${passed}/${totalChecks}`);
  process.exitCode = 1;
} else {
  console.log(`PASS ${passed}/${totalChecks}`);
}
