#!/usr/bin/env node
// verify-does-it-rhyme.mjs
// ─────────────────────────────────────────────────────────────────────────────
// Offline verification of /tools/does-it-rhyme/.
//
//   node verify-does-it-rhyme.mjs
//
// THE THING THIS TOOL COULD MOST EASILY LIE ABOUT is a negative. "No perfect
// rhyme" is the page's headline claim about orange, silver, purple and month, and
// it is exactly the sentence a broken search prints too. A finder that nominated
// too few candidates would return an empty list and look confident doing it, and
// no amount of checking the words it DID return would catch that. So the load
// bearing family here is [5], which throws the index away entirely and asks every
// one of the 126,052 headwords, one at a time, through the engine's own public
// pair function. If the index ever misses a word, that family fails.
//
// This is the same lesson the repo has now learned three times in different
// clothes: a negative result is only evidence if the instrument could have
// returned a positive one. Family [9] therefore checks the checker, by asserting
// that deliberately false claims DO fail.
//
// THE FAMILIES
//   [1] the engine, the finder and the dictionary shipped under public/ are byte
//       for byte the files in research/. The tool cannot drift from the lab by
//       being a copy that quietly stopped being one.
//   [2] the page imports those files from its own directory and defines no rhyme
//       logic of its own, so nothing on the page can disagree with the engine.
//   [3] every figure the page prints re-derives from the dictionary, computed here
//       from scratch rather than read back out of meta.json.
//   [4] bands.txt is SCOWL's admission rule applied to the words CMUdict can
//       pronounce, re-derived here independently of the build script.
//   [5] COMPLETENESS. For each probe word, brute force over the whole dictionary
//       with classifyPair, and assert the finder returns exactly that set, in
//       exactly those classes. The index is allowed to nominate; it is not allowed
//       to decide, and here it is not allowed to omit either.
//   [6] the four famous negatives are empty across all 126,052 headwords, and the
//       carriers the page enumerates are the real and complete carrier list.
//   [7] the ordering rule is the one printed on the page: agreement values are
//       recomputed here by hand from the phones.
//   [8] the commonness band filters what is shown and never what is searched, and
//       a printed count always means the set under it.
//   [9] the positive controls: claims that ought to fail do fail.
//  [10] a real browser loads the real page and the reader sees what the engine
//       says, including the negative table and the pair verdict.
// ─────────────────────────────────────────────────────────────────────────────

import { readFileSync, existsSync, statSync } from 'node:fs';
import { join, extname, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import crypto from 'node:crypto';
import http from 'node:http';

import { classifyPair, classifyProns, rimeParts, anchorCandidates } from './research/prosody-workshop/rhyme.mjs';
import { buildIndex, lookup, parseDict, parseBands, agreementOf, CLASSES } from './research/prosody-workshop/rhyme-finder.mjs';
import { loadScowl } from './research/rhyme-orphans/lexicon.mjs';

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)));
const LAB = join(ROOT, 'research/prosody-workshop');
const TOOL = join(ROOT, 'public/tools/does-it-rhyme');

let pass = 0, fail = 0;
const log = [];
const ok = (c, m) => { (c ? pass++ : fail++); log.push(`  ${c ? '✓' : '✗ FAIL'} ${m}`); };
const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex');

// ── [1] the shipped copies ───────────────────────────────────────────────────
log.push('[1] the engine, the finder and the dictionary shipped here are the lab\'s own files:');
// The dictionary ships under a .txt extension so the edge will compress it (see
// build-rhyme-tool.mjs); the BYTES must still be the lab's, which is what this asserts.
for (const [shipped, source] of [['rhyme.mjs', 'rhyme.mjs'], ['rhyme-finder.mjs', 'rhyme-finder.mjs'], ['cmudict.txt', 'cmudict.dict']]) {
  const a = existsSync(join(TOOL, shipped)) ? readFileSync(join(TOOL, shipped)) : null;
  const b = readFileSync(join(LAB, source));
  ok(a !== null && a.equals(b), `${shipped} is byte-identical to research/prosody-workshop/${source}`);
}
ok(!existsSync(join(TOOL, 'cmudict.dict')),
  'the uncompressed-by-the-edge .dict copy is not also shipped');
