// verify.mjs — the record behind the stratum
// "The Dancing Was Real. The Death Toll Came Later." (/strata/the-dancing-plague/).
//
// This is a verification-limits page, not a physics page: the "numbers" are the
// provenance stamps and the one piece of arithmetic the popular death toll is
// actually made of. This script has two jobs, exactly like the house pattern:
//
//   (a) Recompute selected illustrative totals and thresholds. Waller's 2009
//       article reports a chronicle's rate; Pennant-Rea's 2018 extrapolation
//       is conditional. The model assumes that rate and chooses the days.
//   (b) Read the page's ledger data and check its source groups, selected strings,
//       and example-specific mechanism updates. These checks do not independently
//       establish the history or verify every occurrence of a figure.
//
//   run:  node research/the-dancing-plague/verify.mjs
//
// SOURCES for the asserted figures (all linked in the page footer):
//   - "Dancing plague of 1518", Wikipedia — contemporary attestation (physician
//     notes, cathedral sermons, chronicles, city-council notes); count 50–400;
//     ">30 within days"; and the explicit statement that the Strasbourg sources of
//     the time did NOT mention the number of deaths or even if there were fatalities.
//   - Encyclopaedia Britannica, "Dancing plague of 1518" — "30 within a week",
//     "as many as 400"; deaths described only vaguely, no figure, no "15/day".
//   - The Public Domain Review, "The Dancing Plague of 1518" — the documentary
//     chain (Specklin 16th c.; Imlin chronicle & the ~400; the lost poem via
//     Johann Schilter; Goldmeyer 1636; Paracelsus after his 1526 visit) and the
//     "as many as fifteen … IF such a daily death rate was true … into the hundreds".
//   - John Waller, The Lancet 373:624–625 (2009) — Aachen 1374; the Rhine/Moselle
//     recurrence corridor; MPI framed explicitly as a hypothesis; ergot objections.
//   - "Dancing mania", Wikipedia — Rhineland belief-corridor; St. Vitus/St. John.
//
// No dependencies. node: builtins only.

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

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};

// ─────────────────────────────────────────────────────────────────────────────
// 1. THE PROVENANCE LEDGER — which claims are in the contemporary 1518 record
// ─────────────────────────────────────────────────────────────────────────────
// Source groups: 0 contemporary evidence, 1 Paracelsus after his 1526 visit,
// 2 Specklin and Imlin (Imlin's writing date unestablished), 3 Schilter,
// 4 Waller's 2009 rate report and Pennant-Rea's 2018 conditional.
const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = join(here, '..', '..', 'public', 'strata', 'the-dancing-plague', 'index.html');
let html = '';
try { html = readFileSync(htmlPath, 'utf8'); }
catch (e) { ok('index.html is present and readable', false, e.message); }

function pageArray(name) {
  const match = html.match(new RegExp('var ' + name + ' = (\\[[\\s\\S]*?\\n    \\]);'));
  if (!match) { ok('page array ' + name + ' is present', false); return []; }
  return runInNewContext('(' + match[1] + ')', {}, { timeout: 1000 });
}
const CLAIMS = pageArray('CLAIMS');
const expectedTiers = {
  danced:0, crowd:2, policy:0, pilgrimage:0, staging:2, ritual:2,
  name:1, start:2, fourhundred:2, hundreds:3, rate:4, death:4,
};
ok('each ledger row has its reviewed source group',
  CLAIMS.length === Object.keys(expectedTiers).length &&
  new Set(CLAIMS.map(c => c.key)).size === CLAIMS.length &&
  CLAIMS.every(c => expectedTiers[c.key] === c.tier));
const standingAt = (t) => CLAIMS.filter((c) => c.tier <= t).length;

