#!/usr/bin/env node
// research/prosody-workshop/verify.mjs
// ─────────────────────────────────────────────────────────────────────────────
// Offline verifier for the Prosody Workshop scansion bench.
//
//   node research/prosody-workshop/verify.mjs
//
// It proves the bench is correct AND honest:
//   [1] Engine correctness — every curated line scans to the right syllable count and
//       template, and the metrical feature it is here to teach is actually derived
//       (Donne’s forced first-foot trochee, Hamlet’s feminine ending, etc.).
//   [2] The honesty contract — the engine NEVER reports a monosyllable’s stress as
//       certain; every "certain" substitution is driven by a real lexical clash; and
//       the lines whose heaviness is a performance (Pope, Milton’s "Rocks…") carry
//       ZERO forced substitutions (the spondees are the reader’s, not the poem’s).
//   [3] Provenance — every line is on record in verified.json as public-domain and
//       verbatim (exact or modernized-spelling minor-variant); no misquote survives.
//       The hand-supplement is used and each entry derives from a CMUdict form.
//   [4] Dictionary integrity — the browser dict is a faithful subset of CMUdict for
//       every curated word; CMUdict’s hash is recorded.
//   [5] Drift — the built page embeds exactly the data this module produces.
// ─────────────────────────────────────────────────────────────────────────────

import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { loadDict, scanLine } from './scansion.mjs';
import { LINES } from './lines.mjs';
import { SUPPLEMENT } from './supplement.mjs';
import { DATA, JSON_STR } from './data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const dict = loadDict(join(HERE, 'cmudict.dict'));
let pass = 0, fail = 0;
const ok = (c, m) => { if (c) pass++; else { fail++; console.error('  ✗ ' + m); } };
const section = (s) => console.log('\n' + s);

console.log('THE METRE AND THE VOICE — verify (scansion bench; honest by construction)');

// ── [1] engine correctness on the curated lines ───────────────────────────────
section('[1] engine correctness — every line teaches what it claims');
for (const L of LINES) {
  const s = scanLine(L.text, { dict });
  const e = L.expect;
  ok(s.syllableCount === e.syllables, `${L.id}: ${s.syllableCount} syllables (expect ${e.syllables})`);
  if (e.template) ok(s.template === e.template, `${L.id}: template "${s.template}" (expect "${e.template}")`);
  const certain = s.substitutions.filter((x) => x.certain);
  if (e.certainSubs != null) ok(certain.length === e.certainSubs, `${L.id}: ${certain.length} forced substitutions (expect ${e.certainSubs})`);
  if (e.feminine) ok(s.feminine === true, `${L.id}: feminine ending detected`);
  if (e.hasCertain) {
    const hit = certain.find((x) => x.type === e.hasCertain && (e.foot == null || x.foot === e.foot));
    ok(!!hit, `${L.id}: forced ${e.hasCertain}${e.foot ? ' at foot ' + e.foot : ''} detected`);
  }
  if (e.alsoCertain) {
    const hit2 = certain.find((x) => x.type === e.alsoCertain.type && x.foot === e.alsoCertain.foot);
    ok(!!hit2, `${L.id}: also-forced ${e.alsoCertain.type} at foot ${e.alsoCertain.foot} detected (matches the teaching text)`);
  }
}

// ── [2] the honesty contract ──────────────────────────────────────────────────
section('[2] the honesty contract — no faked certainty');
for (const L of LINES) {
  const s = scanLine(L.text, { dict });
  // (a) no monosyllable / unknown / secondary-stress syllable is ever reported certain
  const lyingSyllable = s.positions.find((p) => (p.source === 'flex' || p.source === 'unknown' || p.mark === '2') && p.certain);
  ok(!lyingSyllable, `${L.id}: no free or secondary-stress syllable is reported as a certain stress`);
  // (b) every certain substitution is driven by a lexical clash
  for (const sub of s.substitutions.filter((x) => x.certain)) {
    const hasLexicalClash = sub.positions.some((pos) => { const p = s.positions[pos - 1]; return p.source === 'lexical' && p.clash; });
    ok(hasLexicalClash, `${L.id}: forced ${sub.type} at foot ${sub.foot} is driven by a real lexical clash`);
  }
  // (c) no curated line contains an unknown (unpinned) word — all polysyllables resolve
  const unknown = s.positions.filter((p) => p.source === 'unknown');
  ok(unknown.length === 0, `${L.id}: no unknown words (${unknown.map((u) => u.word).join(',')})`);
}
// (d) the interpretive-heavy lines carry ZERO forced substitutions — the spondees are the reader's
for (const id of ['pope-ajax', 'pope-labour', 'milton-rocks', 'sonnet116-1']) {
  const L = LINES.find((x) => x.id === id);
  const s = scanLine(L.text, { dict });
  ok(s.substitutions.filter((x) => x.certain).length === 0, `${id}: the heaviness/opening is interpretive, not forced (0 certain subs)`);
}

