// research/i-mutation/verify.mjs
// Offline internal-consistency checks for the i-mutation stratum.
// Run: node research/i-mutation/verify.mjs
//
// What this proves: the dataset is internally consistent with the fronting MAP it
// illustrates - every doublet's mutated vowel is the map's image of its base vowel;
// every mutated form carries a stated i/j-bearing trigger; reconstructions (and only
// reconstructions) carry the asterisk; the predictor answers are the map's images;
// the erasure sequence really erases its trigger; and the data embedded in the page
// is byte-identical to this source of truth (drift guard).
//
// What it does NOT prove: Old English philology. The sound change and doublets are
// established material; the triggers are schematic and individually sourced; the verifier
// catches transcription/consistency errors, it does not re-derive the field.

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { MAP, DOUBLETS, ERASURE, PREDICT, EDGES, DATING, FRAMING, SOURCES } from './data.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); } }

// ── 1. The MAP is well-formed. ───────────────────────────────────────────────
const FRONT = new Set(['e','y','ǣ','ē','ȳ','ie','œ','ø̄']);   // i-mutation reflexes are front vowels
ok(MAP.length >= 6, 'MAP has at least the six core correspondences');
const mapImage = {};
for(const m of MAP){
  ok(typeof m.from === 'string' && m.from.length > 0, `MAP from present (${m.from})`);
  ok(typeof m.to === 'string' && m.to.length > 0, `MAP to present (${m.from}→?)`);
  ok(m.from !== m.to, `MAP ${m.from}→${m.to} actually changes the vowel`);
  ok(FRONT.has(m.to), `MAP target ${m.to} is a front-vowel reflex`);
  ok(['short','long','diph'].includes(m.kind), `MAP ${m.from} has a valid kind`);
  ok(typeof m.gloss === 'string' && m.gloss.length > 10, `MAP ${m.from} has a gloss`);
  // build the image table; this selected illustration assigns each base vowel one reflex
  ok(!(m.from in mapImage), `MAP base ${m.from} appears once`);
  mapImage[m.from] = m.to;
}
// The headline correspondences must be present and correct.
const REQUIRED = { 'ō':'ē', 'ū':'ȳ', 'a':'e', 'u':'y', 'ā':'ǣ' };
for(const [b,r] of Object.entries(REQUIRED)){
  ok(mapImage[b] === r, `MAP has the required correspondence ${b}→${r} (got ${mapImage[b]})`);
}

// ── 2. Every doublet is the map's image. ─────────────────────────────────────
ok(DOUBLETS.length >= 20, `at least 20 doublets (have ${DOUBLETS.length})`);
const seenPairs = new Set();
for(const d of DOUBLETS){
  const tag = `${d.en1}/${d.en2}`;
  ok(!seenPairs.has(tag), `doublet ${tag} is unique`);
  seenPairs.add(tag);
  // base and mut are real map keys, and mut is the image of base
  ok(d.base in mapImage, `doublet ${tag}: base vowel ${d.base} is in the MAP`);
  ok(mapImage[d.base] === d.mut, `doublet ${tag}: ${d.base}→${d.mut} matches the MAP (map says ${d.base}→${mapImage[d.base]})`);
  // the mutated OE form's vowel must be a front reflex (sanity)
  ok(FRONT.has(d.mut), `doublet ${tag}: mutated vowel ${d.mut} is a front reflex`);
  // a trigger is stated and it is a reconstruction (carries *)
  ok(typeof d.trigger === 'string' && d.trigger.length > 1, `doublet ${tag}: has a trigger`);
  ok(d.trigger.startsWith('*'), `doublet ${tag}: trigger ${d.trigger} is marked as reconstructed (*)`);
  // the trigger must contain an i/j to actually CONDITION i-mutation
  ok(/[ij]/.test(d.trigger.normalize('NFD')), `doublet ${tag}: trigger ${d.trigger} contains the i/j that conditions i-mutation`);
  // a grammar category and a gloss and a source
  ok(typeof d.cat === 'string' && d.cat.length > 0, `doublet ${tag}: has a grammar category`);
  ok(typeof d.gloss === 'string' && d.gloss.length > 15, `doublet ${tag}: has a real gloss`);
  ok(typeof d.src === 'string' && /OED|Wright|Wiktionary/.test(d.src), `doublet ${tag}: names a reference`);
  // the OE singular/base form must NOT already be the mutated vowel for the plurals
  // (i.e. the singular keeps the un-fronted vowel - the whole point)
  ok(typeof d.oe1 === 'string' && typeof d.oe2 === 'string', `doublet ${tag}: both OE forms present`);
  ok(d.oe1 !== d.oe2, `doublet ${tag}: the OE base and mutated forms differ`);
}

// The displayed forms follow the cited accounts; vixen has a separate attestation note.
for(const d of DOUBLETS){
  for(const f of [d.en1, d.en2, d.oe1, d.oe2]){
    ok(!f.includes('*'), `display form "${f}" is unstarred; disputed attestation is noted separately`);
  }
}

// ── 3. The required fossil doublets are present. ─────────────────────────────
const must = ['foot/feet','tooth/teeth','goose/geese','man/men','mouse/mice','louse/lice',
              'full/fill','food/feed','long/length','old/elder','fox/vixen'];
