#!/usr/bin/env node
/* THE SEVEN DOUBLED — byte-verifier (al-Fātiḥa · Translation-Criticism XVII)
 *
 * Re-checks, against raw source bytes, every claim the page makes that can be
 * checked without a browser:
 *   - the Arabic text on the page IS the standard Ḥafṣ (Uthmani) Fātiḥa
 *     (interlinear words and the Instrument-IV verses both reconstruct it);
 *   - every English line quoted is present verbatim in its named PD scan;
 *   - the two readings of 1:4 differ by exactly one alif;
 *   - both versifications total seven, over the identical text.
 *
 * Sources (saved raw in this directory):
 *   fatiha-uthmani-clean.txt        canonical Arabic (Tanzil quran-uthmani / alquran.cloud)
 *   sale_7440.txt                   George Sale 1734  (Gutenberg 7440)
 *   rodwell-gutenberg.txt           J.M. Rodwell 1861 (Gutenberg 3434)
 *   muhammadali-1917-jauhar.txt     Muhammad Ali 1917 (archive.org)
 *   pickthall-1930-MN40248.txt      Pickthall 1930    (archive.org MN40248ucmf_9)
 *
 * Usage: node research/the-seven-doubled/verify.mjs
 */
import { readFileSync } from 'node:fs';

const HERE = new URL('.', import.meta.url).pathname;
const PAGE = readFileSync(HERE + '../../public/strata/the-seven-doubled/index.html', 'utf8');
const src = name => readFileSync(HERE + name, 'utf8');

let pass = 0, fail = 0;
const ck = (label, ok, detail = '') => {
  console.log(`  ${ok ? '✓' : '✗'} ${label}${detail ? '  ' + detail : ''}`);
  ok ? pass++ : fail++;
};
const nfc = s => s.normalize('NFC');
const ws  = s => nfc(s).replace(/﻿/g, '').replace(/\s+/g, ' ').trim();          // collapse whitespace
const stripTags = h => h.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&');

console.log('\nTHE SEVEN DOUBLED — byte-verify\n');

/* ---------- 1. the canonical Arabic ---------- */
const canon = src('fatiha-uthmani-clean.txt')
  .replace(/﻿/g, '')
  .split('\n').filter(Boolean)
  .map(l => ws(l.split('\t')[1]));
ck('canonical source has 7 āyāt', canon.length === 7, `(${canon.length})`);
ck('canonical 1:4 is mālik with dagger-alif (مَٰلِكِ)', canon[3].startsWith('مَٰلِكِ'), `('${canon[3]}')`);

/* ---------- 2. interlinear words reconstruct the canonical text ---------- */
// every word object on the page is { ar:"…", … }; pull them in document order.
const arWords = [...PAGE.matchAll(/\bar:\s*"([^"]+)"/g)]
  .map(m => ws(m[1]))
  .filter(w => /[؀-ۿ]/.test(w));   // drop the CSS --ar font-stack match
ck('interlinear exposes 29 words', arWords.length === 29, `(${arWords.length})`);
const interlinJoined = ws(arWords.join(' '));
const canonJoined    = ws(canon.join(' '));
ck('interlinear words === canonical 7 verses, in order', interlinJoined === canonJoined,
   interlinJoined === canonJoined ? '' : `\n      page : ${interlinJoined}\n      canon: ${canonJoined}`);

/* ---------- 3. Instrument IV — BASMALA + V reconstruct the same text ---------- */
const basmala = ws(PAGE.match(/const BASMALA\s*=\s*"([^"]+)"/)[1]);
const vBlock  = PAGE.match(/const V\s*=\s*\[([\s\S]*?)\];/)[1];
const V = [...vBlock.matchAll(/"([^"]+)"/g)].map(m => ws(m[1]));
ck('Instrument IV V[] has 7 segments (v2–v6, v7a, v7b)', V.length === 7, `(${V.length})`);
ck('BASMALA === canonical verse 1', basmala === canon[0], basmala === canon[0] ? '' : `('${basmala}')`);
const ivKufan = ws([basmala, V[0], V[1], V[2], V[3], V[4], V[5] + ' ' + V[6]].join(' '));
ck('Kūfan versification (basmala + 6) === canonical', ivKufan === canonJoined,
   ivKufan === canonJoined ? '' : '\n      ' + ivKufan);
const ivBasran = ws([V[0], V[1], V[2], V[3], V[4], V[5], V[6]].join(' '));
ck('Baṣran versification (7, basmala uncounted) === canonical minus basmala',
   ivBasran === ws(canon.slice(1).join(' ')));

/* ---------- 4. the one-alif variant of 1:4 ---------- */
const rWord = key => ws(PAGE.match(new RegExp(key + ':\\s*\\{\\s*\\n?\\s*word:\\s*"([^"]+)"'))[1]);
const wMalik = rWord('malik'), wKing = rWord('king');
ck('reading mālik renders مَالِكِ (with alif)', wMalik === 'مَالِكِ', `('${wMalik}')`);
ck('reading malik renders مَلِكِ (no alif)',  wKing  === 'مَلِكِ',  `('${wKing}')`);
ck('the two readings differ by exactly one alif (ا)',
   nfc(wMalik).replace('ا', '') === nfc(wKing) && wMalik.includes('ا') && !wKing.includes('ا'));

/* ---------- 5. every English line is verbatim in its named PD scan ---------- */
const pageText = ws(stripTags(PAGE));
function verbatim(label, file, phrases) {
  const source = ws(src(file));
  for (const p of phrases) {
    const np = ws(p);
    const inSource = source.includes(np);
    const inPage   = pageText.includes(np);
    ck(`${label}: "${p.slice(0, 46)}${p.length > 46 ? '…' : ''}"`, inSource && inPage,
       inSource ? (inPage ? '' : '(NOT ON PAGE)') : '(NOT IN SOURCE)');
  }
}
verbatim('Sale 1734', 'sale_7440.txt', [
  'PRAISE be to GOD, the LORD of all creatures',
  'the king of the day of judgment',
  'Thee do we worship, and of thee do we beg assistance',
  'nor of those who go astray',
]);
verbatim('Rodwell 1861', 'rodwell-gutenberg.txt', [
  'King on the day of reckoning',
  'Thee only do we worship, and to Thee do we cry for help',
  'Guide Thou us on the straight path',
]);
verbatim('Muhammad Ali 1917', 'muhammadali-1917-jauhar.txt', [
  'Master of the day of requital',
  'two different words from the same root',
  'the former signifying master and the latter king',
  'not a mere king or a mere judge, but more properly a Master',
]);
verbatim('Pickthall 1930', 'pickthall-1930-MN40248.txt', [
  'Owner of the Day of Judgment',
  'Show us the straight path',
  'The Koran cannot be translated',
  'that inimitable symphony, the very sounds of which',
]);

/* ---------- 6. honest-edge tags the page commits to ---------- */
for (const claim of [
  'names no group',                              // verse-7 honesty
  'ḥasan gharīb',                                // hadith grade
  'mutawātir',                                   // canonicity of both readings
  'Foreign Vocabulary of the Qurʾān',            // ṣirāṭ etymology source
  'esṭrāṭā',                                     // the Syriac link, transliterated (no tofu)
  'The Meaning of the Glorious Koran',           // the hedged title
]) ck(`page commits to: "${claim}"`, pageText.includes(ws(claim)));

console.log(`\n${pass}/${pass + fail} PASS — ${fail === 0 ? 'ALL CHECKS PASS' : fail + ' FAILED'}\n`);
process.exit(fail === 0 ? 0 : 1);