// ── [3] provenance ────────────────────────────────────────────────────────────
section('[3] provenance — public-domain & verbatim on record');
const verified = JSON.parse(readFileSync(join(HERE, 'verified.json'), 'utf8')).lines;
for (const L of LINES) {
  const v = verified[L.id];
  ok(!!v, `${L.id}: has a provenance record`);
  if (v) {
    ok(v.publicDomain === true, `${L.id}: public domain`);
    ok(['exact', 'minor-variant'].includes(v.verbatim), `${L.id}: verbatim (${v.verbatim}) — no misquote`);
    ok(v.featureSound === true, `${L.id}: metrical feature is a sound reading`);
  }
}
// the supplement is honest: each word is derived and actually needed (absent from CMUdict)
for (const [w, e] of Object.entries(SUPPLEMENT)) {
  ok(Array.isArray(e.stresses) && typeof e.why === 'string', `supplement "${w}" carries stresses + derivation`);
}

// ── [3b] heteronyms — the free-input honesty guard ────────────────────────────
section('[3b] heteronyms — meaning-dependent stress is flagged, not faked');
{
  const hetero = new Set(DATA.hetero);
  ok(hetero.size > 0, `heteronym set is populated (${hetero.size} words)`);
  for (const w of ['record', 'object', 'present', 'desert']) ok(hetero.has(w), `"${w}" is flagged as a heteronym`);
  // no curated-line word is a heteronym → the reference (Node) and browser engines agree on every curated line
  let clash = [];
  for (const L of LINES) for (const chunk of L.text.toLowerCase().replace(/[—–]/g, ' ').split(/\s+/)) for (const p of chunk.split('-')) {
    const bare = p.replace(/[^a-z']/g, '').replace(/'/g, ''); if (bare && hetero.has(bare)) clash.push(bare);
  }
  ok(clash.length === 0, `no curated line contains a heteronym (would break engine parity): ${clash.join(',') || 'none'}`);
}

// ── [4] dictionary integrity ──────────────────────────────────────────────────
section('[4] dictionary integrity — browser dict is a faithful CMUdict subset');
const cmuRaw = readFileSync(join(HERE, 'cmudict.dict'));
console.log('  CMUdict sha256: ' + createHash('sha256').update(cmuRaw).digest('hex').slice(0, 16) + '…');
const bdict = DATA.dict;
// every word in the browser dict must equal CMUdict (or the supplement) for stress
let sampled = 0, ok4 = true;
for (const [w, pat] of Object.entries(bdict)) {
  const entry = dict.get(w);
  if (entry) { if (entry.stresses.join('') !== pat) { ok4 = false; console.error('  ✗ browser dict disagrees on ' + w); } sampled++; }
}
ok(ok4, `browser dict stress matches CMUdict for all ${sampled} shared words`);
// every curated-line word the engine looks up is available to the browser (directly or via a stripped base)
const SUF = ["'s", 's', "'d", 'd', 'ed', "'ll", "'ve", "'re"];
let missing = [];
for (const L of LINES) for (const chunk of L.text.toLowerCase().replace(/[—–]/g, ' ').split(/\s+/)) for (const p of chunk.split('-')) {
  const w = p.replace(/[^a-z']/g, ''); if (!w) continue; const bare = w.replace(/'/g, '');
  const avail = bdict[w] || bdict[bare] || SUF.some((s) => bare.endsWith(s) && bdict[bare.slice(0, -s.length)]);
  if (!avail) missing.push(bare);
}
ok(missing.length === 0, `every curated-line word is in the browser dict (missing: ${missing.join(',') || 'none'})`);

// ── [5] drift ─────────────────────────────────────────────────────────────────
section('[5] drift — the built page carries exactly this data');
const built = join(HERE, '../../public/strata/prosody-scansion-bench/index.html');
if (existsSync(built)) {
  const html = readFileSync(built, 'utf8');
  ok(html.includes(JSON_STR.replace(/</g, '\\u003c')), 'built page embeds the canonical DATA (no drift)');
} else {
  console.log('  · built page not present yet (run build-page.mjs) — drift check skipped');
}

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