// research/grassmann/verify.mjs
// Offline internal-consistency checks for the Grassmann's-law stratum.
// Run: node research/grassmann/verify.mjs
//
// What this proves:
//   • the aspirate inventory is well-formed (each aspirate maps to a distinct plain stop);
//   • every WALL item really has its FIRST stop deaspirated and (where a second stop is
//     present) its second stop retained — i.e. the data illustrates dissimilation, not noise;
//   • the θρίξ derivation's breath-count falls exactly where the rule says, the genitive
//     fires Grassmann and the nominative does not, and the two paths end on θ vs τ;
//   • the dissimilation ENGINE that the page runs (re-implemented here) reproduces the
//     stated nominative / genitive / reduplication / single-aspirate outcomes;
//   • the PREDICT answers agree with that same engine;
//   • the asterisk falls only on reconstructions (PIE roots / starred etyma);
//   • DRIFT GUARD: the JSON embedded in the page is byte-identical to this source of truth.
//
// What it does NOT prove: Greek or Indo-Iranian philology. The forms and reconstructions
// are standard reference material (Grassmann 1863; Sihler; Fortson; Smyth; LIV²); 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 { ASPIRATES, WALL, THRIX, PARALLELS, MACHINE_CASES, PREDICT, EDGES, GRASSMANN, FRAMING, SOURCES } 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); } }

// ── The rule engine, ONE definition, shared by page and verifier in spirit. ──
// (The page carries a structurally identical copy in its own JS; the MACHINE_CASES
// below pin the two together so they cannot drift apart silently.)
function grassmannFires(s1asp, s2asp, s2beforeS){
  const surf2 = s2asp && !s2beforeS;   // an aspirate loses its breath before -s
  const surf1 = s1asp;
  return surf1 && surf2;               // two surfacing breaths in a row → law fires
}

// ── 1. Aspirate inventory is well-formed. ───────────────────────────────────
ok(ASPIRATES.length >= 6, `aspirate inventory has at least 6 entries (has ${ASPIRATES.length})`);
const plainOf = {};
for(const a of ASPIRATES){
  ok(['Greek','Sanskrit'].includes(a.lang), `aspirate ${a.asp} is Greek or Sanskrit`);
  ok(a.asp !== a.plain, `aspirate ${a.asp} differs from its plain stop ${a.plain}`);
  ok(typeof a.glyphAsp === 'string' && a.glyphAsp.length >= 1, `aspirate ${a.asp} has an aspirated glyph`);
  ok(typeof a.glyphPlain === 'string' && a.glyphPlain.length >= 1, `aspirate ${a.asp} has a plain glyph`);
  ok(['voiced','voiceless'].includes(a.voice), `aspirate ${a.asp} has a voice value`);
  ok(typeof a.note === 'string' && a.note.length > 10, `aspirate ${a.asp} has a note`);
  ok(!(a.asp in plainOf), `aspirate ${a.asp} listed once`);
  plainOf[a.asp] = a.plain;
}
// the three Greek aspirated stops we actually use
for(const [asp, pl] of [['pʰ','p'],['tʰ','t'],['kʰ','k'],['bh','b'],['dh','d'],['gh','g']]){
  ok(plainOf[asp] === pl, `inventory maps ${asp} → ${pl} (got ${plainOf[asp]})`);
}

