#!/usr/bin/env node
// Verifier for the immersive stratum "The Sinister Hand"
// (public/strata/the-sinister-hand/index.html).
//
// The page makes exactly one class of quantitative claim — the tallies in the
// "check" panel: how many entries are on the wall, how many carry the
// right-good / left-bad asymmetry, how many are documented reversals, and how
// many everyday English words descend from these left/right roots. Every one of
// those is computed live in the browser from a single DATA array. This script
// reads that SAME array straight out of the HTML (so the two cannot drift),
// recomputes the tallies, and asserts:
//   * the counts match what the page's prose and check-panel assert;
//   * every card carries a real https:// source URL;
//   * the six "English words we still speak" are exactly the ones named.
// It verifies the ARITHMETIC and the SOURCING scaffold — not the etymologies
// themselves, which are quotations checked by hand against the sources in
// README.md (etymonline / Wiktionary / named scholarly works).

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

const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = join(here, '..', '..', 'public', 'strata', 'the-sinister-hand', 'index.html');
const html = readFileSync(htmlPath, 'utf8');

// ── pull the DATA array literal out of the page and evaluate just that ──────
const m = html.match(/var DATA = (\[[\s\S]*?\n\s*\]);/);
if (!m) { console.error('FAIL: could not locate the DATA array in the page.'); process.exit(1); }
let DATA;
try { DATA = Function('return (' + m[1] + ');')(); }
catch (e) { console.error('FAIL: DATA array did not evaluate:', e.message); process.exit(1); }

let ok = true;
const check = (cond, msg) => { console.log((cond ? '  ok   ' : '  FAIL ') + msg); if (!cond) ok = false; };

// ── recompute the tallies ───────────────────────────────────────────────────
const total   = DATA.length;
const fits    = DATA.filter(d => d.fits).length;
const flips   = DATA.filter(d => d.flip).length;
const engSum  = DATA.reduce((s, d) => s + (d.engWords || 0), 0);
const pct     = Math.round(1000 * fits / total) / 10;

// distinct languages among the "fits" cards (Latin appears again only as a reversal)
const fitLangs = new Set(DATA.filter(d => d.fits).map(d => d.lang));
const wallLangs = new Set(DATA.map(d => d.lang.startsWith('Latin') ? 'Latin' : d.lang));

console.log('The Sinister Hand — verifier\n');
console.log(`  entries on the wall .......... ${total}`);
console.log(`  carry the asymmetry (fits) ... ${fits}  (${pct}% of the wall)`);
console.log(`  documented reversals ......... ${flips}`);
console.log(`  English words borrowed ....... ${engSum}\n`);

// ── assertions (these mirror the numbers written into the page) ─────────────
check(total === 15, `wall holds 15 entries (got ${total})`);
check(wallLangs.size === 14, `wall holds 14 distinct languages (got ${wallLangs.size})`);
check(fits === 12,  `12 entries carry the right-good/left-bad asymmetry (got ${fits})`);
check(flips === 3,  `3 documented reversals (got ${flips})`);
check(pct === 80,   `that is 80.0% of the wall (got ${pct})`);
check(engSum === 6, `6 everyday English words descend from these roots (got ${engSum})`);
check(fitLangs.size === 12, `the 12 fits cards are 12 distinct languages (got ${fitLangs.size})`);
check(flips + fits === total, `every entry is either a "fits" language or a reversal (${fits}+${flips}=${total})`);

// the six English words, exactly
const engWords = DATA.filter(d => d.eng).flatMap(d => d.eng.split(',').map(s => s.trim()));
const expected = ['sinister','dexterous','dexterity','ambidextrous','gauche','adroit'];
check(engWords.length === 6, `exactly 6 English derivatives listed (got ${engWords.length})`);
check(expected.every(w => engWords.includes(w)),
  `the six words are: ${expected.join(' · ')}`);
// and their engWords counts sum to the same 6 (no double-count)
check(DATA.filter(d => d.eng).reduce((s,d)=>s+d.engWords,0) === 6,
  `engWords counts agree with the derivative list`);

// ── every card is sourced ───────────────────────────────────────────────────
const unsourced = DATA.filter(d => !/^https:\/\/\S+$/.test(d.srcUrl || ''));
check(unsourced.length === 0,
  `every entry carries an https:// source (${unsourced.length} missing)`);
if (unsourced.length) unsourced.forEach(d => console.log('       no source: ' + d.lang));

// every reversal has both a flip line (for "where it breaks") and a note
const badFlip = DATA.filter(d => d.flip && (!d.note || d.fits));
check(badFlip.length === 0, `each reversal is flagged fits:false and carries a note`);

// the page's check panel builds its line from the same counts (guard against drift)
check(html.includes("' languages + '") && html.includes("' documented reversals)"),
  `the check-panel line is templated from fitsAll + flips (not a hard-coded number)`);
// These are copy checks; the cited studies establish the prevalence and its limits.
const handedness = html.match(/<h2 id="why-the-left-hand-lost">[\s\S]*?<\/p>/)?.[0] || '';
check(handedness.includes('overall left-handedness at <strong>10.6%</strong>') &&
      handedness.includes('rates vary across populations and tasks'),
  `the prose separates the overall left-handed estimate from population and task variation`);
check(handedness.includes('do not establish') && handedness.includes('one precise rate of general handedness across prehistory'),
  `the archaeological evidence is not assigned a universal general-handedness rate`);

console.log('\n' + (ok ? 'PASS — every tally on the page recomputes and every card is sourced.'
                       : 'FAIL — see above.'));
process.exit(ok ? 0 : 1);
