#!/usr/bin/env node
// Verifier for /strata/two-words-in-every-five/.
//
// Re-derives the page's figures WITHOUT importing the pipeline that produced
// them wherever that is possible (its own dictionary reader, its own tokeniser
// call, its own entropy), then reads the shipped page and the shipped data file
// and asserts that what a reader sees is what was computed. Reaches no network.
//
//   node research/spell-it-as-it-sounds/verify-two-words-in-every-five.mjs

import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import * as L from './lib.mjs';
import { classifyPair, classifySpelling } from './classify.mjs';

const SLUG = 'two-words-in-every-five';
const PUB = join(L.REPO, 'public', 'strata', SLUG);

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}  ${detail}`); }
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log(`\nverify ${SLUG}\n`);

// ---------------------------------------------------------------------------
// 0. The instrument must be able to fail. Known pairs, known verdicts.
// ---------------------------------------------------------------------------
console.log('the classifier, on cases whose answer is known in advance');
{
  const P = (s) => s.split(' ');
  const cases = [
    ['THE, weak against strong', P('DH AH0'), P('DH IY1'), true, 'weak-form'],
    ['WHICH, the hw of whine', P('W IH1 CH'), P('HH W IH1 CH'), true, 'wh'],
    ['NEW, yod-dropping', P('N UW1'), P('N Y UW1'), true, 'yod'],
    ['LAW, cot against caught', P('L AO1'), P('L AA1'), true, 'cot-caught'],
    ['RECORD, the noun against the verb', P('R EH1 K ER0 D'), P('R AH0 K AO1 R D'), true, 'stress-shift'],
    ['READ, present against past', P('R IY1 D'), P('R EH1 D'), false, null],
    ['LIVE, adjective against verb', P('L AY1 V'), P('L IH1 V'), false, null],
    ['BOW, the two bows', P('B AW1'), P('B OW1'), false, null],
  ];
  for (const [name, a, b, expectExplained, expectRule] of cases) {
    const c = classifyPair(a, b);
    const good = c.explained === expectExplained
      && (!expectRule || c.rules.includes(expectRule));
    ok(name, good, `explained=${c.explained} rules=[${c.rules.join(',')}]`);
  }
  // A rule that fires on everything would explain READ too. It does not.
  ok('the catalogue does not explain everything',
    !classifyPair(P('R IY1 D'), P('R EH1 D')).explained);
}

// ---------------------------------------------------------------------------
// 1. An independent read of the two inputs
// ---------------------------------------------------------------------------
console.log('\nthe inputs, read again from scratch');
const raw = readFileSync(L.CMUDICT_PATH, 'utf8').split('\n')
  .filter((l) => l && !l.startsWith(';;;'));
const entries = new Map();
for (const line of raw) {
  const m = line.match(/^(\S+)\s+(.*)$/);
  if (!m) continue;
  const word = m[1].replace(/\(\d+\)$/, '').toLowerCase();
  const phones = m[2].trim().split(/\s+/).filter((p) => /^[A-Z]+[0-9]?$/.test(p));
  if (!phones.length) continue;
  if (!entries.has(word)) entries.set(word, []);
  entries.get(word).push(phones);
}
ok('cmudict spellings', entries.size === 126052, String(entries.size));
ok('cmudict entries', [...entries.values()].reduce((a, v) => a + v.length, 0) === 135166);

const books = L.loadNovels();
ok('eight novels present', books.length === 8, books.map((b) => b.year).join(' '));
const canon = L.loadCanon();
ok('the Holmes canon present', canon.count === 9 && canon.tokens.length > 400000,
  `${canon.count} volumes, ${canon.tokens.length.toLocaleString()} words`);

const tokens = [];
for (const b of books) for (const t of b.tokens) tokens.push(t);
for (const t of canon.tokens) tokens.push(t);
const freq = new Map();
for (const t of tokens) freq.set(t, (freq.get(t) || 0) + 1);

// ---------------------------------------------------------------------------
// 2. The numbers, recomputed here
// ---------------------------------------------------------------------------
console.log('\nthe numbers, recomputed');
let inDict = 0, multi = 0;
for (const [w, c] of freq) {
  if (!entries.has(w)) continue;
  inDict += c;
  if (entries.get(w).length > 1) multi += c;
}
const multiPct = multi / inDict * 100;

// homophone side, on the single-pronunciation sub-corpus
const strip = (p) => p.map((x) => x.replace(/[0-9]$/, '')).join(' ');
const classes = new Map();
let singleMass = 0;
for (const [w, c] of freq) {
  const e = entries.get(w);
  if (!e || e.length !== 1) continue;
  singleMass += c;
  const k = strip(e[0]);
  if (!classes.has(k)) classes.set(k, []);
  classes.get(k).push(c);
}
let merged = 0, bits = 0;
for (const counts of classes.values()) {
  if (counts.length < 2) continue;
  const tot = counts.reduce((a, b) => a + b, 0);
  merged += tot;
  let h = 0;
  for (const n of counts) { const p = n / tot; h -= p * Math.log2(p); }
  bits += tot * h;
}
const bitsPerWord = bits / singleMass;

let wordBits = 0;
for (const c of freq.values()) { const p = c / tokens.length; wordBits -= p * Math.log2(p); }

let letters = 0, phones = 0, weighed = 0, rTokens = 0;
const VOW = L.ARPA_VOWELS;
for (const [w, c] of freq) {
  const e = entries.get(w);
  if (!e) continue;
  const p = e[0].map((x) => x.replace(/[0-9]$/, ''));
  letters += c * w.replace(/'/g, '').length;
  phones += c * p.length;
  weighed += c;
  for (let i = 0; i < p.length; i++) {
    if (p[i] === 'ER' || (p[i] === 'R' && !VOW.has(p[i + 1] || ''))) { rTokens += c; break; }
  }
}

// ---------------------------------------------------------------------------
// 3. Against the committed results
// ---------------------------------------------------------------------------
const R = JSON.parse(readFileSync(join(L.HERE, 'data', 'results.json'), 'utf8'));
ok('corpus size', R.corpus.tokens === tokens.length, tokens.length.toLocaleString());
ok('dictionary coverage', near(R.corpus.inDictPct, inDict / tokens.length * 100, 1e-9),
  (inDict / tokens.length * 100).toFixed(2) + '%');
ok('more than one reading', near(R.ladder.multiPct, multiPct, 1e-9), multiPct.toFixed(2) + '%');
ok('words in a homophone class', near(R.homophones.mergedPct, merged / singleMass * 100, 1e-9),
  (merged / singleMass * 100).toFixed(2) + '%');
ok('H(spelling | sound)', near(R.homophones.bitsPerToken, bitsPerWord, 1e-9),
  bitsPerWord.toFixed(4) + ' bits/word');
ok('H(word)', near(R.homophones.wordEntropy, wordBits, 1e-9), wordBits.toFixed(3) + ' bits/word');
ok('letters per word', near(R.length.lettersPerWord, letters / weighed, 1e-9),
  (letters / weighed).toFixed(3));
ok('phonemes per word', near(R.length.phonemesPerWord, phones / weighed, 1e-9),
  (phones / weighed).toFixed(3));
ok('non-prevocalic R', near(R.rhotic.pct, rTokens / weighed * 100, 1e-9),
  (rTokens / weighed * 100).toFixed(2) + '%');

// the audit has to cover the residue and its labels have to sum
console.log('\nthe hand audit');
const audit = new Map();
for (const line of readFileSync(join(L.HERE, 'residue-audit.tsv'), 'utf8').split('\n')) {
  if (!line.trim() || line.startsWith('#')) continue;
  const [w, label] = line.split('\t');
  audit.set(w, label);
}
const labels = new Set(['homograph', 'case', 'variation', 'artefact']);
ok('every audit label is one of the four', [...audit.values()].every((l) => labels.has(l)));

// Recompute the residue here, so the audit is checked against a fresh run of the
// classifier rather than against the list the same run wrote out.
let residueMass = 0, residueWords = 0;
const auditMass = { homograph: 0, case: 0, variation: 0, artefact: 0 };
const unaudited = [];
for (const [w, c] of freq) {
  const e = entries.get(w);
  if (!e || e.length < 2) continue;
  if (classifySpelling(e, w).nGroups === 1) continue;
  residueMass += c; residueWords++;
  const l = audit.get(w);
  if (!l) unaudited.push(w); else auditMass[l] += c;
}
ok('the audit covers the residue exactly',
  unaudited.length === 0 && audit.size === residueWords,
  `${residueWords} spellings, ${audit.size} audited, ${unaudited.length} missing`);
ok('residue mass', near(R.ladder.residuePct, residueMass / inDict * 100, 1e-9),
  (residueMass / inDict * 100).toFixed(3) + '%');
ok('homograph mass', near(R.ladder.audit.homograph.tokens, auditMass.homograph, 0)
  && near(R.ladder.audit.case.tokens, auditMass.case, 0),
  ((auditMass.homograph + auditMass.case) / inDict * 100).toFixed(3) + '% including case');
ok('the four labels sum to the residue',
  Object.values(auditMass).reduce((a, b) => a + b, 0) === residueMass);

// ---------------------------------------------------------------------------
// 4. The page a reader actually gets
// ---------------------------------------------------------------------------
console.log('\nthe shipped page');
const html = readFileSync(join(PUB, 'index.html'), 'utf8');
const js = readFileSync(join(PUB, 'page.js'), 'utf8');
const data = JSON.parse(readFileSync(join(PUB, 'data.json'), 'utf8'));
const lexText = readFileSync(join(PUB, 'lexicon.txt'), 'utf8');

ok('data.json matches results.json on the ladder',
  data.ladder.multiPct === R.ladder.multiPct && data.ladder.residuePct === R.ladder.residuePct);
ok('data.json matches results.json on the bits',
  data.homophones.bitsPerToken === R.homophones.bitsPerToken);

// Every figure written into the page's own prose, checked against the data.
const homPct = R.ladder.audit.homograph.pct + R.ladder.audit.case.pct;
const inPage = [
  ['2,193,841 words in the kicker', String(R.corpus.tokens.toLocaleString())],
  ['2.19 million in the description', '2.19 million'],
  ['0.0708 bits', R.homophones.bitsPerToken.toFixed(4)],
  ['one part in 139', 'one part in ' + Math.round(R.homophones.partsOfAWord)],
  ['0.21% homographs', homPct.toFixed(2) + '%'],
  ['39.28% multi-reading', R.ladder.multiPct.toFixed(2) + '%'],
  ['14.39% non-prevocalic R', R.rhotic.pct.toFixed(2) + '%'],
];
for (const [name, needle] of inPage) ok(name + ' appears in the page', html.includes(needle), needle);

// The respelling table must cover every phoneme the lexicon can emit, or a word
// would silently come out with a question mark in it.
const spellKeys = new Set([...js.matchAll(/\b([A-Z]{1,2}):\s*'/g)].map((m) => m[1]));
const missingSpell = data.phonemes.filter((p) => !spellKeys.has(p));
ok('page.js spells every phoneme', missingSpell.length === 0, missingSpell.join(' ') || 'all 39');
ok('the shipped alphabet is one character per phoneme',
  data.code.length === data.phonemes.length && new Set(data.code).size === data.code.length);

// Decode the lexicon the way the browser does and check a few words come back.
const codeToPhone = new Map([...data.code].map((ch, i) => [ch, data.phonemes[i]]));
const lex = new Map();
for (const line of lexText.split('\n')) {
  if (!line || line[0] === '#') continue;
  const [w, prons, rung] = line.split('\t');
  if (w) lex.set(w, { prons: prons ? prons.split('|') : [], rung });
}
const dec = (s) => [...s].map((ch) => codeToPhone.get(ch)).join(' ');
const spot = [
  ['knight', 'N AY T'],
  ['through', 'TH R UW'],
  ['colonel', 'K ER N AH L'],
  ['read', 'R IY D'],
];
for (const [w, want] of spot) {
  const e = lex.get(w);
  ok(`lexicon decodes ${w}`, !!e && e.prons.some((p) => dec(p) === want),
    e ? e.prons.map(dec).join(' / ') : 'missing');
}
ok('read is marked a homograph in the lexicon', lex.get('read')?.rung === 'homograph');
ok('the is marked a weak form', lex.get('the')?.rung === 'weak-form');
ok('lexicon size', lex.size === data.lexiconWords, lex.size.toLocaleString() + ' words');

// The passages have to be spellable, or the instrument opens on a page of dots.
console.log('\nthe passages the instrument opens with');
for (const p of data.passages) {
  const words = L.tokenise(p.text);
  const miss = words.filter((w) => !lex.has(w));
  ok(p.title, miss.length === 0, `${words.length} words, ${miss.length} unknown ${miss.join(' ')}`);
}

// ---------------------------------------------------------------------------
// 5. The controls
// ---------------------------------------------------------------------------
console.log('\nthe controls');
ok('positive control returns zero on respelt text', R.controls.phonemicMergedTokens === 0);
ok('the web-unigram corpus agrees within 6 points on the ladder',
  Math.abs(R.controls.webUnigrams.multiPct - R.ladder.multiPct) < 6,
  R.controls.webUnigrams.multiPct.toFixed(2) + '% against ' + R.ladder.multiPct.toFixed(2) + '%');
ok("this site's own prose agrees within 6 points",
  Math.abs(R.controls.ownProse.multiPct - R.ladder.multiPct) < 6,
  R.controls.ownProse.multiPct.toFixed(2) + '% against ' + R.ladder.multiPct.toFixed(2) + '%');
ok('the residue is small in all three corpora',
  R.controls.webUnigrams.residuePct < 5 && R.controls.ownProse.residuePct < 5 && R.ladder.residuePct < 5);

// A negative control for the corpus reader: the strata directory must exist and
// be non-trivial, or "this site's own prose" was measured on nothing.
const strata = readdirSync(join(L.REPO, 'src', 'content', 'strata')).filter((f) => f.endsWith('.md'));
ok('the own-prose control read a real corpus', strata.length > 500, strata.length + ' files');

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