// research/the-cause-you-read-backwards/verify.mjs
// Offline verifier for the portal "The Cause You Read Backwards".
//
//   node research/the-cause-you-read-backwards/verify.mjs
//
// It does NOT prove historical linguistics. It proves this portal is internally
// consistent with the four member datasets it imports, that the Grimm inversion the
// reconstruction engine uses round-trips (and is one-to-one in the initial position
// it is applied), that every claim the page makes matches the checked member data,
// that the asterisk falls only on reconstructions, and that the built page's embedded
// data is byte-identical to the source of truth (drift guard).
import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import {
  PORTAL, GRIMM_INVERSE, RECONSTRUCT, VERNER, MEMBERS, FOSSILS, FRAMING, SYNTHESIS,
} from './data.mjs';
import { GRIMM } from '../sound-laws/data.mjs';
import { THRIX } from '../grassmann/data.mjs';
import { ERASURE } from '../i-mutation/data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
let pass = 0, fail = 0;
const ok = (c, m) => { if (c) { pass++; } else { fail++; console.error('  ✗ ' + m); } };
const KNOWN_MEMBER_SLUGS = ['the-first-sound-shift', 'i-mutation', 'grassmann', 'sing-sang-sung'];

// ── 1. Grimm's Law is a bijection on the stop series → its inverse round-trips. ──
// (This is exactly why the engine can run it backwards in initial position.)
{
  const gmcSeen = new Set();
  for (const [pie, r] of Object.entries(GRIMM)) {
    ok(!gmcSeen.has(r.gmc), `Grimm reflex not unique — merger at *${pie} → ${r.gmc}`);
    gmcSeen.add(r.gmc);
    ok(GRIMM_INVERSE[r.gmc] === pie, `Grimm inverse fails to round-trip: ${r.gmc} → ${GRIMM_INVERSE[r.gmc]} (want ${pie})`);
  }
  ok(gmcSeen.size === Object.keys(GRIMM).length, 'Grimm is one-to-one across the whole stop series');
}

// ── 2. The reconstruction engine recovers the sourced PIE initial from the reflex. ──
{
  ok(RECONSTRUCT.length >= 4, 'engine offers at least four cognate sets');
  const parts = new Set();
  for (const s of RECONSTRUCT) {
    ok(GRIMM_INVERSE[s.gmcInitial] === s.pieInitial,
      `${s.id}: inverting Germanic '${s.gmcInitial}' gives '${GRIMM_INVERSE[s.gmcInitial]}', want sourced PIE '${s.pieInitial}'`);
    ok(GRIMM[s.pieInitial] && GRIMM[s.pieInitial].gmc === s.gmcInitial,
      `${s.id}: Grimm forward disagrees (*${s.pieInitial} → ${GRIMM[s.pieInitial] && GRIMM[s.pieInitial].gmc}, not ${s.gmcInitial})`);
    ok(s.pie.startsWith('*'), `${s.id}: PIE reconstruction '${s.pie}' must be asterisked`);
    ok(s.protoGmc.startsWith('*'), `${s.id}: Proto-Germanic '${s.protoGmc}' must be asterisked`);
    for (const f of ['english', 'latin', 'greek', 'sanskrit']) {
      if (s[f]) ok(!String(s[f]).startsWith('*'), `${s.id}: attested ${f} '${s[f]}' must NOT be asterisked`);
    }
    parts.add(s.part);
  }
  ok(parts.has(1) && parts.has(2) && parts.has(3),
    `engine should span all three parts of Grimm; saw parts ${[...parts].sort().join(',')}`);
}

// ── 3. Verner: the lost accent read from the voicing, confirmed by Sanskrit. ──
{
  const [fa, br] = VERNER.pair;
  ok(fa.word === 'father' && fa.voiced === true && fa.accent === 'final',
    'Verner: father must be voiced with a final PIE accent (Verner fires)');
  ok(br.word === 'brother' && br.voiced === false && br.accent === 'initial',
    'Verner: brother must be voiceless with an initial PIE accent (Verner does not fire)');
  // The pair must genuinely contrast — same predicted Grimm outcome, opposite Verner result.
  ok(fa.voiced !== br.voiced, 'Verner: the pair must differ in voicing (the whole point)');
  ok(fa.accent !== br.accent, 'Verner: the pair must differ in accent position (the cause)');
  ok(fa.sanskrit && br.sanskrit && !fa.sanskrit.startsWith('*') && !br.sanskrit.startsWith('*'),
    'Verner: both members must cite an attested Sanskrit witness for the accent');
  ok(fa.pie.startsWith('*') && br.pie.startsWith('*'), 'Verner: PIE forms asterisked');
  ok(Array.isArray(VERNER.residue.pair) && VERNER.residue.pair.join('/') === 'was/were',
    'Verner: the surviving residue is the was ~ were (s ~ r) alternation');
}