console.log('\n— the provenance ledger: claims standing at each acceptance tier —');
const standings = [0, 1, 2, 3, 4].map(standingAt);
console.log('  tier 0..4 →', standings.join(', '), 'of', CLAIMS.length);
ok('12 separately sourced claims in the ledger', CLAIMS.length === 12, `${CLAIMS.length}`);
ok('at the STRICT 1518 setting, exactly 3 of 12 claims stand', standingAt(0) === 3,
   `${standingAt(0)}/12`);
ok('the strict rows are dancing, broad policy and pilgrimage',
   CLAIMS.filter((c) => c.tier === 0).map((c) => c.key).join(',') ===
   'danced,policy,pilgrimage');
ok('the death-toll claim is the LAST to appear (modern tier only)',
   CLAIMS.find((c) => c.key === 'death')?.tier === 4);
ok('standing count is monotone non-decreasing as you accept later sources',
   standings.every((v, i) => i === 0 || v >= standings[i - 1]));
ok('standings are exactly 3,4,9,10,12', standings.join(',') === '3,4,9,10,12');

// ─────────────────────────────────────────────────────────────────────────────
// 2. THE DEATH TOLL — a product of one assumed rate, not a count
// ─────────────────────────────────────────────────────────────────────────────
// The contemporary Strasbourg record mentions NO deaths. The famous toll is
// Pennant-Rea conditionally extrapolates hundreds; Waller earlier reports a
// chronicle's rate. This illustration multiplies that assumed rate by chosen days.
const CONTEMPORARY_DEATHS = 0;      // sourced: the 1518 record mentions none
const RATE = 15;                    // reported rate, assumed for this illustration
const daysToReach = (n) => Math.ceil(n / RATE);
const toll = (d) => RATE * d;

console.log('\n— the death toll is 15/day × (a guessed number of days) —');
ok('contemporary Strasbourg record: 0 deaths documented', CONTEMPORARY_DEATHS === 0);
ok('"about 100 dead" needs only 7 days at 15/day', daysToReach(100) === 7,
   `⌈100/15⌉=${daysToReach(100)}`);
ok('15/day × 7 days = 105 (clears 100)', toll(7) === 105 && toll(7) >= 100, `${toll(7)}`);
ok('the "400" figure needs 27 days at 15/day', daysToReach(400) === 27,
   `⌈400/15⌉=${daysToReach(400)}`);
ok('15/day × 27 days = 405 (clears 400)', toll(27) === 405 && toll(27) >= 400, `${toll(27)}`);
ok('the toll is a pure product of the rate (0 days → 0, no independent count)',
   toll(0) === 0);

// ─────────────────────────────────────────────────────────────────────────────
// 3. CROWD SIZE AND DURATION: reported figures and a chosen span
// ─────────────────────────────────────────────────────────────────────────────
const WITHIN_DAYS = 30;   // Imlin: about 34 within four days, printed by Martin p. 119
const PEAK = 400;         // "as many as 400" (Imlin) ; range 50–400
const LOW = 50;
// Chosen model endpoints, not a sourced exact duration: July 14 to September 7.
const spanDays = (Date.UTC(1518, 8, 7) - Date.UTC(1518, 6, 14)) / 86400000;
const spanWeeks = spanDays / 7;

console.log('\n— crowd size and duration —');
ok('more than 30 dancing within days', WITHIN_DAYS === 30);
ok('peak "as many as 400"; honest range 50–400', PEAK === 400 && LOW === 50);
ok('chosen July 14 to September 7 span = 55 days', spanDays === 55, `${spanDays} days`);
ok('that is roughly two months (~7.9 weeks)', spanWeeks > 7.5 && spanWeeks < 8.2,
   `${spanWeeks.toFixed(2)} wks`);

