// research/prosody-workshop/verify-rhyme.mjs
// ─────────────────────────────────────────────────────────────────────────────
// The rhyme lab's verifier. Re-derives every claim the page will make and fails loudly
// on any drift. Run: `node research/prosody-workshop/verify-rhyme.mjs`
//
// Checks:
//   A. CORRECTNESS — the engine reproduces every row of the hand-checked truth set
//      (rhyme-truth.mjs), sound class AND eye-rhyme flag.
//   B. VARIANT DISCLOSURE — variant-dependent pairs are flagged as such (never hidden).
//   C. PROVENANCE — every curated poem's declared scheme has the right length; every
//      end-word is either in CMUdict or covered by the transparent supplement (nothing
//      silently guessed); the supplement is fully used and each entry is derivable.
//   D. THE SHOWCASE CLAIMS — the specific findings the page asserts (Sonnet 18's
//      temperate/date is an eye rhyme; Owen's pararhymes are consonance; the ear
//      over-merges Sonnet 18) all reproduce from the engine.
// ─────────────────────────────────────────────────────────────────────────────
import { loadDict } from './scansion.mjs';
import { classifyPair, schemeReading, earGrouping, orthRime } from './rhyme.mjs';
import { augmentDict, RHYME_SUPPLEMENT } from './rhyme-supplement.mjs';
import { TRUTH, VARIANTS } from './rhyme-truth.mjs';
import { POEMS, PAIRS, GALLERY, HISTORICAL } from './rhyme-data.mjs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const dict = augmentDict(loadDict(join(HERE, 'cmudict.dict')));

let pass = 0, fail = 0;
const fails = [];
function check(name, cond, detail = '') { if (cond) pass++; else { fail++; fails.push(`${name}${detail ? ' — ' + detail : ''}`); } }

// ── A. CORRECTNESS against the truth set ─────────────────────────────────────
for (const row of TRUTH) {
  const v = classifyPair(row.a, row.b, dict);
  check(`sound ${row.a}/${row.b}`, v.known && v.soundClass === row.sound, `got ${v.soundClass}, expected ${row.sound}`);
  check(`eye ${row.a}/${row.b}`, !!v.eye === !!row.eye, `got eye=${v.eye}, expected ${row.eye}`);
}

// ── B. VARIANT DISCLOSURE ────────────────────────────────────────────────────
for (const row of VARIANTS) {
  const v = classifyPair(row.a, row.b, dict);
  check(`variant-best ${row.a}/${row.b}`, v.soundClass === row.best, `got ${v.soundClass}`);
  check(`variant-disclosed ${row.a}/${row.b}`, v.variantDependent === row.variantDependent, `got ${v.variantDependent}`);
}

// ── C. PROVENANCE / dictionary coverage ──────────────────────────────────────
const usedSupp = new Set();
for (const poem of POEMS) {
  check(`scheme-length ${poem.id}`, poem.lines.length === poem.scheme.length,
        `${poem.lines.length} lines vs ${poem.scheme.length} scheme letters`);
  for (const line of poem.lines) {
    const w = line.end.toLowerCase().replace(/[^a-z']/g, '');
    const inDict = dict.has(w) || dict.has(w.replace(/'/g, ''));
    // allow light inflection (handled by the engine's lookup) — re-derive via classifyPair self-pair
    const known = classifyPair(w, w, dict).known;
    check(`coverage ${poem.id}:${w}`, known, 'end-word not in dictionary or supplement');
    if (RHYME_SUPPLEMENT[w]) usedSupp.add(w);
  }
}
for (const pair of PAIRS) {
  for (const w of [pair.a, pair.b]) {
    const known = classifyPair(w, w, dict).known;
    check(`coverage pair:${w}`, known, 'preset-pair word not in dictionary or supplement');
    if (RHYME_SUPPLEMENT[w.toLowerCase()]) usedSupp.add(w.toLowerCase());
  }
}
// GALLERY (Owen couplets): coverage + every couplet must classify as consonance
for (const c of GALLERY.couplets) {
  for (const w of [c.a.end, c.b.end]) {
    check(`coverage gallery:${w}`, classifyPair(w, w, dict).known, 'gallery word not in dictionary or supplement');
    if (RHYME_SUPPLEMENT[w.toLowerCase()]) usedSupp.add(w.toLowerCase());
  }
  const v = classifyPair(c.a.end, c.b.end, dict);
  check(`gallery-consonance ${c.a.end}/${c.b.end}`, v.soundClass === 'consonance', `got ${v.soundClass} — the pararhyme claim requires consonance`);
}
// HISTORICAL: coverage (the note carries the historical claim; the engine reports the modern verdict)
for (const h of HISTORICAL) {
  for (const w of [h.a, h.b]) check(`coverage historical:${w}`, classifyPair(w, w, dict).known, 'historical word not in dictionary or supplement');
}
// every supplement entry must actually be used by some curated content (no dead entries)
for (const w of Object.keys(RHYME_SUPPLEMENT)) {
  check(`supplement-used ${w}`, usedSupp.has(w), 'supplement entry not used by any poem/pair');
  // and each entry must carry a derivation note
  check(`supplement-why ${w}`, !!RHYME_SUPPLEMENT[w].why, 'missing derivation note');
}

// ── D. THE SHOWCASE CLAIMS reproduce ─────────────────────────────────────────
// Each poem declares an `expect` block of specific claims the page makes.
for (const poem of POEMS) {
  const reading = schemeReading(poem.lines.map((l) => l.end), poem.scheme.split(''), dict);
  // group realisations the page prints
  if (poem.expect?.groups) {
    for (const [letter, real] of Object.entries(poem.expect.groups)) {
      const g = reading.groups.find((x) => x.letter === letter);
      check(`${poem.id} group ${letter}`, g && g.realisation === real, `got ${g?.realisation}, expected ${real}`);
    }
  }
  if (poem.expect?.earScheme) {
    check(`${poem.id} ear-scheme`, earGrouping(poem.lines.map((l) => l.end), dict) === poem.expect.earScheme,
          `got ${earGrouping(poem.lines.map((l) => l.end), dict)}`);
  }
  if (poem.expect?.pairs) {
    for (const [a, b, want] of poem.expect.pairs) {
      const v = classifyPair(a, b, dict);
      check(`${poem.id} pair ${a}/${b}`, v.label === want || v.soundClass === want, `got ${v.label}`);
    }
  }
}

// preset-pair specific expectations (each preset carries its own asserted class)
for (const pair of PAIRS) {
  const v = classifyPair(pair.a, pair.b, dict);
  check(`preset ${pair.a}/${pair.b}`, v.soundClass === pair.sound, `got ${v.soundClass}, expected ${pair.sound}`);
  if (pair.eye !== undefined) check(`preset-eye ${pair.a}/${pair.b}`, !!v.eye === !!pair.eye, `got eye=${v.eye}`);
}

// ── report ───────────────────────────────────────────────────────────────────
console.log(`\nRHYME LAB VERIFY — ${pass}/${pass + fail} checks pass\n`);
if (fail) { console.log('FAILURES:'); for (const f of fails) console.log('  ✗ ' + f); process.exit(1); }
console.log('✓ all green — engine reproduces the truth set, coverage complete, showcase claims hold.');