for(const m of must) ok(seenPairs.has(m), `the canonical doublet ${m} is present`);

// Grammar categories cover the four mechanisms the page claims.
const cats = new Set(DOUBLETS.map(d => d.cat.replace('*','')));
for(const c of ['plural','causative','noun -þ','comparative']){
  ok(cats.has(c), `the dataset covers the "${c}" mechanism`);
}

// ── 4. The predictor answers are the map's images. ───────────────────────────
ok(PREDICT.length >= 4, 'predictor has at least 4 items');
for(const p of PREDICT){
  ok(p.base in mapImage, `predictor base ${p.base} is in the MAP`);
  ok(mapImage[p.base] === p.answer, `predictor ${p.base}→${p.answer} matches the MAP`);
  ok(/[ij]/.test(p.trigger), `predictor trigger "${p.trigger}" carries an i/j`);
}

// ── 5. The erasure sequence really erases its trigger. ───────────────────────
ok(ERASURE.stages.length >= 4, 'erasure has at least 4 stages');
const st = ERASURE.stages;
ok(st[0].trigger === false && st[0].mutated === false, 'erasure stage 0: bare stem, no trigger, no mutation');
ok(st[1].trigger === true && st[1].mutated === false, 'erasure stage 1: trigger present, not yet mutated');
const firstMut = st.findIndex(s => s.mutated === true);
ok(firstMut > 0, 'erasure: mutation begins AFTER the trigger arrives');
ok(st[firstMut].trigger === true, 'erasure: mutation fires while the trigger is still present');
ok(st[st.length-1].trigger === false, 'erasure: the trigger is GONE by the final stage');
ok(st[st.length-1].mutated === true, 'erasure: the mutation SURVIVES to the final stage');
// once mutated, stays mutated (monotone)
for(let i=firstMut;i<st.length;i++) ok(st[i].mutated === true, `erasure stage ${i}: mutation persists`);
// the final form should be the attested OE plural that the page uses
ok(st[st.length-1].form === 'fēt', 'erasure ends at the attested OE plural fēt');

// ── 6. Honesty apparatus present. ────────────────────────────────────────────
ok(EDGES.length >= 5, 'at least 5 honest-edge sections');
const edgeText = EDGES.map(e => e.h + ' ' + e.t).join(' ').toLowerCase();
ok(EDGES.some(e => /kine/.test(e.h) && /keeps the umlaut/.test(e.t) && /double plural/.test(e.t)), 'edges identify kine as an umlaut-containing double plural');
ok(edgeText.includes('women') || edgeText.includes('woman'), 'edges name the woman/women messy case');
ok(edgeText.includes('closed set') || edgeText.includes('relic'), 'edges call the plurals a closed set of relics');
ok(edgeText.includes('german'), 'edges note German still spells the umlaut');
ok(edgeText.includes('conditioned') || edgeText.includes('trigger'), 'edges state the change is conditioned');
ok(/45?0|5th|onset/.test(DATING.body), 'dating gives the ~450–500 CE onset honestly');
ok(DATING.body.toLowerCase().includes('gothic'), 'dating notes Gothic lacks the change');
ok(DATING.body.toLowerCase().includes('debate'), 'dating admits the chronology is debated');
ok(FRAMING.notNew.toLowerCase().includes('nothing here is a new claim') || FRAMING.notNew.toLowerCase().includes('standard'),
   'framing states this is not a new linguistic claim');
ok(SOURCES.length >= 5, 'at least 5 sources listed');
ok(SOURCES.some(s => s.tag.includes('Campbell')), 'Campbell (the OE grammar) cited');
ok(SOURCES.some(s => s.tag.includes('OED')), 'the OED cited');

// ── 7. Drift guard: the page embeds this exact data. ─────────────────────────
const pagePath = join(__dir, '..', '..', 'public', 'strata', 'i-mutation', 'index.html');
if(existsSync(pagePath)){
  const html = readFileSync(pagePath, 'utf8');
  const DATA_JSON = JSON.stringify({ MAP, DOUBLETS, ERASURE, PREDICT, EDGES, DATING, FRAMING });
  ok(html.includes(DATA_JSON), 'DRIFT GUARD: page embeds byte-identical data from data.mjs');
  ok(html.includes('feet') && html.includes('fēt'), 'page mentions feet / fēt');
  ok(html.includes('i-mutation') || html.includes('i-umlaut'), 'page names the change');
  // every doublet pair should literally appear in the rendered page
  for(const d of DOUBLETS){
    ok(html.includes(d.en1) && html.includes(d.en2), `page renders doublet ${d.en1}/${d.en2}`);
  }
} else {
  console.log('  (page not built yet - run build-page.mjs, then re-run for the drift guard)');
}

// ── report ───────────────────────────────────────────────────────────────────
console.log('');
if(fail === 0){
  console.log(`i-mutation - internal consistency: ${pass} passed, 0 failed`);
  console.log('ALL GREEN - the dataset is internally consistent with the fronting map, the reconstructions are marked, and the page matches the data.');
} else {
  console.log(`i-mutation - internal consistency: ${pass} passed, ${fail} FAILED`);
  for(const f of fails) console.log('  ✗ ' + f);
  process.exit(1);
}