// ─────────────────────────────────────────────────────────────────────────────
// 4. THE CAUSAL CONTEST — no candidate meets every row; refuse to crown one
// ─────────────────────────────────────────────────────────────────────────────
// Mirrors the page grid. Values: 'met' | 'part' | 'fail'.
const TESTS = ['days', 'mass', 'dancing', 'geo', 'recur'];
const GRID = {
  ergot: { days: 'fail', mass: 'fail', dancing: 'fail', geo: 'fail', recur: 'fail' },
  mpi:   { days: 'met',  mass: 'met',  dancing: 'part', geo: 'met',  recur: 'met'  },
  curse: { days: 'part', mass: 'part', dancing: 'met',  geo: 'met',  recur: 'met'  },
};
const count = (id, v) => TESTS.filter((t) => GRID[id][t] === v).length;
const allMet = (id) => TESTS.every((t) => GRID[id][t] === 'met');

console.log('\n— cause × evidence: none fits every row —');
ok('ergot is the weakest fit — it fails all 5 rows', count('ergot', 'fail') === 5,
   `fails=${count('ergot', 'fail')}`);
ok('but ergot is not "crowned" the winner either — it meets nothing', count('ergot', 'met') === 0);
ok('MPI is the best fit — fails no row', count('mpi', 'fail') === 0);
ok('yet MPI leaves exactly one row amber, and it is "why DANCING?"',
   count('mpi', 'part') === 1 && GRID.mpi.dancing === 'part');
ok('NO candidate meets every row (the page refuses to settle the cause)',
   !allMet('ergot') && !allMet('mpi') && !allMet('curse'));
ok('the saint\'s-curse frame "explains" dancing/geography/recurrence but not the mechanism',
   GRID.curse.dancing === 'met' && GRID.curse.days === 'part' && GRID.curse.mass === 'part');

// recurrence anchor
const AACHEN = 1374;
ok('earlier outbreak anchored at Aachen 1374', AACHEN === 1374);

// provenance anchor years used on the page
const YEARS = { contemporary: 1518, paracelsusVisit: 1526, waller: 2009, pennantRea: 2018 };
ok('provenance anchors: 1518 · 1526 visit · 2009 report · 2018 conditional',
   YEARS.contemporary === 1518 && YEARS.paracelsusVisit === 1526 &&
   YEARS.waller === 2009 && YEARS.pennantRea === 2018);

// ─────────────────────────────────────────────────────────────────────────────
// 5. PARITY — the shipped page must contain the same figures, names, sources
// ─────────────────────────────────────────────────────────────────────────────
console.log('\n— the shipped page contains the same figures and provenance —');

const has = (needle) => html.includes(needle);
const contains = (label, needle) => ok(label, has(needle), needle.length > 42 ? '' : `"${needle}"`);

