#!/usr/bin/env node
// Internal-consistency checks for "The Sound the Spelling Forgot" (the Great Vowel Shift).
//   node research/great-vowel-shift/verify.mjs
//
// What this proves: that the embedded data is internally coherent and transcription-clean —
// the vowel chain is a raising with exactly two breaks; the merger and its named escapees
// land where the prose says; every loan pair contrasts a shifted native value against an
// unshifted late loan; every quoted rhyme word actually occurs in its verbatim passage; and
// the data shipped in the page is byte-identical to this source of truth (the drift guard).
// What it does NOT prove: the phonology itself — that is the cited work of two centuries of
// philology, demonstrated and sourced on the page, not re-derived here.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { VOWELS, MERGER, LOANS, LOAN_NOTE, FOSSILS, WITNESSES, CHAUCER, DATING, FORMANTS, DIPHTHONGS, FORMANT_DOC } 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 : ''}`); };

// ── the IPA inventory we allow (a typo guard) ──
const IPA = new Set(['iː', 'eː', 'ɛː', 'aː', 'ɔː', 'oː', 'uː', 'aɪ', 'eɪ', 'oʊ', 'aʊ', 'ɛ', 'ʊ', 'ʌ', 'əʊ']);

// ── I · the seven vowels ──
ok('seven long vowels', VOWELS.length === 7, `${VOWELS.length}`);
const breaks = VOWELS.filter((v) => v.motion === 'break');
const raises = VOWELS.filter((v) => v.motion === 'raise');
ok('exactly two vowels break (diphthongise)', breaks.length === 2, breaks.map((v) => v.word).join(', '));
ok('exactly five vowels raise', raises.length === 5);
ok('every vowel changed quality (me ≠ mod)', VOWELS.every((v) => v.me !== v.mod));
ok('every me/mod value is in the IPA inventory', VOWELS.every((v) => IPA.has(v.me) && IPA.has(v.mod)));
// the two that break are the two highest ME vowels (close: chart y near 0)
ok('the two breaks are the highest ME vowels (/iː/, /uː/)',
  breaks.every((v) => (v.me === 'iː' || v.me === 'uː') && v.mePos.y < 0.1));
ok('the two breaks become diphthongs and fall low on the chart',
  breaks.every((v) => v.modPos.y > 0.8 && v.glide));
// raises climb: modPos.y < mePos.y (higher on the chart = smaller y)
ok('every raising vowel climbs (ends higher than it began)',
  raises.every((v) => v.modPos.y < v.mePos.y));
// the close-front and close-back targets that /iː/,/uː/ vacate are filled by /eː/,/oː/
const eMeet = VOWELS.find((v) => v.id === 'e'), oMoon = VOWELS.find((v) => v.id === 'o');
ok('the meet-vowel (/eː/) climbs to /iː/', eMeet.mod === 'iː');
ok('the moon-vowel (/oː/) climbs to /uː/', oMoon.mod === 'uː');

// ── II·b · the loanword contrast ──
ok('six loan pairs', LOANS.length === 6);
ok('every loan pair contrasts a shifted native vs an unshifted loan', LOANS.every((l) => l.native.ipa !== l.loan.ipa));
ok('native i-words shifted to /aɪ/, ou-words to /aʊ/',
  LOANS.every((l) => (l.letter === 'i' ? l.native.ipa === 'aɪ' : l.native.ipa === 'aʊ')));
ok('late loans keep the Continental value (i → /iː/, ou → /uː/)',
  LOANS.every((l) => (l.letter === 'i' ? l.loan.ipa === 'iː' : l.loan.ipa === 'uː')));
ok('the load-bearing example "group" is present (etymonline cites the GVS for it)',
  LOANS.some((l) => l.loan.word === 'group') && /Great Vowel Shift/.test(LOAN_NOTE));
ok('the dropped bad examples (route, marine) are NOT used',
  !LOANS.some((l) => ['route', 'marine'].includes(l.loan.word)));

// ── III · the merger and the escapees ──
ok('meet and meat were distinct ME vowels', MERGER.meet.me !== MERGER.meat.me);
ok('meet and meat merged to the same modern vowel /iː/', MERGER.meet.mod === MERGER.meat.mod && MERGER.meet.mod === 'iː');
ok('the escapees diverge from the merger (/eɪ/ ≠ /iː/)', MERGER.escapeeOutcome !== MERGER.meet.mod && MERGER.escapeeOutcome === 'eɪ');
ok('the escapee set is the canonical great/break/steak',
  JSON.stringify(MERGER.escapees) === JSON.stringify(['great', 'break', 'steak']));
