#!/usr/bin/env node
// Internal-consistency checks for "The Rhyme the Sound Forgot".
//   node research/the-rhyme-the-sound-forgot/verify.mjs
//
// What this proves: that the embedded data is internally coherent and honest —
//   • every "broken chime" genuinely encodes vowels that MATCHED in the reconstruction
//     (a.then === b.then) and DIFFER today (a.now !== b.now) — i.e. the data really
//     describes a rhyme broken by sound change, not an arbitrary pair;
//   • every sounded vowel resolves to a published formant value or a diphthong glide,
//     so the audio claim is honest (we only sound what we have numbers for);
//   • every quoted rhyme word actually occurs in its verbatim passage (the text guard);
//   • every rhyme cites a real change, and MOST changes are NOT the Great Vowel Shift
//     (the page's central honesty point — it does not over-blame the famous shift);
//   • the contested cases are tagged `disputed` and name a dispute in their source;
//   • the data shipped in the page is byte-identical to this source of truth (drift guard).
// What it does NOT prove: the phonology itself — that is the cited work of philology,
// demonstrated and attributed on the page, not re-derived here.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { CHANGES, RHYMES, FORMANTS, DIPHTHONGS, FORMANT_DOC, FRAME } from './data.mjs';

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

const qOf = (ipa) => ipa.replace(/ː/g, '');
const resolves = (v) => !!DIPHTHONGS[v] || !!FORMANTS[qOf(v)];

// ── I/II · the broken chimes ──
ok('there are at least six broken rhymes/puns', RHYMES.length >= 6, `${RHYMES.length}`);
ok('every item is a rhyme or a pun', RHYMES.every((r) => r.kind === 'rhyme' || r.kind === 'pun'));
ok('there is at least one rhyme and one pun',
  RHYMES.some((r) => r.kind === 'rhyme') && RHYMES.some((r) => r.kind === 'pun'));
ok('every rhyme id is unique', new Set(RHYMES.map((r) => r.id)).size === RHYMES.length);

// the load-bearing logic: matched THEN, differ NOW
ok('every pair MATCHED in the reconstruction (a.then === b.then) — it really was a chime',
  RHYMES.every((r) => r.a.then === r.b.then), RHYMES.filter((r) => r.a.then !== r.b.then).map((r) => r.id).join(', '));
ok('every pair DIFFERS today (a.now !== b.now) — it really is broken',
  RHYMES.every((r) => r.a.now !== r.b.now), RHYMES.filter((r) => r.a.now === r.b.now).map((r) => r.id).join(', '));
// at least one word in each pair actually moved (so "now" is the result of a change)
ok('in every pair at least one word changed between then and now',
  RHYMES.every((r) => r.a.then !== r.a.now || r.b.then !== r.b.now));

// every sounded vowel is synthesisable
ok('every THEN vowel resolves to a published formant or a diphthong glide',
  RHYMES.every((r) => resolves(r.a.then) && resolves(r.b.then)),
  RHYMES.filter((r) => !(resolves(r.a.then) && resolves(r.b.then))).map((r) => r.id).join(', '));
ok('every NOW vowel resolves to a published formant or a diphthong glide',
  RHYMES.every((r) => resolves(r.a.now) && resolves(r.b.now)),
  RHYMES.filter((r) => !(resolves(r.a.now) && resolves(r.b.now))).map((r) => r.id).join(', '));

// the verbatim text guard. For a RHYME, both words are on the page. For a PUN, only the
// first word (a.w) is on the page — the second (b.w) is the GHOST homophone, deliberately
// absent (that is what a lost pun IS), so we require a.w present and confirm b.w is the ghost.
const inText = (w, t) => new RegExp('\\b' + w + '\\b', 'i').test(t);
for (const r of RHYMES) {
  ok(`text guard · on-page word "${r.a.w}" occurs verbatim in ${r.id}`, inText(r.a.w, r.text));
  if (r.kind === 'rhyme') {
    ok(`text guard · rhyme partner "${r.b.w}" occurs verbatim in ${r.id}`, inText(r.b.w, r.text));
  } else {
    ok(`text guard · pun ghost "${r.b.w}" is NOT on the page in ${r.id} (the lost homophone)`, !inText(r.b.w, r.text));
  }
}

// every item carries a locus, a year, a source, a recon attribution, a certainty
ok('every item has poet/work/where/year/src/recon/certainty',
  RHYMES.every((r) => r.poet && r.work && r.where && r.year && r.src && r.recon &&
    (r.certainty === 'disputed' || r.certainty === 'reconstructed')));
// puns carry a "meaning" (the lost second sense)
ok('every pun states the second sense now lost',
  RHYMES.filter((r) => r.kind === 'pun').every((r) => r.meaning && r.meaning.length > 10));
