// research/sing-sang-sung/verify.mjs
// Offline internal-consistency checks for the strong-verbs / ablaut stratum.
// Run: node research/sing-sang-sung/verify.mjs
//
// What this proves:
//   • the wall's strong verbs really show a vowel change with NO dental suffix, while the
//     imposters carry one — i.e. the data illustrates the strong/weak diagnostic, not noise;
//   • every strong wall row has three principal parts and a distinct present vowel;
//   • the seven classes each carry four principal-part slots, an exemplar and modern reflexes;
//     Class VII uses placeholders because it has no single vowel pattern;
//   • the frozen-noun cards each name an ablaut grade (o-grade / zero-grade) and a source;
//   • the diagnostic answers obey the rule (no item is mislabeled), with both polarities;
//   • the Lieberman figures embedded match the paper (177 → 145 → 98; √-frequency law);
//   • the asterisk falls only on reconstructions (PGmc / PIE forms);
//   • DRIFT GUARD: the JSON embedded in the page is byte-identical to this source of truth.
//
// What it does NOT prove: Germanic or Indo-European philology. The forms and reconstructions
// are standard reference material (Wikipedia; Wiktionary; etymonline; Lieberman et al. 2007);
// the verifier catches transcription/consistency errors, it does not re-derive the field.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { META, WALL, CLASSES, FROZEN, FROZEN_PUNCH, DRIFT, DIAGNOSTIC, EDGES, GRIMM, FRAMING, SOURCES, RELATES } from './data.mjs';
import { pageData } from './build-page.mjs';

const __dir = dirname(fileURLToPath(import.meta.url));
let pass = 0, fail = 0; const fails = [];
function ok(cond, msg){ if(cond){ pass++; } else { fail++; fails.push(msg); } }

const ROMAN = ['I','II','III','IV','V','VI','VII'];
const GRADES = ['e-grade','o-grade','zero-grade'];
// a "dental suffix" tell: a past form ending in -t or -d that is NOT just the bare stem.
function hasDentalSuffix(present, past){
  if(!/[td]$/.test(past)) return false;       // must end in a dental
  if(past === present) return false;          // bare-stem (let/cut) — handled separately
  // strong pasts can coincidentally end in -d (e.g. "rode", "stood") but they are formed by
  // vowel change off a present that does NOT end in the same dental; the imposters here are
  // explicitly flagged, so this helper is only a sanity aid, not the classifier.
  return true;
}

// ── 1. META + framing present and well-formed. ─────────────────────────────
ok(typeof META.headline === 'string' && META.headline.length > 4, 'META has a headline');
ok(/^\d{4}-\d{2}-\d{2}$/.test(META.date), 'META has an ISO date');
ok(typeof META.description === 'string' && META.description.length > 40, 'META has a description');

// ── 2. The wall: strong verbs vs imposters. ────────────────────────────────
const strong = WALL.filter(w => !w.imposter);
const imposters = WALL.filter(w => w.imposter);
ok(strong.length >= 6, `at least 6 strong wall verbs (have ${strong.length})`);
ok(imposters.length >= 2, `at least 2 imposters (have ${imposters.length})`);
const heads = new Set();
for(const w of strong){
  const id = w.parts.join('-');
  ok(!heads.has(id), `wall verb ${id} is unique`); heads.add(id);
  ok(Array.isArray(w.parts) && w.parts.length === 3, `${id}: has three principal parts`);
  ok(w.parts.every(p => typeof p === 'string' && p.length > 0), `${id}: all parts non-empty`);
  // a strong verb changes its vowel: present and past differ.
  ok(w.parts[0] !== w.parts[1], `${id}: present and past differ (a real vowel change)`);
  ok(ROMAN.includes(w.cls), `${id}: names a strong class (${w.cls})`);
  ok(typeof w.grades === 'string' && /grade/.test(w.grades), `${id}: states ablaut grades`);
  ok(w.pgmc.includes('*'), `${id}: gives a starred Proto-Germanic form`);
  ok(typeof w.src === 'string' && w.src.length > 3, `${id}: cites a source`);
  // a strong past must NOT be the weak dental type off a non-dental present.
  ok(!hasDentalSuffix(w.parts[0], w.parts[1]) || /[td]$/.test(w.parts[0]),
     `${id}: strong past "${w.parts[1]}" is not a weak dental suffix on "${w.parts[0]}"`);
  if(w.frozen){
    ok(GRADES.includes(w.frozen.grade), `${id}: frozen noun grade is a real ablaut grade (${w.frozen.grade})`);
    ok(typeof w.frozen.noun === 'string' && w.frozen.noun.length > 0, `${id}: frozen noun named`);
    ok(typeof w.frozen.note === 'string' && w.frozen.note.length > 20, `${id}: frozen noun explained`);
  }
}
for(const w of imposters){
  const id = w.parts.join('-');
  ok(w.parts.length === 3, `imposter ${id}: three parts`);
  // the WHOLE point of an imposter: its past carries a dental -t/-d.
  ok(/[td]$/.test(w.parts[1]), `imposter ${id}: past "${w.parts[1]}" carries a dental suffix`);
  ok(typeof w.why === 'string' && /(-t|-d|dental|suffix|weak)/.test(w.why), `imposter ${id}: explains the dental tell`);
  ok(w.cls === '—', `imposter ${id}: is not assigned a strong class`);
}
// the headline verb must be present and correctly shaped.
const singv = strong.find(w => w.parts[0] === 'sing');
ok(!!singv && singv.parts.join(' ') === 'sing sang sung', 'sing/sang/sung is on the wall');
ok(!!singv && singv.frozen && singv.frozen.noun === 'song' && singv.frozen.grade === 'o-grade', 'song is the o-grade of sing on the wall');

