#!/usr/bin/env node
/* Verify "Perhaps He Does Not Know" (/strata/perhaps-he-does-not-know/). Offline, no network.
   Three layers of assertion:
     A. every English rendering / verdict quoted on the page is present in the page HTML AND
        traceable to a committed public-domain source excerpt under sources/;
     B. the Sanskrit transliteration the page prints is present in the page and matches a
        committed source (Macdonell 1917 / Aufrecht 1877);
     C. the counts the page's prose and check-box rely on (2 of 2 Sāyaṇa-route translators
        close the doubt; 8 of 8 direct-from-Sanskrit let it stand; 10 renderings; 8 flagged
        words) are recomputed here from the same classification the page's script uses.
   Run: node research/nasadiya-sukta/verify.mjs */
import { readFileSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const root = join(here, '..', '..');
const html = readFileSync(join(root, 'public', 'strata', 'perhaps-he-does-not-know', 'index.html'), 'utf8');
const srcDir = join(here, 'sources');

/* --- normalisation: fold to letters/digits + single spaces, strip diacritics & punctuation,
   so a match survives dash/quote/bracket/accent typography differences between sources. --- */
const norm = s => s
  .normalize('NFD').replace(/[̀-ͯ]/g, '')      // strip combining diacritics
  .toLowerCase()
  .replace(/[^a-z0-9ऀ-ॿ]+/g, ' ')              // keep latin, digits, Devanagari
  .replace(/\s+/g, ' ').trim();

/* page haystack: tags removed, normalised two ways (joined + spaced) */
const stripTags = h => h.replace(/<[^>]+>/g, ' ');
const hay = norm(stripTags(html));
const inPage = s => hay.includes(norm(s));

/* source cache */
const srcFiles = readdirSync(srcDir).filter(f => f.endsWith('.txt'));
const cache = new Map();
const readSrc = f => { if (!cache.has(f)) cache.set(f, norm(readFileSync(join(srcDir, f), 'utf8'))); return cache.get(f); };
const inSrc = (file, s) => { const c = readSrc(file); return c.includes(norm(s)); };

let pass = 0, fail = 0; const misses = [];
const check = (label, ok) => { if (ok) pass++; else { fail++; misses.push(label); } };
/* a "quote" must be BOTH on the page and in its named source */
const quote = (file, ...phrases) => phrases.forEach(p => {
  check(`page: "${p.slice(0,60)}"`, inPage(p));
  check(`src[${file}]: "${p.slice(0,60)}"`, inSrc(file, p));
});

/* ---------- A. the ten renderings of the final line (Instrument II) ---------- */
quote('colebrooke-1805.txt',
  'does indeed know; but not another can possess that knowledge',
  'expounded according to the received doctrines of');
quote('mueller-1859.txt',
  "He knows it, — or perchance e'en He knows not",
  'Nor aught nor naught existed',
  'I subjoin a metrical translation of this hymn, which I owe to the kindness of a friend',
  'Language blushes at such expressions, but her blush is a blush of triumph',
  'boldness matched only by the Eleatic thinkers of Greece',
  'may be interpreted in two ways',
  'a confession of doubt on the part of the poet');
quote('muir-1870.txt',
  'he verily knows, or [even] he does not know');
quote('whitney-1882.txt',
  'He surely knoweth: or if he does not know',
  'The unlimited praises which have been bestowed upon it, as philosophy and as poetry, are well-nigh nauseating',
  'its absence is heartily to be wished');
quote('kaegi-1886.txt',
  'or does not He know');
quote('wilson-1888.txt',
  'he assuredly knows, or if he knows not (no one else does)',
  'evidently influenced by the Vedantism of a later period');
quote('griffith-1892.txt',
  'he verily knows it, or perhaps he knows not');
quote('macdonell-1900.txt',
  "He only knows, or ev'n he does not know it");
quote('macdonell-1917.txt',
  'he only knows, or else he knows not',
  'poetry of no mean order',
  'possibly a metrical pause expressive of doubt may have been intended',
  'the meaning of this word here is uncertain',
  'By the creation of this (universe) the gods (come) afterwards',
  'there was energy below, there was impulse above');
quote('macdonell-1922.txt',
  'He only knows, or haply he may know not');

/* ---------- B. the Sanskrit the page prints ---------- */
/* the closing four words — present on page (banner + Instrument I + prose) and in both editions */
check('page: closing pada', inPage('só aṅgá veda, yádi vā ná véda'));
check('src macdonell: closing pada', inSrc('macdonell-1917.txt', 'só aṅgá veda, yádi vā ná véda'));
check('src aufrecht: closing pada', inSrc('aufrecht-1877.txt', 'só angá veda yádi vā ná véda'));
/* the opening line */
check('page: opening line', inPage('nā́sad āsīn'));
check('src macdonell: opening line', inSrc('macdonell-1917.txt', 'nā́sad āsīn'));
check('src aufrecht: opening line', inSrc('aufrecht-1877.txt', 'Násad āsīn'));
/* a mid-hymn line actually shown in Instrument I (within one token, so contiguous pre-JS) */
check('page: stanza 4 line', inPage('tád ágre sám avartatā́dhi'));
check('src: stanza 4 line', inSrc('macdonell-1917.txt', 'tád ágre sám avartatā́dhi'));
/* the accented Devanagari of stanza 1 (banner) — present in page and in the devanagari source */
check('page: devanagari st.1', inPage('व्यो॑मा प॒रो यत्'));
check('src: devanagari st.1', inSrc('devanagari-source.txt', 'व्यो॑मा प॒रो यत्'));

/* B2 (assay line, 2026-10-18). norm() above strips accents, so section B could not see a wrong
   accent: thirteen marks in stanzas 1 to 6 had drifted from Macdonell's printed pages and every
   check still passed. These forms, read again from the page images (pp. 207-211), are compared
   with their accents (NFC, nothing stripped) against the page and the kept transcription. */
const nfc = s => s.normalize('NFC');
const accented = f => nfc(f);
const htmlNfc = nfc(html);
const src1917 = nfc(readFileSync(join(srcDir, 'macdonell-1917.txt'), 'utf8'));
for (const f of ['tadā́nīṃ', 'amṛ́taṃ', 'rā́triā', 'tád ékaṃ', 'dhānyán', 'saliláṃ', 'ápihitam yád ā́sīt',
                 'mahinā́jāyatáikam', 'prathamáṃ yád ā́sīt', 'tiraścī́no', 'svid āsī́3d', 'kúta ā́jātā']) {
  check(`accented page: ${f}`, htmlNfc.includes(accented(f)));
  check(`accented src macdonell-1917: ${f}`, src1917.includes(accented(f)));
}
/* the drifted forms must be gone from the stanza data (they may still appear, quoted, in the Corrections note) */
const stanzaData = htmlNfc.slice(htmlNfc.indexOf('var STANZAS'), htmlNfc.indexOf('var HANDS'));
for (const f of ['tadā́nīm;', 'amṛtaṃ', 'rátriā', 'dhányán', 'ápihitaṃ', 'mahinā́jāyataíkam', 'tiraścíno', 'svid āsī3d', 'kúta ájātā', 'this world the gods']) {
  check(`stanza data no longer has: ${f}`, stanzaData.length > 1000 && !stanzaData.includes(nfc(f)));
}

/* ---------- C. recompute the counts (mirror of the page's HANDS classification) ---------- */
/* [who, year, route, doubt] — route: sayana|sanskrit; doubt: stands|deflected|suppressed */
const HANDS = [
  ['Colebrooke', 1805, 'sayana',   'suppressed'],
  ['Müller friend', 1859, 'sanskrit', 'stands'],
  ['Muir', 1870, 'sanskrit', 'stands'],
  ['Whitney', 1882, 'sanskrit', 'stands'],
  ['Kaegi', 1886, 'sanskrit', 'stands'],
  ['Wilson', 1888, 'sayana',   'deflected'],
  ['Griffith', 1897, 'sanskrit', 'stands'],
  ['Macdonell', 1900, 'sanskrit', 'stands'],
  ['Macdonell', 1917, 'sanskrit', 'stands'],
  ['Macdonell', 1922, 'sanskrit', 'stands'],
];
const sayana = HANDS.filter(h => h[2] === 'sayana');
const sanskrit = HANDS.filter(h => h[2] === 'sanskrit');
const sayanaClose = sayana.filter(h => h[3] !== 'stands');
const sanskritStand = sanskrit.filter(h => h[3] === 'stands');
check(`10 renderings total (got ${HANDS.length})`, HANDS.length === 10);
check(`2 read through Sāyaṇa (got ${sayana.length})`, sayana.length === 2);
check(`both Sāyaṇa-route close the doubt (got ${sayanaClose.length}/2)`, sayanaClose.length === 2);
check(`8 read from the Sanskrit (got ${sanskrit.length})`, sanskrit.length === 8);
check(`all 8 Sanskrit-route let it stand (got ${sanskritStand.length}/8)`, sanskritStand.length === 8);
/* the two additions that close the doubt must actually be marked (class="add") in the page */
check('page marks Colebrooke addition', /class="add">but not another can possess that knowledge/.test(html));
check('page marks Wilson addition', /class="add">\(no one else does\)/.test(html));
/* Macdonell three self-renderings all present (Instrument III) */
check('Macdonell 1900 self-rendering', inPage("He only knows, or ev'n he does not know it"));
check('Macdonell 1917 self-rendering', inPage('he only knows, or else he knows not'));
check('Macdonell 1922 self-rendering', inPage('He only knows, or haply he may know not'));
/* 8 words flagged contested in Instrument I (matches the gloss data) */
const contestedCount = (html.match(/contested:1/g) || []).length;
check(`7 words flagged contested in the gloss data (got ${contestedCount})`, contestedCount === 7);

/* ---------- report ---------- */
console.log(`Perhaps He Does Not Know — verify: ${pass}/${pass + fail} checks pass`);
if (fail) {
  console.error(`\n${fail} FAILING:`);
  for (const m of misses) console.error('  ✗ ' + m);
  process.exit(1);
}
console.log('Every quoted line is present on the page and traceable to a committed source. ✓');
console.log(`Counts: ${sayanaClose.length}/${sayana.length} Sāyaṇa-route close the doubt · ${sanskritStand.length}/${sanskrit.length} Sanskrit-route let it stand · ${HANDS.length} renderings · ${contestedCount} words flagged.`);
