#!/usr/bin/env node
// research/the-form-is-the-checksum/verify.mjs
// ─────────────────────────────────────────────────────────────────────────────
// Offline verifier for the portal "The Form Is the Checksum".
//
//   node research/the-form-is-the-checksum/verify.mjs
//
// It does NOT "prove" that a poem is a channel code — that is the portal's READING,
// stated as such on the page. It proves the portal is internally consistent with the
// four member layers it reuses, and that every operable claim recomputes:
//
//   [1] The DESIGNED code (check-digits): the blind-spot sets re-derive from the
//       member's imported engine — ISBN-10 catches every adjacent transposition,
//       Luhn is blind exactly to 0↔9, Verhoeff is blind to none — and the two demo
//       numbers are valid, with ISBN detecting a transposition Luhn's 0↔9 swap hides.
//   [2] METRE (Homer): the six Greek lines the page shows are byte-identical to the
//       lines The Sixth Letter verifies against the Monro-Allen Perseus text, and the
//       hiatus statistic the page reports is the figure that member's page carries.
//   [3] RHYME: the three featured couplets are imported unchanged from The Rhyme the
//       Sound Forgot and each really encodes vowels that matched then and differ now.
//   [4] The POSITIONAL code (Lamentations): re-derived from the acrostic member's
//       first-letters.json — chapter 1 is the standard alphabet, chapters 2 and 4 are
//       the pe-before-ayin variant, and the ayin/pe verse positions invert as claimed.
//   [5] Provenance + drift: every member exists on the ground; the built page embeds
//       the canonical DATA byte-for-byte (no drift from this source of truth).
// ─────────────────────────────────────────────────────────────────────────────

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

import {
  DATA, JSON_STR, HEB_STD, HEB_VARIANT,
} from './data.mjs';
import {
  SCHEMES, transpositionBlindPairs, toDigits,
  luhnValid, isbn10Valid,
} from '../check-digits/engine.mjs';
import { RHYMES } from '../the-rhyme-the-sound-forgot/data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; } else { fail++; console.error('  ✗ ' + msg); } };
const section = (s) => console.log('\n' + s);

console.log('THE FORM IS THE CHECKSUM — verify\n(portal; reuses four checked members, re-derives every operable claim)');

// ── [1] THE DESIGNED CODE — check-digits re-derived from the member engine ──────
section('[1] check digits — a code catches only its error class');
{
  const cd = DATA.checkdigit;

  // blind-spot sets re-derived here from the imported engine
  const reIsbn = transpositionBlindPairs(SCHEMES.isbn10);
  const reLuhn = transpositionBlindPairs(SCHEMES.luhn);
  const reVerh = transpositionBlindPairs(SCHEMES.verhoeff);
  ok(reIsbn.length === 0, 'ISBN-10 catches every adjacent transposition (blind set empty)');
  ok(reLuhn.length === 1 && reLuhn[0] === '09', 'Luhn is blind to exactly the 0↔9 transposition');
  ok(reVerh.length === 0, 'Verhoeff catches every adjacent transposition (blind set empty)');
  // the page's embedded blind sets equal the freshly-derived ones (no drift)
  ok(JSON.stringify(cd.schemes.isbn10) === JSON.stringify(reIsbn), 'page ISBN blind set matches engine');
  ok(JSON.stringify(cd.schemes.luhn) === JSON.stringify(reLuhn), 'page Luhn blind set matches engine');
  ok(cd.isbn.catchesTransposition === true, 'page states ISBN catches transpositions');

  // demo numbers are valid, and the transposition story is real
  const isbn = toDigits(cd.isbn.number);
  ok(isbn10Valid(isbn), `ISBN demo ${cd.isbn.number} is valid`);
  const isbnT = isbn.slice(); [isbnT[4], isbnT[5]] = [isbnT[5], isbnT[4]];
  ok(!isbn10Valid(isbnT), 'transposing two ISBN digits is DETECTED (becomes invalid)');

  const luhn = toDigits(cd.luhn.number);
  ok(luhnValid(luhn), `Luhn demo ${cd.luhn.number} is valid`);
  // find the adjacent 0,9 and swap it — must stay valid (blind)
  const i = luhn.findIndex((x, k) => k + 1 < luhn.length && ((x === 0 && luhn[k + 1] === 9) || (x === 9 && luhn[k + 1] === 0)));
  ok(i >= 0, 'Luhn demo contains an adjacent 0,9 pair to swap');
  const luhnT = luhn.slice(); [luhnT[i], luhnT[i + 1]] = [luhnT[i + 1], luhnT[i]];
  ok(luhnValid(luhnT), 'swapping the Luhn 0↔9 is UNDETECTED (still valid) — the code’s blind spot');
}

// ── [2] METRE — the six Homer lines match the member; the statistic is the member’s ─
section('[2] metre — Homer’s digamma (reused from The Sixth Letter)');
{
  const memVerify = join(HERE, '../the-sixth-letter/verify.mjs');
  ok(existsSync(memVerify), 'member the-sixth-letter/verify.mjs exists');
  const src = readFileSync(memVerify, 'utf8');
  for (const L of DATA.metre.lines) {
    ok(src.includes(L.text), `line ${L.ref} is byte-identical to the member’s verified text`);
    // each crux word must actually stand in its line, and its restoration begin with ϝ
    for (const cx of L.cruxes) {
      const core = (s) => s.replace(/[·,.;··ʼ’]+$/u, '');
      const inLine = L.text.split(' ').some((t) => core(t) === cx.base);
      ok(inLine, `${L.ref}: crux "${cx.base}" is a real token in the line`);
      ok(cx.restored.startsWith('ϝ') && [...cx.restored].length === [...cx.base].length + 1,
        `${L.ref}: restoration "${cx.restored}" is the base with a digamma prefixed`);
    }
  }
  ok(DATA.metre.lines.length === 6, 'six canonical lines carried');

  // the hiatus statistic the page reports must be the figure the member’s page carries
  const memPage = join(HERE, '../../src/content/strata/the-sixth-letter.md');
  const page = readFileSync(memPage, 'utf8');
  ok(page.includes('45%') && page.includes('16%'), 'member page carries the ≈45% / ≈16% hiatus figures');
  ok(page.includes('2.76'), 'member page carries the ≈2.76× ratio');
  ok(DATA.metre.hiatus.digammaRate === 45 && DATA.metre.hiatus.controlRate === 16 && DATA.metre.hiatus.ratio === 2.76,
    'page reports the member’s measured hiatus figures');
}