const meta = JSON.parse(readFileSync(join(TOOL, 'meta.json'), 'utf8'));
ok(meta.source.cmudict.sha256 === sha256(readFileSync(join(LAB, 'cmudict.dict'))),
  'meta.json records the dictionary\'s true SHA-256');
ok(meta.source.engine.sha256 === sha256(readFileSync(join(LAB, 'rhyme.mjs'))),
  'meta.json records the engine\'s true SHA-256');

// ── [2] the page is glue, not a second engine ────────────────────────────────
log.push('\n[2] the page defines no rhyme logic of its own:');
const page = readFileSync(join(TOOL, 'index.html'), 'utf8');
const worker = readFileSync(join(TOOL, 'worker.mjs'), 'utf8');
ok(/new Worker\('\.\/worker\.mjs'/.test(page), 'the page starts its worker from its own directory');
ok(/from '\.\/rhyme-finder\.mjs'/.test(worker), 'the worker imports rhyme-finder.mjs from its own directory');
ok(/from '\.\/rhyme\.mjs'/.test(worker), 'the worker imports rhyme.mjs from its own directory');
ok(/fetch\('\.\/cmudict\.txt'\)/.test(worker), 'the worker fetches the dictionary from its own directory');
ok(/fetch\('\.\/bands\.txt'\)/.test(worker), 'the worker fetches the bands from its own directory');
const pageScript = page.slice(page.indexOf('<script type="module">'));
for (const forbidden of ['rimeParts', 'anchorCandidates', 'classifyProns', 'maximalOnset', 'neutralisePreRhotic']) {
  ok(!new RegExp('function\\s+' + forbidden + '|' + forbidden + '\\s*=\\s*(function|\\()').test(pageScript),
    `the page's own script does not reimplement ${forbidden}`);
}
ok(/verify-does-it-rhyme\.mjs/.test(page), 'the page names the check a reader can run');

// ── [3] the dictionary figures, re-derived from scratch ──────────────────────
log.push('\n[3] every figure the page prints re-derives from the dictionary:');
const dictText = readFileSync(join(LAB, 'cmudict.dict'), 'utf8');
// deliberately NOT parseDict: an independent parse, so a bug in the shipped one shows
const rawHeads = new Set();
let rawProns = 0;
for (const line of dictText.split('\n')) {
  const t = line.trim();
  if (!t || t.startsWith(';;;')) continue;
  const sp = t.indexOf(' ');
  if (sp === -1) continue;
  rawProns++;
  rawHeads.add(t.slice(0, sp).replace(/\(\d+\)$/, '').toLowerCase());
}
ok(rawHeads.size === 126052, `the dictionary holds 126,052 headwords (independent parse: ${rawHeads.size})`);
ok(rawProns === 135166, `the dictionary holds 135,166 pronunciations (independent parse: ${rawProns})`);
ok(meta.stats.headwords === rawHeads.size, 'meta.json agrees about headwords');
ok(meta.stats.pronunciations === rawProns, 'meta.json agrees about pronunciations');
for (const n of [rawHeads.size, rawProns]) {
  ok(page.includes(n.toLocaleString('en-US')), `the page prints ${n.toLocaleString('en-US')}`);
}

const bandsText = readFileSync(join(TOOL, 'bands.txt'), 'utf8');
const index = buildIndex(dictText, bandsText);
ok(index.stats.rimeFragments === meta.stats.rimeFragments,
  `the rime-fragment count is stable at ${index.stats.rimeFragments.toLocaleString('en-US')}`);

// ── [4] the bands ────────────────────────────────────────────────────────────
log.push('\n[4] bands.txt is SCOWL\'s own admission, applied to what CMUdict can pronounce:');
const scowl = loadScowl();
const expectRows = [];
for (const [w, b] of scowl.band) if (rawHeads.has(w)) expectRows.push(w + ' ' + b);
expectRows.sort();
ok(bandsText === expectRows.join('\n') + '\n', `bands.txt re-derives exactly (${expectRows.length.toLocaleString('en-US')} words)`);
const bands = parseBands(bandsText);
const BANDS = [10, 20, 35, 60, 95];
for (const b of BANDS) {
  let n = 0;
  for (const [, v] of bands) if (v <= b) n++;
  ok(meta.bandSizes[b] === n, `band ${b} admits ${n.toLocaleString('en-US')} words, and meta.json says so`);
  ok(page.includes(n.toLocaleString('en-US')), `the page's band selector prints ${n.toLocaleString('en-US')}`);
}

// ── [5] COMPLETENESS: brute force over the whole dictionary ──────────────────
log.push('\n[5] the finder returns exactly what the engine finds, index thrown away:');
const dict = parseDict(dictText);
const shaped = new Map();
for (const [w, prons] of dict) shaped.set(w, { prons });

/** Every word in the dictionary that meets `word` in any class, decided only by the engine. */
function bruteForce(word) {
  const prons = dict.get(word);
  const found = { perfect: new Set(), identity: new Set(), assonance: new Set(), consonance: new Set() };
  const RANK = { perfect: 5, identity: 4, consonance: 3, assonance: 3, distant: 0 };
  for (const [other, otherProns] of dict) {
    if (other === word) continue;
    let best = null;
    for (const pa of prons) for (const pb of otherProns) {
      const v = classifyProns(pa, pb);
      if (!v || v.class === 'distant') continue;
      if (!best || RANK[v.class] > RANK[best.class]) best = v;
    }
    if (best) found[best.class].add(other);
  }
  return found;
}

const PROBES = ['orange', 'silver', 'purple', 'month', 'light', 'storm', 'paradise', 'hear', 'love', 'willow'];
for (const w of PROBES) {
  const brute = bruteForce(w);
  const r = lookup(index, w, { band: null, limit: 1e9 });
  for (const c of CLASSES) {
    const got = new Set(r.classes[c].rows.map((x) => x.word));
    const want = brute[c];
    const missing = [...want].filter((x) => !got.has(x));
    const extra = [...got].filter((x) => !want.has(x));
    ok(missing.length === 0 && extra.length === 0,
      `${w}: ${c} is exactly the engine's own set (${want.size})`
      + (missing.length ? ` — MISSING ${missing.slice(0, 5).join(',')}` : '')
      + (extra.length ? ` — EXTRA ${extra.slice(0, 5).join(',')}` : ''));
    ok(r.classes[c].totalAllWords === want.size,
      `${w}: the unfiltered ${c} count is ${want.size}`);
  }
}

// and the same verdict again through the page's OTHER half, classifyPair on words
log.push('\n[5b] the finder and the pair checker never disagree about the same two words:');
let sampled = 0, agreed = 0;
for (const w of ['light', 'storm', 'hear', 'paradise']) {
  const r = lookup(index, w, { band: 35, limit: 12 });
  for (const c of CLASSES) {
    for (const row of r.classes[c].rows) {
      sampled++;
      const v = classifyPair(w, row.word, shaped);
      if (v.known && v.soundClass === c) agreed++;
      else log.push(`      ! ${w}/${row.word}: finder said ${c}, classifyPair said ${v.soundClass}`);
    }
  }
}
ok(sampled > 0 && agreed === sampled, `all ${sampled} sampled rows get the same class from classifyPair`);

// ── [6] the famous negatives ─────────────────────────────────────────────────
log.push('\n[6] the negatives are enumerations, not empty searches:');
for (const f of meta.famous) {
  const brute = bruteForce(f.word);
  ok(brute.perfect.size === 0,
    `${f.word}: brute force over all ${rawHeads.size.toLocaleString('en-US')} headwords finds 0 perfect rhymes`);
  ok(f.perfect === 0, `meta.json records ${f.word} as having 0`);
  const r = lookup(index, f.word, { band: null, limit: 0 });
  ok(r.negative !== null, `${f.word}: the page is handed an enumeration to show`);
  // every carrier of the word's own rime is listed, and nothing else carries it
  for (const frag of r.negative.fragments) {
    const key = frag.fragment.join(' ');
    const carriers = new Set(frag.carriers.map((c) => c.word));
    let trueCarriers = 0;
    for (const [other, otherProns] of dict) {
      for (const ph of otherProns) {
        for (const at of anchorCandidates(ph)) {
          const rp = rimeParts(ph, { at });
          if (rp && rp.fragment.join(' ') === key) { trueCarriers++; if (!carriers.has(other)) ok(false, `${f.word}: carrier ${other} of /${key}/ is missing from the enumeration`); }
        }
      }
    }
    ok(trueCarriers > 0, `${f.word}: rime /${key}/ is carried by at least the word itself`);
    ok(frag.carriers.some((c) => c.word === f.word && c.relation === 'itself'),
      `${f.word}: the enumeration names the word itself as itself`);
    for (const c of frag.carriers) {
      if (c.relation === 'itself') continue;
      ok(c.relation !== 'perfect', `${f.word}: carrier ${c.word} is ${c.relation}, not a rhyme (or the negative would be false)`);
    }
  }
}
// silver's story specifically, because it is the one that looks like a bug
const silver = meta.famous.find((f) => f.word === 'silver');
ok(silver.fragments[0].carriers.some((c) => c.word === 'quicksilver' && c.relation === 'identity'),
  'silver: quicksilver carries the rime and is reported as identity, not as a rhyme');

// ── [7] the ordering rule is the printed one ─────────────────────────────────
log.push('\n[7] the agreement number is the rule the page prints:');
{
  const r = lookup(index, 'light', { band: 35, limit: 40 });
  let checked = 0, right = 0;
  for (const c of CLASSES) {
    for (const row of r.classes[c].rows) {
      const v = classifyProns(dict.get('light')[0], dict.get(row.word)[0]);
      if (!v || v.class !== c) continue;   // a different pron pairing won; [5b] covers those
      const a = rimeParts(dict.get('light')[0], { at: v.atA });
      const b = rimeParts(dict.get(row.word)[0], { at: v.atB });
      checked++;
      if (agreementOf(v, a, b) === row.agreement) right++;
    }
  }
  ok(checked > 10 && right === checked, `light: all ${checked} recomputed agreement values match the row`);
  for (const c of CLASSES) {
    const rows = r.classes[c].rows;
    let sorted = true;
    for (let i = 1; i < rows.length; i++) if (rows[i].agreement > rows[i - 1].agreement) sorted = false;
    ok(sorted, `light: the ${c} list really is ordered by agreement, strongest first`);
  }
  // the rule as stated: assonance agreement is 1 + shared coda prefix
  const assonRow = r.classes.assonance.rows.find((x) => x.word === 'lights');
  if (assonRow) ok(assonRow.agreement === 2, 'light/lights: the vowel plus one shared coda consonant is agreement 2');
  else ok(false, 'light/lights was expected in the assonance list');
}
{
  // Owen's pararhyme, the case consonance exists for
  const v = classifyPair('escaped', 'scooped', shaped);
  ok(v.known && v.soundClass === 'consonance' && v.tight, 'escaped/scooped is tight consonance, as Strange Meeting uses it');
}

// ── [8] the band filters what is shown, never what is searched ───────────────
log.push('\n[8] the commonness band filters the list and not the search:');
for (const w of ['light', 'storm']) {
  const wide = lookup(index, w, { band: null, limit: 1e9 });
  const narrow = lookup(index, w, { band: 20, limit: 1e9 });
  for (const c of CLASSES) {
    const expect = wide.classes[c].rows.filter((x) => x.band !== null && x.band <= 20).length;
    ok(narrow.classes[c].total === expect,
      `${w}: the ${c} count at band 20 (${narrow.classes[c].total}) is the number of rows that pass the band`);
    ok(narrow.classes[c].totalAllWords === wide.classes[c].total,
      `${w}: the ${c} search itself is unchanged by the band`);
  }
  ok(narrow.candidatesTested === wide.candidatesTested,
    `${w}: exactly as many candidates are judged at band 20 as at no band`);
}
{
  // a count is never the truncated count
  const r = lookup(index, 'light', { band: 35, limit: 5 });
  ok(r.classes.assonance.rows.length === 5 && r.classes.assonance.total > 5,
    'a truncated list still reports the full count, not the shown count');
}

// ── [9] positive controls: the checks above can fail ─────────────────────────
log.push('\n[9] the controls, because a check that cannot fail is not a check:');
{
  const r = lookup(index, 'cat', { band: 35, limit: 1e9 });
  ok(r.classes.perfect.total > 0, 'cat has perfect rhymes, so an empty list is not what this tool always returns');
  ok(r.classes.perfect.rows.some((x) => x.word === 'hat'), 'cat/hat is among them');
  ok(r.negative === null, 'a word with rhymes is given no negative enumeration');
}
{
  const brute = bruteForce('cat');
  ok(brute.perfect.size > 0, 'the brute force used for the negatives finds rhymes when they exist');
}
{
  const r = lookup(index, 'qqqzzz', {});
  ok(!r.known && /no pronunciation/i.test(r.note), 'an unknown word is refused rather than guessed');
}
{
  // the anchor fix this engine carries: it must still be carrying it
  const v = classifyPair('paradise', 'nice', shaped);
  ok(v.known && v.soundClass === 'perfect', 'paradise/nice is a perfect rhyme (the 2026-08-06 anchor fix holds)');
  const h = classifyPair('hear', 'clear', shaped);
  ok(h.known && h.soundClass === 'perfect', 'hear/clear is a perfect rhyme (the pre-rhotic neutralisation holds)');
}
{
  // and a guard against the fix over-reaching
  const v = classifyPair('telephone', 'telegram', shaped);
  ok(v.known && v.soundClass === 'distant', 'telephone/telegram is still not a rhyme');
}

// ── [10] a real browser ──────────────────────────────────────────────────────
log.push('\n[10] a real browser loads the real page and shows what the engine says:');
const MIME = {
  '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript',
  '.json': 'application/json', '.dict': 'text/plain', '.txt': 'text/plain',
  '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2',
};
const server = http.createServer((req, res) => {
  let p = decodeURIComponent(new URL(req.url, 'http://l').pathname);
  if (p.endsWith('/')) p += 'index.html';
  const f = join(ROOT, 'public', p);
  if (!f.startsWith(join(ROOT, 'public')) || !existsSync(f) || !statSync(f).isFile()) { res.writeHead(404); res.end('not here'); return; }
  res.writeHead(200, { 'content-type': MIME[extname(f)] || 'application/octet-stream' });
  res.end(readFileSync(f));
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const BASE = `http://127.0.0.1:${server.address().port}/tools/does-it-rhyme/`;

let browser = null;
try {
  const { chromium } = await import('playwright');
  const PINNED = '/opt/pw-browsers/chromium-1194/chrome-linux/chrome';
  try { browser = await chromium.launch({ args: ['--no-sandbox'] }); }
  catch { browser = await chromium.launch({ args: ['--no-sandbox'], executablePath: PINNED }); }

  const pg = await browser.newPage({ viewport: { width: 1280, height: 900 } });
  const errors = [];
  pg.on('pageerror', (e) => errors.push(String(e.message)));
  pg.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });

  await pg.goto(BASE, { waitUntil: 'load' });
  await pg.waitForFunction(() => window.__RHYME && window.__RHYME.ready(), null, { timeout: 180000 });
  ok(true, 'the page builds its index in a browser and reports itself ready');

  const stats = await pg.evaluate(() => window.__RHYME.stats());
  ok(stats.headwords === rawHeads.size && stats.pronunciations === rawProns,
    'the browser read the same dictionary this verifier did');

  const status = (await pg.textContent('#status')).trim();
  ok(status.includes(rawProns.toLocaleString('en-US')) && status.includes(rawHeads.size.toLocaleString('en-US')),
    'the status line the reader sees prints the true dictionary figures');

  // the negative, in the DOM, not in a return value
  await pg.fill('#q', 'orange');
  await pg.click('#go');
  await pg.waitForSelector('.negative table', { timeout: 30000 });
  const negText = (await pg.textContent('.negative')).replace(/\s+/g, ' ');
  ok(/No perfect rhyme/.test(negText), 'the reader is told orange has no perfect rhyme');
  const rows = await pg.$$eval('.negative tbody tr td.mono:first-child', (ns) => ns.map((n) => n.textContent.trim()));
  ok(rows.length === 2 && rows.every((w) => w === 'orange'),
    'the enumeration the reader sees lists orange, and only orange, under both of its rimes');
  ok(!/perfect rhymes ·/i.test(await pg.textContent('#out')), 'no perfect-rhyme list is shown for orange');

  // silver: the enumeration must explain the compounds rather than look broken
  await pg.fill('#q', 'silver');
  await pg.click('#go');
  await pg.waitForSelector('.negative table', { timeout: 30000 });
  const silverText = (await pg.textContent('.negative')).replace(/\s+/g, ' ');
  ok(/quicksilver/.test(silverText) && /not a rhyme/.test(silverText),
    'silver: the reader is shown quicksilver and told it is the same sound rather than a rhyme');

  // a word with rhymes: the counts on screen are the engine's counts
  await pg.fill('#q', 'storm');
  await pg.click('#go');
  await pg.waitForSelector('.cls', { timeout: 30000 });
  const expect = lookup(index, 'storm', { band: 35, limit: 150 });
  const heads = await pg.$$eval('.cls > summary', (ns) => ns.map((n) => n.textContent.trim()));
  for (const c of CLASSES) {
    if (!expect.classes[c].total) continue;
    const want = expect.classes[c].total.toLocaleString('en-US');
    ok(heads.some((h) => h.endsWith('· ' + want)), `storm: the ${c} heading on screen reads ${want}`);
  }
  const chips = await pg.$$eval('.cls[open] .w', (ns) => ns.map((n) => n.dataset.w));
  ok(chips.length > 0 && chips.every((w) => expect.classes.perfect.rows.some((r) => r.word === w)),
    'storm: every word in the open list is one the engine put there');

  // clicking a word judges the pair, with the phones shown
  await pg.click('.cls[open] .w');
  await pg.waitForSelector('.badge', { timeout: 30000 });
  const badge = (await pg.textContent('.badge')).trim();
  ok(/rhyme|identical/.test(badge), `clicking a result judges the pair (got "${badge}")`);
  ok((await pg.$$('.reading .ph')).length >= 2, 'the pair verdict shows the phones it was made from');

  // the disclosures the honesty contract promises
  await pg.fill('#q', 'again rain');
  await pg.click('#go');
  await pg.waitForSelector('.badge', { timeout: 30000 });
  ok(/more than one pronunciation/.test((await pg.textContent('#out')).replace(/\s+/g, ' ')),
    'again/rain discloses that the dictionary lists disagreeing pronunciations');

  await pg.fill('#q', 'pomegranate');
  await pg.click('#go');
  await pg.waitForSelector('.cls, .refusal, .negative', { timeout: 30000 });
  ok(!/could not/.test(await pg.textContent('#out')),
    'pomegranate is answered, which the old lab could not do (its browser dictionary held 9,434 words)');

  await pg.fill('#q', 'zzzqqqx');
  await pg.click('#go');
  await pg.waitForSelector('.refusal', { timeout: 30000 });
  ok(/no pronunciation/i.test(await pg.textContent('.refusal')), 'an unknown word is refused on screen too');

  // the card the room and the social preview both use
  const res = await pg.goto(BASE.replace('/tools/does-it-rhyme/', '/media/tool-does-it-rhyme.png'));
  ok(res.status() === 200 && (res.headers()['content-type'] || '').includes('image/png'),
    'the og:image the page declares is a PNG actually served at that path');

  ok(errors.length === 0, `the page runs without console or page errors${errors.length ? ': ' + errors.slice(0, 3).join(' | ') : ''}`);
} catch (e) {
  ok(false, `the browser family could not run: ${e && e.message}`);
} finally {
  if (browser) await browser.close();
  server.close();
}

console.log('DOES IT RHYME: offline verification of /tools/does-it-rhyme/');
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('\nVERIFICATION FAILED'); process.exit(1); }
console.log('\nALL CHECKS PASS');