// ── 2. Every WALL item illustrates dissimilation of the FIRST stop. ─────────
ok(WALL.length >= 5, `at least 5 wall items (have ${WALL.length})`);
const seen = new Set();
for(const w of WALL){
  ok(!seen.has(w.id), `wall id ${w.id} is unique`); seen.add(w.id);
  ok(typeof w.head === 'string' && w.head.length > 0, `${w.id}: has a head`);
  ok(typeof w.translit === 'string' && w.translit.length > 0, `${w.id}: has a transliteration`);
  ok(typeof w.gloss === 'string' && w.gloss.length > 3, `${w.id}: has a gloss`);
  ok(typeof w.blurb === 'string' && w.blurb.length > 40, `${w.id}: has a real blurb`);
  ok(typeof w.src === 'string' && w.src.length > 3, `${w.id}: cites a source`);
  // `stepped` names a deaspiration (contains an aspirate symbol and a "→")
  ok(/→/.test(w.stepped), `${w.id}: 'stepped' shows a change (→)`);
  ok(/[ʰh]/.test(w.stepped), `${w.id}: 'stepped' starts from an aspirate (has a breath mark)`);
  // the surviving stop is named and itself an aspirate (the breath that stayed).
  // (In reduplication — πέφυκα — the two stops are the SAME phoneme pʰ; that is the
  // point, so we do NOT require them to be distinct.)
  ok(/[ʰh]/.test(w.survived), `${w.id}: 'survived' is the breath that stayed`);
  // every underlying form, where given, carries an asterisk (it is a reconstruction)
  if(w.underlying){ ok(w.underlying.includes('*'), `${w.id}: underlying form ${w.underlying} is starred (reconstruction)`); }
}
// the headline example must be present and correctly shaped
const thrix = WALL.find(w => w.id === 'thrix');
ok(!!thrix && thrix.head.includes('θρίξ') && thrix.head.includes('τριχός'), `the θρίξ ~ τριχός alternation is on the wall`);
const budh = WALL.find(w => w.id === 'budh');
ok(!!budh && budh.underlying === '*bʰewdʰ-', `the Buddha root *bʰewdʰ- is on the wall`);

// ── 3. The θρίξ derivation is internally exact. ─────────────────────────────
ok(THRIX.nom.fired === false, 'θρίξ: the nominative does NOT fire Grassmann');
ok(THRIX.gen.fired === true,  'τριχός: the genitive DOES fire Grassmann');
// each path: aspirate count is monotone non-increasing and ends at 1
for(const [name, col] of [['nom', THRIX.nom], ['gen', THRIX.gen]]){
  let prev = Infinity;
  for(const s of col.stages){
    ok(typeof s.aspirates === 'number', `${name}: every stage states an aspirate count`);
    ok(s.aspirates <= prev, `${name}: aspirate count never rises (${prev}→${s.aspirates})`);
    prev = s.aspirates;
  }
  ok(col.stages[0].aspirates === 2, `${name}: starts from the two-aspirate stem`);
  ok(col.stages[col.stages.length-1].aspirates === 1, `${name}: ends with one surviving breath`);
  ok(col.stages[col.stages.length-1].final === true, `${name}: last stage is marked final`);
}
// exactly the genitive path has a stage marked as the law firing
ok(THRIX.gen.stages.some(s => s.grassmann === true), 'τριχός path marks the Grassmann step');
ok(!THRIX.nom.stages.some(s => s.grassmann === true), 'θρίξ path has no Grassmann step');
// the two paths end on the right Greek words
ok(THRIX.nom.stages.at(-1).form.includes('θρίξ'), 'nominative path ends at θρίξ (θ kept)');
ok(THRIX.gen.stages.at(-1).form.includes('τριχός'), 'genitive path ends at τριχός (τ — θ gone)');

// ── 4. The engine reproduces the canonical machine cases. ───────────────────
for(const c of MACHINE_CASES){
  const fires = grassmannFires(c.s1asp, c.s2asp, c.s2beforeS);
  ok(fires === c.fires, `engine: ${c.id} (${c.label}) fires=${fires}, expected ${c.fires}`);
}
// the three named cases must behave as the textbook says
const gen = MACHINE_CASES.find(c => c.id === 'gen');
const nom = MACHINE_CASES.find(c => c.id === 'nom');
const redup = MACHINE_CASES.find(c => c.id === 'redup');
ok(grassmannFires(gen.s1asp, gen.s2asp, gen.s2beforeS) === true,  'engine: τριχός fires');
ok(grassmannFires(nom.s1asp, nom.s2asp, nom.s2beforeS) === false, 'engine: θρίξ (before -s) does not fire');
ok(grassmannFires(redup.s1asp, redup.s2asp, redup.s2beforeS) === true, 'engine: τίθημι reduplication fires');
// the θρίξ machine cases must agree with the THRIX stepper's fired flags
ok(grassmannFires(gen.s1asp, gen.s2asp, gen.s2beforeS) === THRIX.gen.fired, 'machine gen agrees with stepper gen');
ok(grassmannFires(nom.s1asp, nom.s2asp, nom.s2beforeS) === THRIX.nom.fired, 'machine nom agrees with stepper nom');

