#!/usr/bin/env node
// verify.mjs — the offline check for "The Tales That Were Never There".
//
// This script compares the eight local excerpt files with the page after stripping
// display tags and normalizing whitespace. It checks local agreement, not external
// source accuracy. SOURCES.md records excerpt boundaries and normalization; the
// assay record names the separate source readings. The remaining checks require
// the corrected historical statements and the three instruments' key strings.
//
// Run: node research/the-tales-that-were-never-there/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/the-tales-that-were-never-there/index.html', 'utf8');
const rd = (f) => readFileSync(HERE + f, 'utf8').trim();

// Strip tags, decode the few entities the page uses, collapse whitespace.
const norm = (s) => s
  .replace(/<[^>]+>/g, '')
  .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  .replace(/&quot;/g, '"').replace(/&#39;/g, "'")
  .replace(/\s+/g, ' ')
  .trim();
// Old wording in the Corrections note must not satisfy a current-content check.
const currentPage = PAGE.replace(/<section\b[^>]*id="corrections"[^>]*>[\s\S]*?<\/section>/, '');
const pagePlain = norm(currentPage);
const has = (needle) => pagePlain.includes(norm(needle));

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

const PASSAGES = [
  ['Fisherman · Grub Street 1706', 'fisherman-grubstreet-1706.txt'],
  ['Fisherman · Lane 1839',        'fisherman-lane-1839.txt'],
  ['Fisherman · Payne 1882',       'fisherman-payne-1882.txt'],
  ['Fisherman · Burton 1885',      'fisherman-burton-1885.txt'],
  ['Aladdin · Galland Fr 1806',    'aladdin-galland-fr-1806.txt'],
  ['Aladdin · Galland En 1909',    'aladdin-galland-en-1909.txt'],
  ['Aladdin · Burton 1887',        'aladdin-burton-1887.txt'],
  ['Aladdin · Payne 1889',         'aladdin-payne-1889.txt'],
];

console.log('\n1. Eight local excerpt files match the page after tag and whitespace normalization');
for (const [label, file] of PASSAGES) {
  const src = norm(rd(file));
  if (pagePlain.includes(src)) ok(label + ': local excerpt matches (' + src.length + ' chars)');
  else {
    bad(label + ': local excerpt does not match');
    // help future debugging: show the first divergence point
    const head = src.slice(0, 40);
    console.log('      looked for: ' + head + '…');
  }
}

console.log('\n2. The record-corrections are stated, with their anchors');
const CLAIMS = [
  ['earlier surviving witnesses distinguished from Diyab\'s unavailable Arabic Aladdin', ["Aladdin & Ali Baba have no known surviving Arabic witness older than Galland's French.", "Galland's diary records Diyāb's Arabic Aladdin text, now unavailable."]],
  ['the China setting (the orphan tale is not even Arabian)', 'a kingdom of China'],
  ['Aladdin published in 1712 and Ali Baba in 1717', ["Aladdin was printed in Galland's volumes IX–X, 1712", 'Ali Baba followed in 1717']],
  ['two joined folios, early literary text, later dated reuse, and the full title', ['consists of two joined paper folios', 'dates the literary text to the early ninth century', 'later reuse to October 879', 'Kitāb fīhi ḥadīth min alf layla']],
  ['the oldest MS breaks off near night 282', '282'],
  ['the back-translations / Chavis & Sabbāgh', 'back-translation'],
  ['the Bodleian Ali Baba counterfeit', 'counterfeit'],
  ['Mahdi named as the source of the finding', 'Mahdi'],
  ['Hannā Diyāb named as the storyteller', 'Diyāb'],
  ['"1,001" disclosed as an idiom, not a count', 'idiom for'],
  ['Sindbad is a separate cycle inserted before manuscript exhaustion', ['Sindbad is not an orphan tale', 'Galland had already translated Sindbad from a separate Arabic manuscript and inserted it in volume III. Later, when his manuscript sources ran out']],
  ['the Diyab-as-author debate kept open (Bottigheimer/Horta)', 'genuinely open'],
  ['Mahdi single-original thesis flagged as contested', 'is contested'],
];
for (const [label, required] of CLAIMS) {
  const needles = Array.isArray(required) ? required : [required];
  const missing = needles.filter(needle => !has(needle));
  if (missing.length === 0) ok(label); else bad(label + ' (missing: ' + missing.join(' | ') + ')');
}

console.log('\n3. The three instruments are wired (load-bearing strings present)');
const STRUCT = [
  ['ledger: the three famous tales are all listed', ['Aladdin and the Wonderful Lamp', 'Ali Baba and the Forty Thieves', 'Sindbad the Sailor']],
  ['ledger: a genuine medieval-core tale is listed', ['The Fisherman and the Jinni', 'The Three Apples']],
  ['ledger: orphan/core/late filter buttons', ['In the medieval core', 'Joined later', 'Orphan tales']],
  ['instrument II: both tales selectable', ['data-t="fisherman"', 'data-t="aladdin"']],
  ['instrument II: the distinct sets of four versions are present', ['Grub Street English of Galland', 'Edward William Lane', 'John Payne', 'Richard F. Burton', 'Antoine Galland (the source itself)', 'Galland-English (Wiggin & Smith)', 'order: ["grub","lane","payne","burton"]', 'order: ["gallandfr","gallanden","payne","burton"]']],
  ['instrument III: the stratigraphy spans 9th c. to 1994', ['c. 9th–10th c.', '1984–1994']],
  ['the venue framing + home link', ['twenty-fifth entry of the Translation-Criticism Venue', 'return to the wasteland']],
  ['the shared home banner is included', ['/media/home-banner.js']],
];
for (const [label, needles] of STRUCT) {
  const miss = needles.filter(n => !pagePlain.includes(norm(n)) && !PAGE.includes(n));
  if (miss.length === 0) ok(label);
  else bad(label + ' — missing: ' + miss.join(' | '));
}

console.log('\n4. No translator is quoted who is in copyright (Mardrus/Mathers, Borges named-only)');
// These names may appear as cited positions, but their words must not be quoted as
// verbatim passages. The eight passage files are all pre-1929 PD; assert the page
// does not embed a Mathers/Mardrus English passage block by checking the voice data
// only contains the eight known PD hands.
const handCount = (PAGE.match(/who:"/g) || []).length;
if (handCount === 8) ok('exactly 8 translation voices embedded (all public-domain)');
else bad('expected 8 embedded voices, found ' + handCount + ' — check no in-copyright text slipped in');

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