// ── [3] RHYME — imported unchanged; each chimes then and clashes now ────────────
section('[3] rhyme — vowels that matched then and differ now (from The Rhyme the Sound Forgot)');
{
  for (const p of DATA.rhyme.pairs) {
    const r = RHYMES.find((x) => x.id === p.id);
    ok(!!r, `rhyme ${p.id} exists in the member data`);
    if (!r) continue;
    // reused unchanged
    ok(r.text === p.text && r.a.w === p.a.w && r.b.w === p.b.w, `${p.id}: text and words reused verbatim`);
    ok(r.a.then === p.a.then && r.b.then === p.b.then && r.a.now === p.a.now && r.b.now === p.b.now,
      `${p.id}: vowel values reused verbatim`);
    // the load-bearing property of a broken chime
    ok(p.a.then === p.b.then, `${p.id}: the two vowels MATCHED in the period (chime)`);
    ok(p.a.now !== p.b.now, `${p.id}: the two vowels DIFFER today (broken)`);
  }
  const disp = DATA.rhyme.pairs.find((p) => p.id === 's116-proved-loved');
  ok(disp && disp.certainty === 'disputed', 'the proved/loved centrepiece is carried as DISPUTED (honesty)');
}

// ── [4] THE POSITIONAL CODE — re-derived from the acrostic member’s data ────────
section('[4] the acrostic — a positional code, re-derived from first-letters.json');
{
  const fl = JSON.parse(readFileSync(join(HERE, '../lamentations-acrostic/first-letters.json'), 'utf8'));
  const ini = (c) => fl[String(c)].map((v) => v.letter);

  ok(ini(1).join('') === HEB_STD.join(''), 'chapter 1 is the STANDARD alphabet, aleph→tav');
  ok(ini(2).join('') === HEB_VARIANT.join(''), 'chapter 2 is the pe-before-ayin VARIANT');
  ok(ini(4).join('') === HEB_VARIANT.join(''), 'chapter 4 is the pe-before-ayin VARIANT');
  ok(ini(3).length === 66, 'chapter 3 is a triple acrostic (66 verses)');

  // ayin/pe inversion, straight from the data
  const ap = (c) => ({ ayin: ini(c).indexOf('ע') + 1, pe: ini(c).indexOf('פ') + 1 });
  const a1 = ap(1), a2 = ap(2);
  ok(a1.ayin === 16 && a1.pe === 17, 'chapter 1: ayin (16) before pe (17) — standard');
  ok(a2.pe === 16 && a2.ayin === 17, 'chapter 2: pe (16) before ayin (17) — the fossil');
  // the page carries these positions unchanged
  ok(DATA.acrostic.ayinPe.ch1.ayin === 16 && DATA.acrostic.ayinPe.ch1.pe === 17, 'page ch1 ayin/pe positions correct');
  ok(DATA.acrostic.ayinPe.ch2.pe === 16 && DATA.acrostic.ayinPe.ch2.ayin === 17, 'page ch2 ayin/pe positions correct');
  ok(DATA.acrostic.order['1'] === 'standard' && DATA.acrostic.order['2'] === 'variant' && DATA.acrostic.order['4'] === 'variant',
    'page order classification (1 standard, 2 & 4 variant)');

  // detection demo: transposing two verses of chapter 1 breaks the alphabet
  const c1 = ini(1).slice(); [c1[5], c1[6]] = [c1[6], c1[5]];
  ok(c1.join('') !== HEB_STD.join(''), 'transposing two verses is DETECTED by the acrostic (margin no longer spells the alphabet)');
}

// ── [5] PROVENANCE + DRIFT ──────────────────────────────────────────────────────
section('[5] provenance + drift');
{
  const strata = join(HERE, '../../src/content/strata');
  for (const m of [...DATA.members, ...DATA.contrast]) {
    ok(existsSync(join(strata, m.slug + '.md')), `member on the ground: ${m.slug}`);
  }
  ok(DATA.synthesis.table.length === 4, 'synthesis maps four forms to four error classes');
  const tblSlugs = DATA.synthesis.table.map((t) => t.member).sort().join(',');
  ok(tblSlugs === ['check-digits', 'grief-in-order', 'the-rhyme-the-sound-forgot', 'the-sixth-letter'].join(','),
    'the four synthesis rows point at the four members');

  const built = join(HERE, '../../public/strata/the-form-is-the-checksum/index.html');
  if (existsSync(built)) {
    const html = readFileSync(built, 'utf8');
    ok(html.includes(JSON_STR), 'built page embeds the canonical DATA byte-for-byte (no drift)');
  } else {
    console.log('  · built page not present yet (run build-page.mjs) — drift check skipped');
  }
}

// ── summary ─────────────────────────────────────────────────────────────────────
console.log(`\n${fail === 0 ? '✓' : '✗'} ${pass}/${pass + fail} checks passed`);
process.exit(fail === 0 ? 0 : 1);