// ── 5. PREDICT answers agree with the rule (and are well-formed). ───────────
ok(PREDICT.length >= 5, `at least 5 predictor items (have ${PREDICT.length})`);
for(const p of PREDICT){
  ok(typeof p.q === 'string' && p.q.length > 5, `predict "${p.q}": has a prompt`);
  ok(typeof p.fires === 'boolean', `predict "${p.q}": fires is boolean`);
  ok(typeof p.front === 'string' && p.front.length >= 1, `predict "${p.q}": names the surfacing front stop`);
  ok(typeof p.note === 'string' && p.note.length > 10, `predict "${p.q}": has an explanation`);
  // when it fires, the front stop must be PLAIN (no breath); when not, it keeps a breath
  if(p.fires){ ok(!/[ʰ]/.test(p.front) && !/bh|dh|gh|kh|th|ph/.test(p.front), `predict "${p.q}": firing → plain front stop (${p.front})`); }
  else { ok(/[ʰ]|φ|θ|χ|bh|dh|gh/.test(p.front), `predict "${p.q}": not firing → front keeps its breath (${p.front})`); }
}
// the predictor must contain at least one firing and one non-firing item
ok(PREDICT.some(p => p.fires) && PREDICT.some(p => !p.fires), 'predictor has both firing and non-firing cases');

// ── 6. The parallels table is three-branch and starred where reconstructed. ─
ok(PARALLELS.cols.length === 4, 'parallels table has four columns');
ok(PARALLELS.rows.length >= 3, `parallels table has at least 3 roots (has ${PARALLELS.rows.length})`);
for(const r of PARALLELS.rows){
  ok(r.pie.includes('*'), `parallel root ${r.pie} is starred (reconstruction)`);
  for(const k of ['skt','grk','gmc','note','law']){ ok(typeof r[k] === 'string' && r[k].length > 0, `parallel ${r.pie}: has ${k}`); }
}
// the headline Buddha root must be present and tie Sanskrit budh to the law
const bp = PARALLELS.rows.find(r => r.pie.includes('bʰewdʰ'));
ok(!!bp && /budh/.test(bp.skt), 'parallels: *bʰewdʰ- → Sanskrit budh- present');

// ── 7. Honesty apparatus is present and names the key uncertainties. ────────
ok(EDGES.length >= 5, `at least 5 honest edges (have ${EDGES.length})`);
const edgeText = EDGES.map(e => e.h + ' ' + e.t).join(' ').toLowerCase();
ok(/independent|not inherited|parallel|separately/.test(edgeText), 'edges name the independent-development point');
ok(/de decker|chronolog|date|argued/.test(edgeText), 'edges name the Greek chronology uncertainty');
ok(/aspirated stop|fricative|\/p|pʰ|not the modern/.test(edgeText), 'edges note ancient φ θ χ were stops, not fricatives');
ok(/does not|not re-prove|reconstruction/.test(edgeText), 'edges state what the check does NOT do');
// Grassmann the man, dated, with the 1863 paper
ok(GRASSMANN.dates.includes('1809') && GRASSMANN.dates.includes('1877'), 'Grassmann dated 1809–1877');
ok(/1863/.test(GRASSMANN.paper) && /Aspiraten/.test(GRASSMANN.paper), 'the 1863 paper is cited with its title');
ok(/Ausdehnungslehre|exterior|Grassmann number|algebra/.test(GRASSMANN.body), 'the mathematician half is told');
ok(/rigveda|sanskrit/i.test(GRASSMANN.body), 'the Sanskritist half is told');
ok(typeof FRAMING.whatsNew === 'string' && typeof FRAMING.notNew === 'string', 'framing present');
ok(SOURCES.length >= 5, `at least 5 sources (have ${SOURCES.length})`);
ok(SOURCES.some(s => /grassmann/i.test(s.t) && s.u), 'a Grassmann-law source has a URL');

// ── 8. DRIFT GUARD: page JSON == source of truth. ───────────────────────────
const PAGE = join(__dir, '..', '..', 'public', 'strata', 'grassmann', '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)');
  // and the page must actually parse it
  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(`\nGrassmann's law — 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');