ok('escapee outcome /eɪ/ equals the name-vowel reflex',
  MERGER.escapeeOutcome === VOWELS.find((v) => v.id === 'a').mod);
ok('homophone pairs are genuinely two different spellings', MERGER.homophones.every(([a, b]) => a !== b));
ok('the merger note flags that the escape is unexplained', /not settled|irregular/.test(MERGER.note));

// ── I · the fossils ──
ok('six spelling fossils', FOSSILS.length === 6);
ok('every fossil records a vowel that has since changed (me ≠ mod)', FOSSILS.every((f) => f.me !== f.mod));
ok('every fossil value is in the IPA inventory', FOSSILS.every((f) => IPA.has(f.me) && IPA.has(f.mod)));
// the fossil values agree with the vowel table where the keyword matches
for (const f of FOSSILS) {
  const v = VOWELS.find((v) => v.word === f.ex);
  if (v) ok(`fossil "${f.ex}" matches the vowel table (${f.me}→${f.mod})`, v.me === f.me && v.mod === f.mod);
}

// ── IV · the witnesses (verbatim guard: the quoted rhyme words occur in the text) ──
ok('two rhyme witnesses + one pun', WITNESSES.rhymes.length === 2 && WITNESSES.puns.length === 1);
ok('Sonnet 116 rhyme 1 quotes the words "love" and "remove"',
  /\blove\b/i.test(WITNESSES.rhymes[0].text) && /\bremove\b/i.test(WITNESSES.rhymes[0].text));
ok('Sonnet 116 rhyme 2 quotes the words "proved" and "loved"',
  /\bproved\b/.test(WITNESSES.rhymes[1].text) && /\bloved\b/.test(WITNESSES.rhymes[1].text));
ok('the pun passage quotes the word "hour"', /\bhour\b/.test(WITNESSES.puns[0].text));
ok('OP readings are attributed to Crystal, not asserted as fact',
  WITNESSES.rhymes.concat(WITNESSES.puns).every((w) => /Crystal/.test(w.src) || /Crystal/.test(w.point)));
ok('three orthoepist witnesses with works and dates',
  WITNESSES.orthoepists.length === 3 && WITNESSES.orthoepists.every((o) => /\d{4}/.test(o.work)));

// ── the Chaucer anchor ──
const chLines = CHAUCER.text.split('\n');
ok('Chaucer anchor is four lines', chLines.length === 4);
ok('Chaucer text quotes "Aprille" and "Marche" (Skeat 1900 spelling)',
  /Aprille/.test(CHAUCER.text) && /Marche/.test(CHAUCER.text));
ok('Chaucer source names the edition and flags spelling variation',
  /Skeat/.test(CHAUCER.src) && /Riverside|Harvard/.test(CHAUCER.src));

// ── dating / the honest caveat ──
ok('the term is attributed to Jespersen (1909)', /Jespersen/.test(DATING.coiner.who) && /1909/.test(DATING.coiner.work));
ok('the caveat names the chain an idealization', /idealization|idealiz/.test(DATING.caveat));
ok('the skeptic note credits Stockwell & Minkova and notes Lass defends coherence',
  /Stockwell/.test(DATING.skeptic) && /Lass/.test(DATING.skeptic));
ok('the caveat flags the Northern-dialect exception', /Northern|North of England|North/.test(DATING.caveat));

// ── THE VOICE: formant synthesis data (the page can be heard) ──────────────────
// What this proves: every Middle-English vowel has a sourced F1/F2; the diphthong
// endpoints resolve to real monophthong targets; the published acoustics agree, in
// ORDER, with the schematic chart the page draws (F1 rises with openness, F2 falls
// with backness) — so the picture and the sound are two independent witnesses.
// What it does NOT prove: the timbre of the synthesis (un-checkable here) or the
// reconstructed Middle-English values themselves (cited, not re-derived).
const qOf = (ipa) => ipa.replace(/ː/g, '');
const KNOWN_SRC = new Set(['Catford 2001', 'Peterson & Barney 1952']);
ok('formant table has the nine vowels the page needs', Object.keys(FORMANTS).length === 9,
  Object.keys(FORMANTS).join(' '));
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 2nd ed. (not the unconfirmed 1988)',
  Object.values(FORMANTS).some((f) => f.src === 'Catford 2001') &&
  !JSON.stringify(FORMANTS).includes('Catford 1988'));
