// research/high-german-shift/verify.mjs
// Internal-consistency verifier for the stratum "The Wall Between Ship and Schiff".
//
// It does NOT prove historical linguistics. It proves the curated dataset is
// internally consistent with the conditioning rule it illustrates — catching
// transcription errors and demonstrating the regularity across the set — and that
// the page embeds exactly this data (drift guard). Run: node verify.mjs
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { RULE, ROWS, DATA, SUBREG, FAN, NOT_THE_SHIFT, DATING, FRAMING } 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 conditioning rule predicts every voiceless-stop entry's outcome. ──────
// For p/t/k, the German reflex must equal RULE.positions[pos].outcomes[c].
const voiceless = DATA.filter(d => ['p', 't', 'k'].includes(d.c) && d.confidence !== 'gap');
for (const d of voiceless) {
  const predicted = RULE.positions[d.pos]?.outcomes[d.c];
  ok(predicted === d.out,
    `RULE predicts ${d.c} in ${d.pos} → ${predicted}, but ${d.en}/${d.de} claims ${d.out}`);
}
ok(voiceless.length >= 20, `expected ≥20 voiceless-stop examples, got ${voiceless.length}`);

// ── 2. The German reflex actually appears in the German word (transcription guard).
function appears(de, out) {
  const w = de.toLowerCase();
  if (out === 'f')  return /f/.test(w);
  if (out === 'pf') return /pf/.test(w);
  if (out === 's')  return /(ss|ß|s)/.test(w);
  if (out === 'z')  return /z/.test(w);
  if (out === 'ch') return /ch/.test(w);
  if (out === 't')  return /t/.test(w);
  if (out === 'k')  return /k/.test(w);
  return false;
}
for (const d of DATA) {
  ok(appears(d.de, d.out), `reflex "${d.out}" not visible in German "${d.de}" (${d.en})`);
}

// ── 3. The English member kept the OLD stop (so the pair really is a contrast).
// The shifting consonant's pre-shift stop should be visible in the English word,
// except where English itself wore it away (I < ic; the th-initial words).
const englishKeepsStop = {
  p: w => /p/.test(w), t: w => /t/.test(w), k: w => /(k|c|ck)/.test(w), d: w => /d/.test(w),
};
const englishExempt = new Set(['I']); // English reduced ic → I (vowel)
for (const d of DATA) {
  if (englishExempt.has(d.en)) { pass++; continue; }
  ok(englishKeepsStop[d.c](d.en.toLowerCase()),
    `English "${d.en}" should still show the old ${d.c} (the unshifted side)`);
}

// ── 4. Every entry is sourced; reconstructed forms (if any) carry the asterisk. ──
for (const d of DATA) ok(typeof d.source === 'string' && d.source.length > 8, `${d.en}/${d.de} missing source`);

// ── 5. ROWS membership matches RULE.standard (what reached the written standard). ─
for (const r of ROWS) {
  if (r.id === 'k-kx') { ok(r.member === 'southern', 'k→kx must be tagged southern'); continue; }
  ok(r.member === 'standard', `${r.id} expected standard`);
}
ok(RULE.standard['k→kx'] === false, 'initial k→kx must be marked NOT in the standard');
ok(RULE.standard['b→p'] === false && RULE.standard['g→k'] === false, 'b→p / g→k must be marked NOT standard');
ok(RULE.standard['d→t'] === true, 'd→t must be marked standard');

// ── 6. The gap rows really show an UNSHIFTED initial k in standard German. ────────
const gap = DATA.filter(d => d.confidence === 'gap');
for (const d of gap) {
  ok(d.c === 'k' && d.pos === 'affricate' && d.out === 'k',
    `gap entry ${d.en}/${d.de} should be initial k staying k`);
  ok(/^k/.test(d.de.toLowerCase()), `gap entry ${d.de} should keep initial k in the standard`);
}
ok(gap.length >= 2, 'need ≥2 gap examples (initial k unshifted)');

