#!/usr/bin/env node
// verify.mjs — the offline check for "Odi et amo" (Catullus 85).
//
// House rule: every factual claim is checked and the check is shown.
// This script:
//   1. Collates the Latin against TWO independent public-domain editions
//      (Burton/Smithers 1894, Müller text; and Ellis's Oxford text) and asserts
//      they agree on every word — differing only in one mark of punctuation.
//   2. Holds the part-of-speech table and asserts the headline counts
//      (14 words · 8 verbs · 0 nouns · 0 adjectives) AND that the tagged words,
//      in order, reconstruct the couplet exactly.
//   3. Asserts the immersive page reproduces the Latin and all ten English
//      renderings (nine translations; Cranstoun gives two) verbatim.
//   4. Checks the morpheme split of `excrucior` is present and labelled passive.
//
// Run: node research/catullus-85/verify.mjs   (exit 0 = all pass)

import { readFileSync } from 'node:fs';

const HERE = new URL('.', import.meta.url).pathname;
const PAGE = readFileSync(HERE + '../../public/strata/odi-et-amo/index.html', 'utf8');
const rd = (f) => readFileSync(HERE + f, 'utf8');

let pass = 0, fail = 0;
const ok  = (m) => { pass++; console.log('  ✓ ' + m); };
const bad = (m) => { fail++; console.log('  ✗ ' + m); };

// Normalize HTML to plain text: drop tags, turn the literal "\n" inside the JS
// data strings into spaces, decode the few entities used, collapse whitespace.
const norm = (s) => s
  .replace(/<[^>]+>/g, '')
  .replace(/\\n/g, ' ')
  .replace(/&nbsp;|&#8202;/g, ' ')
  .replace(/&mdash;/g, '—')
  .replace(/&amp;/g, '&')
  .replace(/\s+/g, ' ')
  .trim();
const pagePlain = norm(PAGE);
const has = (frag) => pagePlain.includes(norm(frag));

// ---------------------------------------------------------------------------
console.log('\n1. The Latin — two witnesses, collated');
{
  const stripLatin = (f) => rd(f).split('\n').filter(l => l && !l.startsWith('#')).join(' ')
    .replace(/\s+/g, ' ').trim();
  const burton = stripLatin('latin-burton-g20732.txt');
  const ellis  = stripLatin('latin-ellis-g23294.txt');
  // Reduce each to a comparable word sequence: lower-case, strip punctuation.
  const words = (s) => s.toLowerCase().replace(/[.,:;]/g, '').split(/\s+/).filter(Boolean);
  const wb = words(burton), we = words(ellis);
  const sameWords = wb.length === we.length && wb.every((w, i) => w === we[i]);
  if (sameWords) ok(`both editions agree on all ${wb.length} words (case/punctuation aside)`);
  else bad(`Latin witnesses disagree on wording:\n      Burton: ${wb.join(' ')}\n      Ellis:  ${we.join(' ')}`);
  // The known editorial variant: full stop (Burton/Müller) vs colon (Ellis) after "amo".
  if (burton.includes('amo.') && ellis.includes('amo:')) ok('the one real variant is present: "amo." (Müller) vs "amo:" (Ellis)');
  else bad('expected the amo. / amo: punctuation variant between the two editions');
  // The page shows the full-stop form.
  if (has('Odi et amo. quare id faciam, fortasse requiris.')) ok('page shows the hexameter verbatim');
  else bad('page is missing the hexameter');
  if (has('nescio, sed fieri sentio et excrucior')) ok('page shows the pentameter verbatim');
  else bad('page is missing the pentameter');
}

// ---------------------------------------------------------------------------
console.log('\n2. The parse — 14 words, 8 verbs, 0 nouns, 0 adjectives');
{
  // word, part of speech ('verb' tagged here are finite verbs + the infinitive)
  const TABLE = [
    ['Odi', 'verb'], ['et', 'conj'], ['amo', 'verb'], ['quare', 'adv'],
    ['id', 'pron'], ['faciam', 'verb'], ['fortasse', 'adv'], ['requiris', 'verb'],
    ['nescio', 'verb'], ['sed', 'conj'], ['fieri', 'verb'], ['sentio', 'verb'],
    ['et', 'conj'], ['excrucior', 'verb'],
  ];
  const count = (p) => TABLE.filter(([, q]) => q === p).length;
  const checks = [
    ['words', TABLE.length, 14],
    ['verbs', count('verb'), 8],
    ['conjunctions', count('conj'), 3],
    ['adverbs', count('adv'), 2],
    ['pronouns', count('pron'), 1],
    ['nouns', count('noun'), 0],
    ['adjectives', count('adj'), 0],
  ];
  for (const [label, got, want] of checks) {
    if (got === want) ok(`${label}: ${got}`);
    else bad(`${label}: expected ${want}, got ${got}`);
  }
  // Reconstruction: the tagged words, in order, must equal the couplet's words.
  const couplet = 'Odi et amo quare id faciam fortasse requiris nescio sed fieri sentio et excrucior';
  const rebuilt = TABLE.map(([w]) => w).join(' ');
  if (rebuilt === couplet) ok('the 14 tagged words reconstruct the couplet in order');
  else bad(`reconstruction mismatch:\n      ${rebuilt}\n      ${couplet}`);
  // The two passives are exactly fieri and excrucior.
  if (PAGE.includes('"fieri",   pos: "verb",  k: "vp"') || PAGE.match(/w:\s*"fieri"[^}]*k:\s*"vp"/) )
    ok('fieri tagged passive in the page data'); else bad('fieri not tagged passive on page');
  if (PAGE.match(/w:\s*"excrucior"[^}]*k:\s*"vp"/)) ok('excrucior tagged passive in the page data');
  else bad('excrucior not tagged passive on page');
  // And the page advertises the counts to the reader.
  for (const claim of ['<b>8</b> verbs', '<b>0</b> nouns', '<b>14</b> words'])
    if (PAGE.includes(claim)) ok(`page states: ${claim.replace(/<[^>]+>/g, '')}`); else bad(`page omits headline: ${claim}`);
}