// every ME long vowel resolves to a sourced quality
ok('every ME long vowel (me) has a sourced formant target',
  VOWELS.every((v) => FORMANTS[qOf(v.me)]));
// every modern diphthong reflex resolves (either a monophthong or a glide of two)
const resolves = (ipa) => !!DIPHTHONGS[ipa] || !!FORMANTS[qOf(ipa)];
ok('every modern reflex (mod) is synthesisable (monophthong or a glide of two targets)',
  VOWELS.every((v) => resolves(v.mod)));
ok('the four diphthongs each glide between two real monophthong targets',
  Object.values(DIPHTHONGS).every((d) => FORMANTS[d.from] && FORMANTS[d.to]) && Object.keys(DIPHTHONGS).length === 4);
// the two break-vowel reflexes are genuinely diphthongs (fall across the chart)
ok('the two break vowels become glide-synthesised diphthongs (/aɪ/, /aʊ/)',
  VOWELS.filter((v) => v.motion === 'break').every((v) => DIPHTHONGS[v.mod]));

// ── THE CROSS-CHECK: acoustics agree with the drawn chart ──
const monoUp = (arr, get) => arr.every((r, i) => i === 0 || get(r) >= get(arr[i - 1]));
const monoDown = (arr, get) => arr.every((r, i) => i === 0 || get(r) <= get(arr[i - 1]));
const meRows = VOWELS.map((v) => ({ v, fm: FORMANTS[qOf(v.me)] }));
// F1 tracks openness WITHIN each backness series (front and back vowels sit at slightly
// different F1 levels, so the interleaved-by-height sequence is not globally monotonic —
// the honest claim is per-series, which is also the cleaner articulatory statement).
const frontUp = meRows.filter((r) => r.v.mePos.x < 0.5).sort((a, b) => a.v.mePos.y - b.v.mePos.y);
const backUp  = meRows.filter((r) => r.v.mePos.x >= 0.5).sort((a, b) => a.v.mePos.y - b.v.mePos.y);
const byBack  = meRows.slice().sort((a, b) => a.v.mePos.x - b.v.mePos.x);     // front → back
ok('F1 rises with openness through the FRONT series i→e→ɛ→a (acoustics ⟂ articulation)',
  monoUp(frontUp, (r) => r.fm.f1), frontUp.map((r) => r.fm.f1).join('→'));
ok('F1 rises with openness through the BACK series u→o→ɔ',
  monoUp(backUp, (r) => r.fm.f1), backUp.map((r) => r.fm.f1).join('→'));
ok('F2 falls monotonically as the chart goes front → back (all 7 vowels)',
  monoDown(byBack, (r) => r.fm.f2), byBack.map((r) => r.fm.f2).join('→'));
ok('every front vowel has higher F2 than every back vowel (the front/back split is acoustic)',
  Math.min(...frontUp.map((r) => r.fm.f2)) > Math.max(...backUp.map((r) => r.fm.f2)));
// the close vowels really are the lowest-F1 (the "ceiling" the break vowels hit)
ok('the two highest (close) ME vowels /iː/,/uː/ have the lowest F1 (the ceiling)',
  Math.max(FORMANTS.i.f1, FORMANTS.u.f1) <= Math.min(FORMANTS.e.f1, FORMANTS.ɛ.f1, FORMANTS.a.f1, FORMANTS.ɔ.f1, FORMANTS.o.f1));
// honesty doc names what is sourced and what is not
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 is honest that this is a sketch, not a recording', /not a recording|reconstruction/.test(FORMANT_DOC.honest));
ok('the apparatus dates the recording floor correctly (1877 playable / 1860 captured)',
  /1877/.test(FORMANT_DOC.honest) && /1860/.test(FORMANT_DOC.honest));

// ── DRIFT GUARD: the page embeds this data byte-for-byte ──
const page = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'public', 'strata', 'the-sound-the-spelling-forgot', 'index.html');
let html = '';
try { html = readFileSync(page, 'utf8'); } catch { /* page not built yet */ }
const blobs = { VOWELS, MERGER, LOANS, LOAN_NOTE, FOSSILS, WITNESSES, CHAUCER, DATING, FORMANTS, DIPHTHONGS, FORMANT_DOC };
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);
