#!/usr/bin/env node
/* Verify "The Gate Built by Love" (/strata/abandon-all-hope/). Offline, no network.
   Three layers of assertion:
     A. every canonical string (Italian lines, all 15 English line-9 renderings,
        commentary quotes, career attestation phrases) is present in the page HTML;
     B. every OCR-normalised reading shown on the page corresponds to a RAW string
        present in a committed source file under research/dante-gate/sources/
        (so each normalisation is auditable, none silent);
     C. the counts the page's prose relies on (0 of 15 begin "Abandon", 3 add a
        final "here", 2 keep "every") are recomputed here from the same table.
   Run: node research/dante-gate/verify.mjs */
import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const root = join(here, '..', '..');
const html = readFileSync(join(root, 'public', 'strata', 'abandon-all-hope', 'index.html'), 'utf8');

/* page haystack: tags removed two ways (joined and spaced), whitespace collapsed */
const collapse = s => s.replace(/\s+/g, ' ').trim();
const hayJoin = collapse(html.replace(/<[^>]+>/g, ''));
const haySpace = collapse(html.replace(/<[^>]+>/g, ' '));
const inPage = s => {
  const n = collapse(s);
  return hayJoin.includes(n) || haySpace.includes(n);
};

let pass = 0, fail = 0;
const misses = [];
const check = (group, ok, label) => {
  if (ok) pass++;
  else { fail++; misses.push([group, label]); }
};
const pageHas = (group, ...strs) =>
  strs.forEach(s => check(group, inPage(s), s.length > 90 ? s.slice(0, 90) + '…' : s));

/* ---------- A1. the Italian (SDI 1921, Vandelli), as shown in Instrument I ---------- */
pageHas('Italian SDI 1921',
  'Per me si va ne la città dolente,',
  'per me si va ne l’etterno dolore,',
  'per me si va tra la perduta gente.',
  'Giustizia mosse il mio alto fattore;',
  'fecemi la divina potestate,',
  'la somma sapienza e ’l primo amore.',
  'Dinanzi a me non fuor cose create',
  'se non etterne, e io etterna duro.',
  'Lasciate ogni speranza, voi ch’entrate.');

/* the same nine lines against the transcription JSON (from the page images),
   modulo the two disclosed normalisations: guillemets dropped, space after
   apostrophe closed, punctuation-spacing closed */