// ── 7. The Rhenish fan: a real BUNDLE — the per-consonant lines do not coincide. ──
// ranks 1..N unique and ordered:
const ranks = FAN.map(f => f.rank);
ok(new Set(ranks).size === ranks.length, 'fan ranks must be unique');
ok(ranks.slice().sort((a, b) => a - b).join() === ranks.join(), 'fan must be listed north→south by rank');
// The load-bearing fact: NO single rank-cut sorts the family by consonant. Concretely,
// the p-lines straddle the t-line, so you cannot draw one line that puts all shifted-p
// on one side and also sorts t. Check: there exist two p-features with a t-feature
// strictly between them in rank.
const pRanks = FAN.filter(f => f.cons === 'p').map(f => f.rank).sort((a, b) => a - b);
const tRanks = FAN.filter(f => f.cons === 't').map(f => f.rank);
const straddled = tRanks.some(t => pRanks.length >= 2 && t > pRanks[0] && t < pRanks[pRanks.length - 1]);
ok(straddled, 'the fan must interleave consonants (a t-line between two p-lines) — the proof there is no single clean wall');
// the k-lines (Uerdingen ik/ich, Benrath maken/machen) are the two northernmost:
const kRanks = FAN.filter(f => f.cons === 'k').map(f => f.rank).sort((a, b) => a - b);
ok(kRanks[0] === 1 && kRanks[1] === 2, 'ik/ich and maken/machen (k) should be the two northernmost lines');

// ── 8. The "not the shift" set is genuinely th→d (English th, German d, Dutch d). ─
for (const n of NOT_THE_SHIFT) {
  ok(/th/i.test(n.en), `${n.en} should contain th (the separate þ→d change)`);
  ok(/d/i.test(n.de), `${n.de} should show d (þ→d)`);
}

// ── 9. The sub-irregularity: pf → f after l/r, with the Karpfen counter-example. ──
ok(SUBREG.simplified.every(s => /f/.test(s.de) && !/pf/.test(s.de)), 'helfen/scharf/werfen show f, not pf, in the standard');
ok(/pf/.test(SUBREG.counter.de), 'Karpfen must keep -pf- (the counter-example to the simplification)');

// ── 10. The blocking environments keep an unshifted stop. ─────────────────────────
ok(RULE.blocked.examples.every(b => /[ptk]/.test(b.de.toLowerCase())),
  'every blocked example should still show an unshifted stop');
ok(/ist/.test(RULE.blocked.examples.map(b => b.de).join(' ').toLowerCase()), 'ist (st blocks t) should be a blocked example');

// ── 11. Apparatus sanity: dating is a range; framing is hedged. ───────────────────
ok(/\d/.test(DATING.span) && /debated/i.test(DATING.note), 'dating must be a sourced range with the debate flagged');
ok(/principal/i.test(FRAMING.claim) && /not/i.test(FRAMING.notWhole), 'framing must claim only the consonant wall, not the whole gap');

// ── 12. DRIFT GUARD: the built page embeds exactly this DATA (byte-identical JSON).
try {
  const html = readFileSync(join(__dir, '../../public/strata/high-german-shift/index.html'), 'utf8');
  const m = html.match(/<script id="hgs-data" type="application\/json">([\s\S]*?)<\/script>/);
  ok(!!m, 'page must carry the embedded <script id="hgs-data"> JSON block');
  if (m) {
    const embedded = JSON.parse(m[1]);
    const canonical = JSON.parse(JSON.stringify({ RULE, ROWS, DATA, SUBREG, FAN, NOT_THE_SHIFT, DATING, FRAMING }));
    ok(JSON.stringify(embedded) === JSON.stringify(canonical),
      'DRIFT: embedded page data differs from data.mjs — rebuild the page');
  }
} catch (e) {
  ok(false, 'drift guard could not read the built page: ' + e.message + ' (build it, then re-run)');
}

console.log(`\nHigh German shift — internal consistency: ${pass} passed, ${fail} failed`);
if (fail) { console.log('FAILURES:\n  - ' + fails.join('\n  - ')); process.exit(1); }
console.log('ALL GREEN — the dataset is internally consistent with the conditioning rule, and the page matches the data.');