// ---------------------------------------------------------------------------
console.log('\n3. excrucior — the morpheme split & the passive');
{
  for (const seg of ['ex', 'cruci', 'or'])
    if (PAGE.includes(`data-k="${seg}"`)) ok(`segment present: ${seg}`); else bad(`segment missing: ${seg}`);
  if (has('the wooden frame on which criminals were crucified')) ok('crux gloss (cross) present');
  else bad('crux gloss missing');
  if (has('I am tortured / crucified')) ok('excrucior glossed as passive "I am crucified"');
  else bad('excrucior passive gloss missing');
}

// ---------------------------------------------------------------------------
console.log('\n4. The ten renderings — verbatim on the page');
{
  // Canonical transcriptions (mark tags removed; see SOURCES.md for provenance).
  const REN = [
    ['Burton 1894',     'Hate I, and love I. Haps thou’lt ask me wherefore I do so. Wot I not, yet so I do feeling a torture of pain.'],
    ['Smithers 1894',   'I hate and I love. Wherefore do I so, peradventure thou askest. I know not, but I feel it to be thus and I suffer.'],
    ['Ellis 1871',      'Half I hate, half love. How so? one haply requireth. Nay, I know not; alas feel it, in agony groan.'],
    ['Cranstoun i',     'I hate and love. “Why do I so?” Perhaps you ask. I can’t explain: The bitter fact I only know, And torture racks my brain.'],
    ['Cranstoun ii',    'I hate and love. Why so? I cannot tell: I feel it; and endure the pains of hell.'],
    ['Martin 1861',     'Hate and love — wherefore I cannot tell. But by my tortures know the fact too well.'],
    ['Lamb 1821',       'Tho’ I hate, yet I love! — you’ll perhaps ask me, how? I can’t tell; but I’m vext, and I feel that I do.'],
    ['Kelly 1854',      'I hate and love. You ask perhaps how can that be. I know not; but I feel that it is so, and I am tortured.'],
    ['Cornish 1913',    'I hate and love. Why I do so, perhaps you ask. I know not, but I feel it, and I am in torment.'],
    ['Macnaghten 1899', 'I hate the while I love: how this be so, Perchance you seek to know: Ah! there I am not wise. Only ’tis so I feel and agonise.'],
  ];
  for (const [who, text] of REN) {
    if (has(text)) ok(`${who} reproduced verbatim`);
    else {
      bad(`${who} does NOT match verbatim`);
      const a = norm(text);
      let i = 0; while (i < a.length && pagePlain.includes(a.slice(0, i + 1))) i++;
      console.log('      first divergence near: …' + a.slice(Math.max(0, i - 28), i + 28) + '…');
    }
  }
}

// ---------------------------------------------------------------------------
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ ' + fail + ' FAILED'} — ${pass} checks passed, ${fail} failed.`);
process.exit(fail === 0 ? 0 : 1);