const itJson = JSON.parse(readFileSync(join(here, 'italian-text.json'), 'utf8'));
const sdi = itJson.find(e => e.year === 1921);
check('Italian JSON', !!sdi, 'SDI 1921 entry exists in italian-text.json');
if (sdi) {
  const normIt = s => collapse(s.replace(/[«»]/g, '').replace(/'/g, '’')
    .replace(/([’]) /g, '$1').replace(/ ([;:,.!])/g, '$1'));
  sdi.lines_1_9.split('\n').map(normIt).filter(Boolean).forEach(line =>
    check('Italian JSON↔page', inPage(line), line));
}
/* the two other PD editions' key readings, quoted in the apparatus/notes */
const witte = itJson.find(e => e.year === 1862);
const moore = itJson.find(e => e.year === 1894);
check('Witte 1862', !!witte && /ed io eterna duro/.test(witte.lines_1_9), 'Witte prints "ed io eterna duro"');
check('Witte 1862', !!witte && /Lasciate\s+ogni\s+speranza/.test(witte.lines_1_9), 'Witte prints "ogni speranza"');
check('Moore 1894', !!moore && /ed io eterno duro/i.test(moore.lines_1_9), 'Moore prints "eterno duro"');
check('Moore 1894', !!moore && /ogni speranza voi ch' ?entrate/i.test(moore.lines_1_9), 'Moore prints "ogni ... ch\'entrate"');

/* ---------- A2 + B. the fifteen hands: page shows CLEAN, source file holds RAW ---------- */
/* clean = as displayed (markers stripped); raw = regex the committed source
   excerpt must match (encodes the disclosed OCR normalisations). */
const HANDS = [
  ['Rogers 1782',   'Ye who here enter to return despair.', /Ye\s+who\s+here\s+enter\s+to\s+return\s+de[fs]pair/, 'rogers'],
  ['Boyd 1802',     'Here bid at once your lingering hope farewell', /Here\s+bid\s+at\s+once\s+your\s+lingering\s+hope\s+farewell/, 'boyd'],
  ['Cary 1814',     'All hope abandon ye who enter here.', /All\s+hope\s+abandon\s+ye\s+who\s+enter\s+here\./, 'cary'],
  ['Wright 1833',   'All hope abandon — ye who enter here.', /All\s+hope\s+abandon\s+—?\s*ye\s+who\s+enter\s+here/, 'wright'],
  ['Dayman 1843',   'Ye that are entering — all hope resign.', /Ye\s+that\s+are\s+entering\s+—?\s*all\s+hope\s+resign/, 'dayman'],
  ['Carlyle 1849',  'Leave all hope, ye that enter.', /Leave\s+all\s+hope[,y]\s+ye\S?\s*that\s+enter/, 'carlyle'],
  ['Cayley 1851',   'O you that enter me, all hope resign.', /O\s+you\s+that\s+enter\s+me,\s+all\s+hope\s+resign/, 'cayley'],
  ['Rossetti 1865', 'Leave off all hope, all ye that enter in.', /Leave\s+off\s+all\s+hope,\s+all\s+ye\s+that\s+enter\s+in/, 'rossetti'],
  ['Longfellow 1867','All hope abandon, ye who enter in!', /All\s+hope\s+abandon,\s+ye\s+who\s+enter\s+in!/, 'longfellow'],
  ['Sibbald 1884',  'Ye who make entrance, every hope resign!', /Ye\s+who\s+make\s+entrance,\s+every\s+hope\s+resign/, 'sibbald'],
  ['Plumptre 1886', 'Ye that pass in, all hope abandon ye.', /Ye\s+that\s+pass\s+in,\s+all\s+hope\s+abandon\s+ye/, 'plumptre'],
  ['Norton 1891',   'Leave every hope, ye who enter!', /Leave\s+every\s+hope,\s+ye\s+who\s+enter!/, 'norton'],
  ['Temple 1900',   'leave all hope, ye that enter.', /leave\s+all\s+hope,\s+ye\s+that\s+enter/, 'temple|okey|infernoofdanteal'],
  ['Langdon 1918',  'ALL HOPE ABANDON, YE THAT ENTER HERE!', /ALL\s+HOPE\s+ABANDON,\s+YE\s+THAT\s+ENTER\s+HERE!/, 'langdon'],
  ['Anderson 1921', 'Leave, ye that enter in, all hope behind!', /Leave,\s+ye\s+that\s+enter\s+in,\s+all\s+hope\s+behind!/, 'anderson'],
];
import { readdirSync } from 'node:fs';
const srcDir = join(here, 'sources');
const srcFiles = readdirSync(srcDir).filter(f => f.endsWith('.txt'));
const fileCache = new Map();
const readSrc = f => {
  if (!fileCache.has(f)) fileCache.set(f, readFileSync(join(srcDir, f), 'utf8'));
  return fileCache.get(f);
};
for (const [who, clean, rawRe, filePat] of HANDS) {
  check('page: ' + who, inPage(clean), clean);
  const pats = filePat.split('|');
  const candidates = srcFiles.filter(f => pats.some(p => f.toLowerCase().includes(p)));
  const hit = candidates.some(f => rawRe.test(readSrc(f).replace(/\s+/g, ' ')));
  check('raw: ' + who, hit, `no committed source file matching /${filePat}/ contains ${rawRe}`);
}

/* ---------- A3. commentary quotes (page ↔ commentary.json) ---------- */
const comm = JSON.parse(readFileSync(join(here, 'commentary.json'), 'utf8'));
const commHas = frag => comm.some(e => collapse(e.quote).includes(collapse(frag)));
const QUOTES = [
  'By a prosopopoeia, or figure of giving personality to inanimate things, Dante makes the Gate of Hell itself utter the dire words with which this canto opens.',
  'The three qualities here mentioned — power, wisdom, and love — represent the three Persons of the Trinity',
  'By potestate, sapienza, amore are indicated the Persons of the Trinity.',
  'St. Thomas Aquinas says that punishment when deserved is love.',
  'Patri attribuitur potentia, Filio sapientia, Spiritui sancto bonitas',
  'This canto begins with a repetition of sounds like the tolling of a funeral bell: dolente … dolore!',
  'Hell was created at the time of the fall of the rebellious angels, and at that time the only things that existed were the cose eterne, i.e. the angels, the heavens, and other imperishable things',
  'io eterno duro: ‘I endure everlastingly,’ eterno being adverbial. If eterna is read, it agrees with io, i.e. la porta of l. 11',
];
for (const q of QUOTES) {
  check('page: commentary', inPage(q), q.slice(0, 70) + '…');
  /* commentary.json normalises punctuation slightly differently (-- vs —, straight quotes);
     compare letters+digits only so the correspondence is still real, not cosmetic */
  const lettersOnly = s => collapse(s).replace(/[^\p{L}\p{N}]+/gu, ' ').trim().toLowerCase();
  const inJson = comm.some(e => lettersOnly(e.quote).includes(lettersOnly(q)));
  check('json: commentary', inJson, 'commentary.json holds: ' + q.slice(0, 60) + '…');
}

/* ---------- A4. the career attestations (page ↔ line-career.json ↔ evidence files) ---------- */
const career = JSON.parse(readFileSync(join(here, 'line-career.json'), 'utf8'));
/* The scope of the translation claim. Until the 2026-10-11 claims pass this check asserted
   ZERO published translations printing the modern wording, and the page said, unscoped, that
   "no classic translator wrote" it. John Ciardi's 1954 Inferno prints it (capitals, no comma).
   So: every translation recorded as printing it must be later than all eighteen the page
   checked (the latest, Anderson, is 1921); Ciardi's must be recorded with committed evidence
   that holds the line; the page must name him; and the unscoped wordings must be gone. */
{
  const prints = career.translations_that_print_it;
  const checkedMax = Math.max(...HANDS.map(([who]) => +who.match(/\d{4}/)[0]),
    ...career.translations_checked_exact_wordings.map(t => +t.year));
  const ciardi = prints.find(t => /Ciardi/.test(t.translator) && t.year === 1954);
  const ciardiFile = ciardi && ciardi.evidence_file.replace(/^sources\//, '');
  const ciardiEv = !!ciardiFile && srcFiles.includes(ciardiFile)
    && /ABANDON ALL HOPE YE WHO ENTER HERE/.test(readSrc(ciardiFile));
  /* the dated Corrected note, and the claims record that scripts/assay-fold.mjs folds in
     (<!--aw-assay--> block, which quotes each corrected claim word for word), may name the old
     wording; every other line of the page may not. The text is read twice: with tags stripped
     (prose split by markup) and with tags kept, because two of these wordings only ever stood
     inside meta/og/twitter content attributes, which stripping whole tags would throw away. */
  const htmlClaims = html.replace(/<!--aw-assay:start-->[\s\S]*?<!--aw-assay:end-->/g, '')
    .replace(/<p>Corrected \d{4}-\d\d-\d\d[\s\S]*?<\/p>/g, '');
  const hayClaims = collapse(htmlClaims.replace(/<[^>]+>/g, ' '));
  const rawClaims = collapse(htmlClaims);
  const unscoped = ['no classic translator wrote', 'not what any classic translator wrote',
    'none of its classic translators wrote', 'classic translators never wrote',
    'belongs to no one'].filter(s => hayClaims.includes(s) || rawClaims.includes(s));
  check('career', prints.length >= 1 && prints.every(t => t.year > checkedMax) && ciardiEv
    && inPage('John Ciardi’s 1954') && unscoped.length === 0,
    `line-career.json records Ciardi 1954 (with evidence) as the translation printing the modern wording, later than every one checked (to ${checkedMax}), and the page states the claim with that scope` +
    (unscoped.length ? ` (unscoped wording still on the page: ${unscoped.join(' | ')})` : ''));
}
const ATTS = [
  ['1885 St. Paul Daily Globe', 'Regarding marriage, it will be written above the gates', /Abandon\s+all\s+hope,\s+ye\s+who\s+enter\s+here/i, 'stpaulglobe-1885'],
  ['1891 Vermont Phoenix', 'the inscription which Dante saw over the doorway of hell', /Abandon\s+all\s+hope,\s+ye\s+who\s+enter\s+here/i, 'vtphoenix-1891'],
  ['1839 Morning Herald', 'the concluding words of Dante’s celebrated inscription', /Abandon\s+hope\.\s+All\s+ye\s+who\s+enter\s+here/i, 'morningherald-1839'],
  ['1851 Sunday Dispatch', 'the well remembered inscription of Dante over the gates of Tartarus', /Abandon\s+hope,\s+all\s+ye\s+who\s+enter\s+here/i, 'sundaydispatch-1851'],
  ['1858 Weekly Pioneer', 'would have been more appropriate', /Abandon\s+hope,?.?\s+all\s+ye\s+who\s+enter\s+here/i, 'weeklypioneerdemocrat-1858'],
];
for (const [who, ctxFrag, phraseRe, filePat] of ATTS) {
  check('page: ' + who, inPage(ctxFrag), ctxFrag);
  const candidates = srcFiles.filter(f => f.includes(filePat));
  const ok = candidates.length > 0 && candidates.some(f => phraseRe.test(readSrc(f).replace(/\s+/g, ' ')));
  check('evidence: ' + who, ok, `${filePat} file exists and contains the phrase`);
}
/* the LoC links shown must be the verified ones */
pageHas('career links',
  'https://www.loc.gov/resource/sn90059522/1885-11-22/ed-1/?sp=4',
  'https://www.loc.gov/resource/sn83030312/1839-05-28/ed-1/?sp=3',
  'https://www.loc.gov/resource/sn83030362/1851-04-06/ed-1/?sp=1');

/* ---------- C. the counts the prose relies on ---------- */
const beginsAbandon = HANDS.filter(([, clean]) => /^abandon/i.test(clean)).length;
check('counts', beginsAbandon === 0, `0 of 15 begin with "Abandon" (got ${beginsAbandon})`);
const endsHere = HANDS.filter(([, clean]) => /enter here[.!”"]*$/i.test(clean)).length;
check('counts', endsHere === 3, `3 of 15 end "…enter here" (got ${endsHere}) — Cary, Wright, Langdon`);
const keepsEvery = HANDS.filter(([, clean]) => /\bevery\b/i.test(clean)).length;
check('counts', keepsEvery === 2, `2 of 15 keep "every" (got ${keepsEvery}) — Sibbald, Norton`);
check('counts', HANDS.length === 15, `15 hands (got ${HANDS.length})`);

/* ---------- report ---------- */
console.log(`The Gate Built by Love — verify: ${pass}/${pass + fail} checks pass`);
if (fail) {
  console.error(`\n${fail} FAILING:`);
  for (const [g, s] of misses) console.error(`  [${g}] ${s}`);
  process.exit(1);
}
console.log('Every quoted line is present and traceable to a committed source. ✓');
