#!/usr/bin/env node
// Verifier for `the-first-sound-shift`.
//
// What this DOES check (and all it claims): the curated dataset is internally
// consistent with the two sound laws it illustrates.
//   1. Every declared correspondence is a real part of Grimm's Law (no invented shift).
//   2. Each Proto-Germanic reflex actually realizes that correspondence.
//   3. Each doublet genuinely splits: the Latinate loan preserves a consonant the
//      native English word shifted away from.
//   4. The father/brother contrast obeys Verner's Law: voicing of the medial stop
//      iff the PIE accent left the preceding vowel unstressed (witnessed by Sanskrit).
//   5. Every entry cites a source.
//   6. Drift guard: the data embedded in the published page is byte-identical to this.
//   7. Badge guard: the page's "verifier: N internal-consistency checks, all green"
//      badge states this run's own total (this check included) and no check failed.
//
// What it does NOT do: prove historical linguistics, or derive the Latin/Greek/
// Sanskrit witnesses by rule (those branches have their own laws this file does not
// model — the witnesses are sourced, not computed). See data.mjs header.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { DATA, GRIMM, VERNER_VOICED, VERNER_RESIDUE } from './data.mjs';

const __dir = dirname(fileURLToPath(import.meta.url));
let pass = 0, fail = 0;
const fails = [];
function check(name, cond, detail = '') {
  if (cond) { pass++; }
  else { fail++; fails.push(`✗ ${name}${detail ? ' — ' + detail : ''}`); }
}

// Normalize a reflex grapheme to how it is written in our Proto-Germanic forms:
// labiovelars hʷ/kʷ are written hw/kw.
const norm = (g) => g.replace('ʷ', 'w');

// ---- 1 & 2: Grimm correspondence declared + realized -----------------------
for (const e of DATA) {
  const corr = GRIMM[e.shift.pie];
  check(`${e.id}: declares a real Grimm correspondence (${e.shift.pie})`, !!corr,
    `"${e.shift.pie}" is not in Grimm's Law table`);
  if (!corr) continue;
  const want = norm(corr.gmc);
  const pg = (e.protoGmc || '').toLowerCase();
  check(`${e.id}: Proto-Germanic ${e.protoGmc} realizes ${corr.label}`,
    pg.includes(want.toLowerCase()),
    `expected reflex "${want}" not found in ${e.protoGmc}`);
}

// ---- 3: doublets genuinely split at the shifted consonant ------------------
for (const e of DATA) {
  if (!e.borrowed) continue;
  const corr = GRIMM[e.shift.pie];
  if (!corr) continue;
  const reflex = norm(corr.gmc).toLowerCase();
  const kept = e.borrowed.kept.toLowerCase();
  // The loan must preserve a consonant DIFFERENT from the Germanic reflex —
  // that divergence is exactly what makes father≠paternal one word, two roads.
  check(`${e.id}: doublet "${e.english}" / "${e.borrowed.word}" splits at the shift`,
    kept !== reflex,
    `loan keeps "${kept}" but native reflex is also "${reflex}" — no split`);
}

// ---- 4: Verner's Law — the father/brother contrast -------------------------
// Both descend from a PIE form with a MEDIAL *t. Grimm alone would give voiceless
// *þ in both. Verner: the *t voices to *d iff the vowel before it was unstressed in
// PIE (i.e. the accent was NOT on that preceding syllable). Sanskrit preserves the
// accent: pitá́ (final stress → father voiced) vs bhrá́tā (initial stress → brother voiceless).
const vernerEntries = DATA.filter((e) => e.verner && e.verner.witness);
check('Verner: the father/brother contrast pair is present',
  vernerEntries.some((e) => e.id === 'father') && vernerEntries.some((e) => e.id === 'brother'));
for (const e of vernerEntries) {
  // accent === 'final' means the stressed syllable is NOT the one before the medial
  // stop → preceding vowel unstressed → Verner voicing applies.
  const expectVoiced = e.verner.accent !== 'initial';
  check(`${e.id}: isVerner flag matches the accent witness (${e.verner.accent})`,
    e.verner.isVerner === expectVoiced);
  const pg = (e.protoGmc || '').toLowerCase();
  if (expectVoiced) {
    // medial *t → voiced *d (and crucially NOT the voiceless *þ outcome)
    check(`${e.id}: Proto-Germanic ${e.protoGmc} shows the VOICED Verner reflex (d)`,
      pg.includes('d'), `expected voiced *d in ${e.protoGmc}`);
  } else {
    check(`${e.id}: Proto-Germanic ${e.protoGmc} keeps the VOICELESS reflex (þ)`,
      pg.includes('þ'), `expected voiceless *þ in ${e.protoGmc}`);
  }
}
// Sanity: the voiced-variant table is the inverse of the four voiceless fricatives.
check('Verner voiced-variant table covers f/þ/h/s',
  ['f', 'þ', 'h', 's'].every((k) => VERNER_VOICED[k]));

// ---- 5: every entry cites a source -----------------------------------------
for (const e of [...DATA, ...VERNER_RESIDUE]) {
  check(`${e.id || e.pair?.join('/')}: has a source citation`,
    typeof e.source === 'string' && e.source.length > 12);
}

// ---- 6: drift guard — the published page embeds exactly this data ----------
const pagePath = join(__dir, '..', '..', 'public', 'strata', 'the-first-sound-shift', 'index.html');
let html = '';
try { html = readFileSync(pagePath, 'utf8'); } catch { /* page may not exist yet */ }
if (html) {
  const blobs = {
    'DATA': JSON.stringify(DATA),
    'GRIMM': JSON.stringify(GRIMM),
    'VERNER_RESIDUE': JSON.stringify(VERNER_RESIDUE),
  };
  for (const [name, json] of Object.entries(blobs)) {
    check(`drift guard: page embeds current ${name} verbatim`, html.includes(json),
      `the page's embedded ${name} differs from data.mjs (rebuild the page)`);
  }
  // ---- 7: badge guard, the page's stated check count is this run's total ----
  // Runs last so the total is known; +1 counts this check itself.
  const m = html.match(/verifier: (\d+) internal-consistency checks, all green/);
  const total = pass + fail + 1;
  check(`badge guard: page badge states ${total} checks, all green, and none failed`,
    !!m && Number(m[1]) === total && fail === 0,
    m ? `page says ${m[1]} checks, all green; this run has ${total} checks, ${fail} failed`
      : 'badge text not found in the page');
} else {
  console.log('  (page not built yet: drift guard and badge guard skipped)');
}

// ---- report ----------------------------------------------------------------
console.log(`\nThe First Sound Shift — dataset verification`);
console.log(`  entries: ${DATA.length} cognate sets + ${VERNER_RESIDUE.length} Verner-residue pairs`);
console.log(`  ${pass} passed, ${fail} failed`);
if (fail) { console.log('\n' + fails.join('\n')); process.exit(1); }
console.log('  ✓ all checks green');