// ── 3. The seven classes. ──────────────────────────────────────────────────
ok(CLASSES.length === 7, `exactly seven classes (have ${CLASSES.length})`);
CLASSES.forEach((c, i) => {
  ok(c.n === ROMAN[i], `class ${i} is numbered ${ROMAN[i]} (got ${c.n})`);
  ok(typeof c.env === 'string' && c.env.length > 8, `class ${c.n}: has an environment`);
  ok(Array.isArray(c.pgmc) && c.pgmc.length === 4, `class ${c.n}: four principal-part slots`);
  ok(c.exemplar && c.exemplar.pgmc.includes('*'), `class ${c.n}: starred exemplar`);
  ok(typeof c.exemplar.gloss === 'string' && c.exemplar.gloss.length > 1, `class ${c.n}: exemplar glossed`);
  ok(typeof c.grade === 'string' && c.grade.length > 30, `class ${c.n}: explains its ablaut story`);
  ok(Array.isArray(c.modern) && c.modern.length >= 4, `class ${c.n}: at least 4 modern reflexes`);
  ok(c.modern.every(m => /\/|—/.test(m)), `class ${c.n}: reflexes shown as three-part forms`);
});
// Class III must be the sing class and say so.
const c3 = CLASSES.find(c => c.n === 'III');
ok(/sing/.test(c3.grade) || c3.modern.some(m => /sing/.test(m)), 'Class III is identified as the sing class');
// Class VII is reduplicating (its pattern is shown as dashes, explained in prose).
const c7 = CLASSES.find(c => c.n === 'VII');
ok(c7.pgmc.every(v => v === '—'), 'Class VII shows no single vowel pattern (reduplicating)');
ok(/reduplicat/i.test(c7.grade), 'Class VII grade explains reduplication');
// Classes IV and V must name the long-ē-is-Germanic caveat somewhere in the data.
const allGradeText = CLASSES.map(c => c.grade).join(' ').toLowerCase();
ok(/germanic innovation|arose inside germanic|not.*pie lengthened|germanic, not pie/.test(allGradeText),
   'classes name the Germanic-innovation caveat for the long ē');

// ── 4. The frozen o-grade cards. ───────────────────────────────────────────
ok(FROZEN.length >= 5, `at least 5 frozen-noun cards (have ${FROZEN.length})`);
const fseen = new Set();
for(const f of FROZEN){
  ok(!fseen.has(f.verb + f.noun), `frozen ${f.verb}/${f.noun} is unique`); fseen.add(f.verb + f.noun);
  ok(GRADES.includes(f.grade), `frozen ${f.verb}/${f.noun}: real ablaut grade (${f.grade})`);
  ok(typeof f.note === 'string' && f.note.length > 25, `frozen ${f.verb}/${f.noun}: has a real note`);
  ok(typeof f.src === 'string' && /Wiktionary|etymonline/i.test(f.src), `frozen ${f.verb}/${f.noun}: cites a lexical source`);
}
// sing→song and ride→road are the explicitly-labeled o-grades; both must be present.
ok(FROZEN.some(f => f.verb === 'sing' && f.noun === 'song' && f.grade === 'o-grade'), 'frozen: sing→song (o-grade)');
ok(FROZEN.some(f => f.verb === 'ride' && f.noun === 'road' && f.grade === 'o-grade'), 'frozen: ride→road (o-grade)');
// at least one zero-grade card (the contrast).
ok(FROZEN.some(f => f.grade === 'zero-grade'), 'frozen: at least one zero-grade card for contrast');
ok(typeof FROZEN_PUNCH === 'string' && FROZEN_PUNCH.length > 60, 'the frozen-section punch line is present');