// ── 4. Grassmann θρίξ ~ τριχός — the law watched turning on and off. ──
{
  ok(THRIX.nom.fired === false, 'θρίξ (nom): Grassmann must NOT fire (only one aspirate survives before -s)');
  ok(THRIX.gen.fired === true, 'τριχός (gen): Grassmann MUST fire (two aspirates present)');
  const nomFinal = THRIX.nom.stages[THRIX.nom.stages.length - 1].form;
  const genFinal = THRIX.gen.stages[THRIX.gen.stages.length - 1].form;
  ok(nomFinal.includes('θ'), `θρίξ must keep its initial θ (got ${nomFinal})`);
  ok(genFinal.includes('τ') && genFinal.includes('χ'), `τριχός must show τ…χ (first breath stepped aside; got ${genFinal})`);
  // the deciding difference is whether a second aspirate surfaces (aspirate count).
  const nomLast = THRIX.nom.stages[THRIX.nom.stages.length - 1].aspirates;
  ok(nomLast === 1, 'θρίξ ends with a single aspirate (no trigger left)');
  ok(THRIX.gen.stages.some((s) => s.grassmann === true), 'τριχός derivation records the Grassmann step');
}

// ── 5. The ablaut fossil — a dead grammatical system, alive in a noun. ──
{
  const want = { sing: 'song', ride: 'road', bind: 'bond' };
  for (const [verb, noun] of Object.entries(want)) {
    const f = FOSSILS.find((x) => x.verb === verb);
    ok(f && f.noun === noun, `fossil ${verb} → ${noun} missing or wrong`);
    ok(f && f.grade === 'o-grade', `fossil ${verb}/${noun} must be the o-grade`);
  }
  ok(FOSSILS.length === 3, 'exactly three fossil pairs selected');
}

// ── 6. i-mutation — the cause that deletes itself. ──
{
  const st = ERASURE.stages;
  ok(st[st.length - 1].form === 'fēt', 'erasure ends at fēt (feet)');
  ok(st.some((s) => s.trigger === true) && st[st.length - 1].trigger === false,
    'the conditioning *-i must appear and then be gone (self-erasure)');
  ok(/backward/i.test(ERASURE.note), 'erasure note must state the rule reads backwards');
}

// ── 7. The four members are the real strata, one per vanished-cause kind. ──
{
  ok(MEMBERS.length === 4, 'four members');
  const kinds = new Set();
  for (const m of MEMBERS) {
    ok(KNOWN_MEMBER_SLUGS.includes(m.slug), `member slug ${m.slug} is a real P13 stratum`);
    ok(m.url === `/strata/${m.slug}/`, `member url mismatch for ${m.slug}`);
    ok(m.vanished && m.trace && m.reads, `member ${m.slug} missing a field`);
    kinds.add(m.accent);
  }
  ok(kinds.size === 4, 'four distinct vanished-cause kinds (suffix / accent / breath / grade)');
}

// ── 8. Synthesis + honesty apparatus present. ──
{
  ok(SYNTHESIS.length === 4, 'synthesis table has one row per member');
  ok(/hypothesis|working/i.test(FRAMING.exceptions) && /Verner/.test(FRAMING.exceptions),
    'framing must name regularity as a hypothesis and Verner-as-exception');
  ok(/merger/i.test(FRAMING.invertibility) && /redundanc/i.test(FRAMING.invertibility),
    'framing must concede mergers destroy information and reconstruction leans on redundancy');
  ok(/reconstruction|hypothesis|uncertain/i.test(FRAMING.limits),
    'framing must flag PIE as a reconstruction with uncertainty');
}

// ── 9. Drift guard: the built page embeds this exact data. ──
{
  const page = join(HERE, '../../public/strata/the-cause-you-read-backwards/index.html');
  if (existsSync(page)) {
    const html = readFileSync(page, 'utf8');
    const needle = 'const PORTAL = ' + JSON.stringify(PORTAL) + ';';
    ok(html.includes(needle), 'built page embeds PORTAL byte-for-byte (no drift from source of truth)');
    ok(html.includes('research/the-cause-you-read-backwards/verify.mjs'), 'page cites its verifier');
  } else {
    console.error('  · (page not built yet — run build-page.mjs; drift guard skipped)');
  }
}

console.log(`\n${fail ? '✗' : '✓'} the-cause-you-read-backwards: ${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
