#!/usr/bin/env node
// verify.mjs — the offline check for "In the Beginning Of" (Genesis 1:1).
//
// House rule: every factual claim is checked and the check is shown.
// The quoted texts live in sources.json, written by fetch-sources.mjs straight
// from the primary digitizations (never from memory). This script asserts that
// the immersive page reproduces each of them — Hebrew, Greek, Latin, and ten
// English hands — and that the Rashi excerpt on the page is a true substring of
// the full Rashi text as fetched.
//
//   node research/genesis-1-1/verify.mjs   (exit 0 = all pass)

import { readFileSync } from 'node:fs';

const HERE = new URL('.', import.meta.url).pathname;
const PAGE = readFileSync(HERE + '../../public/strata/in-the-beginning-of/index.html', 'utf8');
const SRC = JSON.parse(readFileSync(HERE + 'sources.json', 'utf8')).items;

let pass = 0, fail = 0;
const ok = (m) => { pass++; console.log('  ✓ ' + m); };
const bad = (m) => { fail++; console.log('  ✗ ' + m); };

// Normalize HTML to plain text: drop tags, decode the handful of entities used,
// collapse whitespace, then Unicode-NFC. Hebrew points are stored in different
// keyboard orders by different sources (Sefaria writes dagesh-before-shewa;
// editors often produce the canonical shewa-before-dagesh). NFC reorders
// combining marks to canonical order, so NFC-equal strings are the same text —
// a standard, lossless equality. Case, punctuation and the marks themselves are
// preserved.
const norm = (s) => s
  .replace(/<[^>]+>/g, '')
  .replace(/&nbsp;/g, ' ')
  .replace(/&amp;/g, '&')
  .replace(/&mdash;/g, '—')
  .replace(/&#8202;/g, ' ')
  .replace(/\s+/g, ' ')
  .trim()
  .normalize('NFC');
const pagePlain = norm(PAGE);
const has = (text) => pagePlain.includes(norm(text));
const hasCI = (text) => pagePlain.toLowerCase().includes(norm(text).toLowerCase());
const t = (key) => { if (!SRC[key]) throw new Error('missing source key: ' + key); return SRC[key].text; };

// ---------------------------------------------------------------------------
console.log('\n1. The Hebrew — Genesis 1:1 and the four construct parallels');
{
  const heb = [
    ['heb_gen_1_1', 'Genesis 1:1 (the verse itself)'],
    ['heb_jer_27_1', 'Jeremiah 27:1 — bereshit mamlechet Yehoyakim'],
    ['heb_gen_10_10', 'Genesis 10:10 — reshit mamlachto'],
    ['heb_deut_18_4', 'Deuteronomy 18:4 — reshit deganecha'],
    ['heb_gen_49_3', 'Genesis 49:3 — reshit oni'],
  ];
  for (const [k, label] of heb) has(t(k)) ? ok(label + ' — verbatim') : bad(label + ' — NOT verbatim on page');
}

// ---------------------------------------------------------------------------
console.log('\n2. Rashi — the page excerpt is a true substring of the fetched text');
{
  const full = norm(t('rashi_gen_1_1_b'));
  // Lift the Rashi Hebrew straight off the page (no re-typing), strip the framing
  // ellipses, and assert it is a contiguous substring of the fetched Rashi — i.e.
  // the quote was excerpted, not paraphrased or invented.
  const m = PAGE.match(/<div class="rashi">[\s\S]*?<div class="h">([\s\S]*?)<\/div>/);
  if (!m) { bad('could not locate the Rashi Hebrew on the page'); }
  else {
    const onPage = norm(m[1]).replace(/[……]/g, '').trim();
    if (onPage.length < 30) bad('Rashi excerpt on page is suspiciously short');
    else if (full.includes(onPage)) ok(`Rashi excerpt (${onPage.length} chars) is verbatim within the fetched text`);
    else {
      bad('Rashi excerpt on page is NOT a substring of the fetched Rashi');
      let i = 0; while (i < onPage.length && full.includes(onPage.slice(0, i + 1))) i++;
      console.log('      diverges near char ' + i + ': …' + onPage.slice(Math.max(0, i - 18), i + 18) + '…');
    }
  }
}

// ---------------------------------------------------------------------------
console.log('\n3. The ancient layer — Greek, Latin, John (faithful)');
{
  // The ladder shows the Greek and Latin truncated with an ellipsis; assert the
  // shown fragment is a genuine case-folded prefix of the fetched source.
  const prefix = (frag, key) => {
    const a = norm(frag).toLowerCase();
    const b = norm(t(key)).toLowerCase();
    if (b.startsWith(a) && hasCI(frag)) ok(`${key}: page fragment is a true prefix of the source`);
    else bad(`${key}: shown fragment is NOT a clean prefix (onPage=${hasCI(frag)}, isPrefix=${b.startsWith(a)})`);
  };
  prefix('ἐν ἀρχῇ ἐποίησεν ὁ θεὸς', 'lxx_gr_1_1');
  prefix('In principio creavit Deus', 'vg_la_1_1');
  // John 1:1 (TR) appears in full, verbatim, in the apparatus.
  has(t('john_1_1_gr')) ? ok('John 1:1 (Textus Receptus) — verbatim in apparatus') : bad('John 1:1 missing/altered');
}

// ---------------------------------------------------------------------------
console.log('\n4. The four construct parallels in the KJV’s own English');
{
  for (const k of ['kjv_jer_27_1', 'kjv_gen_10_10', 'kjv_deut_18_4', 'kjv_gen_49_3'])
    has(t(k)) ? ok(`${k} — verbatim`) : bad(`${k} — NOT verbatim on page`);
}

// ---------------------------------------------------------------------------
console.log('\n5. The ten English hands — Genesis 1:1–2, verbatim');
{
  const hands = [
    ['wycliffe', 'Wycliffe c.1395'], ['tyndale', 'Tyndale 1530'], ['douay', 'Douay–Rheims 1609'],
    ['kjv', 'King James 1611'], ['brenton', 'Brenton 1851 (from the Greek)'], ['darby', 'Darby 1890'],
    ['ylt', "Young's Literal 1898"], ['asv', 'American Standard 1901'], ['jps1917', 'JPS 1917'],
    ['web', 'World English Bible'],
  ];
  let n = 0;
  for (const [slug, label] of hands) {
    const a = has(t(slug + '_1_1')), b = has(t(slug + '_1_2'));
    if (a && b) { ok(`${label} — both verses verbatim`); n++; }
    else {
      bad(`${label} — mismatch (v1=${a}, v2=${b})`);
      for (const vk of [slug + '_1_1', slug + '_1_2']) if (!has(t(vk))) {
        const src = norm(t(vk));
        let i = 0; while (i < src.length && pagePlain.includes(src.slice(0, i + 1))) i++;
        console.log(`      ${vk} diverges near: …${src.slice(Math.max(0, i - 30), i + 30)}…`);
      }
    }
  }
  n === hands.length ? ok(`all ${hands.length} hands reproduced`) : bad(`only ${n}/${hands.length} hands fully verbatim`);
}

// ---------------------------------------------------------------------------
console.log('\n6. The page states its own structure honestly');
{
  for (const claim of ['Entry XXVII', 'ten public-domain', 'genuinely unsettled', 'none supplied from memory'])
    has(claim) ? ok(`page states: "${claim}"`) : bad(`page omits: "${claim}"`);
}

// ---------------------------------------------------------------------------
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ ' + fail + ' FAILED'} — ${pass} checks passed, ${fail} failed.`);
process.exit(fail === 0 ? 0 : 1);