// ── 5. The drift (Lieberman figures pinned to the paper). ──────────────────
const L = DRIFT.lieberman;
ok(L.tracked === 177 && L.middle === 145 && L.modern === 98, 'Lieberman counts are 177 → 145 → 98');
ok(L.modern < L.middle && L.middle < L.tracked, 'the counts strictly decrease (verbs regularize away)');
ok(Math.abs(L.lawSlope + 0.5) < 0.1, 'the regularization-rate slope is ≈ −0.5 (inverse √-frequency)');
ok(/square root|√|half-life/.test(DRIFT.body), 'the drift body states the √-frequency / half-life law');
ok(/177/.test(DRIFT.body) && /98/.test(DRIFT.body), 'the drift body carries the headline counts');
ok(DRIFT.cells.length >= 3 && DRIFT.cells.every(c => c.n && c.l), 'drift stat cells are well-formed');
// the frequency axis: positions ascend, doomed at the low end, safe at the high end.
ok(DRIFT.freq.length >= 4, 'the frequency axis has at least 4 ticks');
let prevPos = -1;
for(const t of DRIFT.freq){
  ok(typeof t.pos === 'number' && t.pos >= 0 && t.pos <= 100, `freq tick "${t.v}": position in [0,100]`);
  ok(t.pos > prevPos, `freq tick "${t.v}": positions strictly ascend (${prevPos}→${t.pos})`);
  prevPos = t.pos;
  ok(['doomed','mid','safe'].includes(t.band), `freq tick "${t.v}": valid band`);
}
ok(DRIFT.freq[0].band === 'doomed' && DRIFT.freq.at(-1).band === 'safe', 'the rare end is doomed, the common end safe');
ok(DRIFT.freq.some(t => /wed/.test(t.v)), 'the axis names "wed" (the paper\'s next-domino)');
// born-by-analogy: each names an older weak form and a newer strong-looking one.
ok(DRIFT.born.length >= 3, 'at least 3 born-by-analogy forms');
for(const b of DRIFT.born){ ok(b.from && b.to && b.from !== b.to && b.by.length > 20, `born ${b.from}→${b.to}: well-formed with a reason`); }
// the snuck caveat must be honest (its analogy is contested).
const snuck = DRIFT.born.find(b => b.to === 'snuck');
ok(!!snuck && /unknown|guess|not a fact|contested|Merriam/i.test(snuck.by), 'the snuck entry flags its contested origin');

// ── 6. The diagnostic obeys the rule and has both polarities. ──────────────
ok(DIAGNOSTIC.length >= 6, `at least 6 diagnostic items (have ${DIAGNOSTIC.length})`);
for(const d of DIAGNOSTIC){
  ok(typeof d.form === 'string' && d.form.length > 1, `diagnostic "${d.form}": has a form`);
  ok(typeof d.strong === 'boolean', `diagnostic "${d.form}": strong is boolean`);
  ok(typeof d.why === 'string' && d.why.length > 20, `diagnostic "${d.form}": has an explanation`);
  // honesty of the answer key: a WEAK answer must point at a dental/suffix; a STRONG answer
  // must claim a vowel change or class (and not call itself weak).
  if(d.strong){ ok(/vowel|class|strong/i.test(d.why), `diagnostic "${d.form}": strong reason cites vowel/class`); }
  else { ok(/-t|-d|dental|suffix|weak/i.test(d.why), `diagnostic "${d.form}": weak reason cites the dental suffix`); }
}
ok(DIAGNOSTIC.some(d => d.strong) && DIAGNOSTIC.some(d => !d.strong), 'diagnostic has both strong and weak items');
// the two signature surprises must be present and correctly keyed.
ok(DIAGNOSTIC.some(d => d.form === 'cut' && d.strong === false), 'diagnostic: "cut" is keyed weak');
ok(DIAGNOSTIC.some(d => d.form === 'let' && d.strong === true), 'diagnostic: "let" is keyed strong (leveled Class VII)');
ok(DIAGNOSTIC.some(d => d.form === 'brought' && d.strong === false), 'diagnostic: "brought" is keyed weak');