// disputed items name the dispute in their source string
ok('every disputed item names a dispute (Cercignani / Whichello / contested) in its source',
  RHYMES.filter((r) => r.certainty === 'disputed').every((r) => /Cercignani|Whichello|contested|Contested|dispute|DISPUTED|some dialects/.test(r.src)));
ok('the Sonnet 116 proved/loved pair is present and tagged disputed (the honesty centrepiece)',
  RHYMES.some((r) => r.id === 's116-proved-loved' && r.certainty === 'disputed'));

// ── III · the changes ──
ok('every rhyme cites a change that exists in CHANGES',
  RHYMES.every((r) => CHANGES[r.change]), RHYMES.filter((r) => !CHANGES[r.change]).map((r) => r.id).join(', '));
ok('every change has name/mech/src and a boolean gvs flag',
  Object.values(CHANGES).every((c) => c.name && c.mech && c.src && typeof c.gvs === 'boolean'));
const gvsCount = RHYMES.filter((r) => CHANGES[r.change].gvs).length;
const notCount = RHYMES.length - gvsCount;
ok('MOST broken rhymes are NOT the Great Vowel Shift (the page\'s central claim)',
  notCount > gvsCount, `not-GVS ${notCount} vs GVS ${gvsCount}`);
ok('at least one rhyme IS the Great Vowel Shift (the claim is not zero either)', gvsCount >= 1, `${gvsCount}`);
ok('the FOOT–STRUT change is flagged not-GVS', CHANGES.strut && CHANGES.strut.gvs === false);
ok('the LINE–JOIN change is flagged not-GVS', CHANGES.choice && CHANGES.choice.gvs === false);

// ── the formant backing ──
const KNOWN_SRC = new Set(['Catford 2001', 'Peterson & Barney 1952']);
ok('every formant entry carries a recognised published source',
  Object.values(FORMANTS).every((f) => KNOWN_SRC.has(f.src)));
ok('every formant has plausible F1/F2 in Hz (200–1000 / 500–2600)',
  Object.values(FORMANTS).every((f) => f.f1 >= 200 && f.f1 <= 1000 && f.f2 >= 500 && f.f2 <= 2600));
ok('the citation is the verifiable edition — Catford 2001 (not the unconfirmed 1988)',
  Object.values(FORMANTS).some((f) => f.src === 'Catford 2001') && !JSON.stringify(FORMANTS).includes('Catford 1988'));
ok('the /ʌ/ added for the love-vowel is sourced to Peterson & Barney 1952',
  FORMANTS['ʌ'] && FORMANTS['ʌ'].src === 'Peterson & Barney 1952');
ok('every diphthong glides between two real monophthong targets',
  Object.values(DIPHTHONGS).every((d) => FORMANTS[d.from] && FORMANTS[d.to]));
ok('the apparatus is honest that this is a sketch, not a recording', /not a recording|reconstruction/.test(FORMANT_DOC.honest));
ok('the apparatus names F3 as a non-distinguishing nominal, not a claim', /F3 is a fixed nominal/.test(FORMANT_DOC.sourced));
ok('the apparatus says the synth sounds the stressed vowels only',
  /stressed vowels only/.test(FORMANT_DOC.what));

// ── IV · the untranslatable frame ──
ok('the Crystal "no single OP" quote is present and attributed', /no .single. OP/.test(FRAME.crystalSingle) && /originalpronunciation/.test(FRAME.crystalSrc));
ok('the Crystal "guesswork" quote is present', /guesswork/.test(FRAME.crystalGuess));
ok('the counter names Cercignani with a page citation', /Cercignani/.test(FRAME.counter) && /p\. vii|pp\. vii/.test(FRAME.counterSrc));
ok('the stat attributes the 96/154 figure to interviews, not asserted as Crystal\'s primary text',
  /interviews|press|NPR|WNYC/.test(FRAME.stat));
ok('the thesis names the doubled loss / the untranslatable across time',
  /untranslatable|reconstruction|no living speaker/.test(FRAME.thesis));

// ── DRIFT GUARD: the page embeds this data byte-for-byte ──
const pagePath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'public', 'strata', 'the-rhyme-the-sound-forgot', 'index.html');
let html = '';
try { html = readFileSync(pagePath, 'utf8'); } catch { /* page not built yet */ }
const blobs = { CHANGES, RHYMES, FORMANTS, DIPHTHONGS, FORMANT_DOC, FRAME };
for (const [name, value] of Object.entries(blobs)) {
  const m = html.match(new RegExp(`<script id="data-${name}" type="application/json">([\\s\\S]*?)</script>`));
  ok(`drift guard · page's ${name} is byte-identical to data.mjs`, !!m && m[1] === JSON.stringify(value),
    m ? '' : 'block missing — run build-page.mjs');
}

console.log(`\n${pass}/${n} checks pass`);
process.exit(pass === n ? 0 : 1);