if (html) {
  // the headline epistemic figures
  contains('page shows "3 of 12 claims stand"', '3 of 12 claims stand');
  contains('page shows the toll product 15/day × 7 = 105', '15</b>/day &times; <b>7</b> days = <b>105</b>');
  contains('page shows the contemporary count is 0', 'counted in the 1518 record: <span class="zero">0</span>');
  contains('page shows "100 dead" needs 7 days', '100 dead</strong>" in just <strong>7 days</strong>');
  contains('page shows the 400-in-27-days recompute', '15/day &times; 27 = 405');
  contains('page states the record mentions no deaths', 'no deaths at all');
  contains('page shows the ~55-day / ~8-week span', '55 days (~8 weeks)');
  // crowd figures
  contains('page shows >30 within days', '30 dancing within days');
  contains('page shows the 50–400 range', '50&ndash;400');
  contains('page shows "as many as 400"', 'As many as 400');
  // provenance stamps
  contains('page dated 2026-07-09 (published)', '"datePublished":"2026-07-09"');
  contains('page dated 2026-10-14 (modified)', '"dateModified":"2026-10-14"');
  contains('year 1518', '1518');
  contains('Paracelsus after 1526 visit', 'AFTER 1526');
  contains('Goldmeyer 1636', '1636');
  contains('Waller 2009 rate report', 'WALLER, LANCET 2009');
  contains('Pennant-Rea 2018 conditional', 'PENNANT-REA, PUBLIC DOMAIN REVIEW, 2018');
  contains('Lancet 2009', '(2009)');
  contains('Aachen 1374', '1374');
  // the named, later-only elements the strict setting strips
  contains('names Frau Troffea (flagged later/disputed)', 'Frau Troffea');
  contains('flags the name as disputed', 'NAME DISPUTED');
  contains('names Paracelsus', 'Paracelsus');
  contains('names the Imlin chronicle', 'Imlin');
  contains('names Specklin', 'Specklin');
  contains('names Goldmeyer', 'Goldmeyer');
  contains('names Schilter', 'Schilter');
  contains('names St. Vitus', 'St. Vitus');
  contains('names Saverne', 'Saverne');
  // Pennant-Rea's conditional, distinct from Waller's earlier rate report.
  contains('quotes Pennant-Rea\'s exact conditional words', 'if such a daily death rate was true');
  // the causal contest, un-crowned
  contains('ergot named as weakest, not disproven', 'not disproven');
  contains('MPI named most-accepted, not fact', 'most-accepted');
  contains('mass psychogenic illness present', 'Mass psychogenic illness');
  contains('shape-of-fears result present', 'borrows the');
  contains('Tanganyika 1962 comparison case', 'Tanganyika, 1962');
  // the honest verdict
  contains('final verdict line present', 'Unresolved cause');
  // a11y / house requirements
  contains('aria-live status readout present', 'role="status" aria-live="polite"');
  contains('reduced-motion guard present', 'prefers-reduced-motion');
  contains('canvas is aria-hidden', 'canvas id="timeline" aria-hidden="true"');
  contains('self-hosted fonts, no third party', '/fonts/fonts.css');
  contains('canonical url present', 'https://artwaste.land/strata/the-dancing-plague/');
  contains('load-bearing closing tags present', '</script>\n</body>\n</html>');
}

// The comparison must change its proposed mechanism with the selected example.
const FEARS = pageArray('FEARS');
const gas = FEARS.find(f => f.id === 'gas');
ok('toxic-gas comparison uses acute anxiety, not a fixed trance label',
  !!gas && gas.mechanism.includes('acute anxiety') && !/trance|dissociative/.test(gas.mechanism));
ok('four comparison examples have individual mechanisms',
  FEARS.length === 4 && FEARS.every(f => typeof f.mechanism === 'string') &&
  new Set(FEARS.map(f => f.mechanism)).size === 4);
const fearUpdate = html.match(/    function selectFear\(id\) \{[\s\S]*?\n    \}/);
const ledgerUpdate = html.match(/    function updateLedger\(t\) \{[\s\S]*?\n    \}/);
if (fearUpdate && ledgerUpdate) {
  const env = {
    FEARS, CLAIMS, TIERS: pageArray('TIERS'),
    elFF:{}, elFS:{}, elFW:{}, elFM:{}, elTierNow:{}, elRoMain:{}, elRoSub:{},
    document:{ querySelectorAll: () => [] },
    rowEls: CLAIMS.map(() => ({ classList:{ toggle() {} }, querySelector: () => ({}) })),
  };
  for (const f of FEARS) {
    runInNewContext(fearUpdate[0] + '; selectFear(' + JSON.stringify(f.id) + ');', env, { timeout:1000 });
    ok('selecting ' + f.id + ' updates the displayed mechanism', env.elFM.textContent === f.mechanism);
  }
  for (let t = 0; t <= 4; t++) {
    runInNewContext(ledgerUpdate[0] + '; updateLedger(' + t + ');', env, { timeout:1000 });
    ok('tier ' + t + ' displays its actual standing count',
      env.elRoMain.textContent.endsWith(standingAt(t) + ' of 12 claims stand.'));
  }
} else {
  ok('page update functions are present', false);
}

// ─────────────────────────────────────────────────────────────────────────────
const total = fails === 0;
console.log(`\n${total ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(total ? 0 : 1);