// ── 7. Honesty apparatus + sources. ────────────────────────────────────────
ok(EDGES.length >= 5, `at least 5 honest edges (have ${EDGES.length})`);
const edgeText = EDGES.map(e => e.h + ' ' + e.t).join(' ').toLowerCase();
ok(/drift|selection|newberry/.test(edgeText), 'edges name the drift-vs-selection caveat');
ok(/definition-dependent|approximate|popularized|memory aid/.test(edgeText), 'edges name that the counts are approximate');
ok(/inferred|read off|standard inference/.test(edgeText), 'edges admit which ablaut grades are inferred');
ok(/-ed|dental suffix|controversial|do\b|dōn/.test(edgeText), 'edges name the open problem of the -ed suffix');
// Grimm the man, dated, with the 1819 coinage.
ok(/1785/.test(GRIMM.who) && /1863/.test(GRIMM.who), 'Grimm dated 1785–1863');
ok(/1819/.test(GRIMM.body) && /Deutsche Grammatik/.test(GRIMM.body), 'the 1819 Deutsche Grammatik coinage is named');
ok(/Grimm's Law|consonant shift/.test(GRIMM.body), 'the tie to Grimm\'s Law is drawn');
ok(typeof FRAMING.whatsNew === 'string' && typeof FRAMING.notNew === 'string' && typeof FRAMING.check === 'string', 'framing present');
ok(/Lieberman/.test(FRAMING.notNew) && /Newberry/.test(FRAMING.notNew), 'framing names both the source and its caveat');
ok(SOURCES.length >= 7, `at least 7 sources (have ${SOURCES.length})`);
ok(SOURCES.some(s => /Lieberman/.test(s.t) && s.u), 'a Lieberman source carries a URL');
ok(SOURCES.some(s => /Newberry/.test(s.t) && s.u), 'the Newberry caveat is sourced');
ok(SOURCES.some(s => /Germanic strong verb/.test(s.t) && s.u), 'the strong-verb reference is sourced');
ok(RELATES.length >= 3 && RELATES.every(r => r.u.startsWith('/strata/')), 'relates point at real strata');

// ── 8. The asterisk falls only on reconstructions. ─────────────────────────
// Collect every starred token in the dataset; each must be a PGmc/PIE-style form
// (a leading * on a letter), never a stray asterisk in prose.
const blob = JSON.stringify(pageData());
const stars = blob.match(/\*[A-Za-zĀ-ɏʰ̥ǣēīōūþðǭ-]+/g) || [];
ok(stars.length > 0, 'the dataset contains starred reconstructions (it is about deep history)');
for(const s of stars.slice(0, 200)){
  ok(/^\*[A-Za-zĀ-ɏʰ̥ǣēīōūþðǭ.-]+$/.test(s), `starred token ${s} looks like a reconstruction, not stray prose`);
}

// ── 9. DRIFT GUARD: page JSON == source of truth. ──────────────────────────
const PAGE = join(__dir, '..', '..', 'public', 'strata', 'sing-sang-sung', 'index.html');
let pageHtml = '';
try { pageHtml = readFileSync(PAGE, 'utf8'); } catch { /* handled below */ }
ok(pageHtml.length > 0, 'the immersive page exists and is readable');
const m = pageHtml.match(/<script id="awdata" type="application\/json">([\s\S]*?)<\/script>/);
ok(!!m, 'the page carries an awdata JSON block');
if(m){
  ok(m[1] !== '__AWDATA__', 'the awdata block has been filled (run build-page.mjs)');
  const expected = JSON.stringify(pageData());
  ok(m[1] === expected, 'DRIFT GUARD: page JSON is byte-identical to data.mjs (run build-page.mjs after edits)');
  if(m[1] !== '__AWDATA__'){
    let parsed = null; try { parsed = JSON.parse(m[1]); } catch {}
    ok(parsed && Array.isArray(parsed.WALL) && parsed.WALL.length === WALL.length, 'page JSON parses and carries the wall');
  }
}

// ── report ──────────────────────────────────────────────────────────────────
console.log(`\nThe Song Inside the Verb — internal-consistency checks`);
console.log(`  passed: ${pass}`);
console.log(`  failed: ${fail}`);
if(fail){ console.log('\nFAILURES:'); for(const f of fails) console.log('  ✗ ' + f); process.exit(1); }
console.log('\n  all green — the dataset is internally consistent and the page is in sync.\n');
