#!/usr/bin/env node
/* Verify "The First Man to Read It" (/strata/the-first-man-to-read-it/). Offline, no network.
   Three layers of assertion:
     A. selected phrases from renderings, attestations and transliterations appear in the
        page HTML and committed source transcriptions under sources/, after normalization;
     B. no PENDING-A markers survive in the page HTML;
     C. selected counts are checked using a separate classification table and constants.
        This does not establish every figure at every displayed occurrence.
   Run: node research/gilgamesh-flood/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', 'the-first-man-to-read-it', 'index.html'), 'utf8');
const srcDir = join(here, 'sources');

/* normalisation: strip diacritics/punct, fold case+whitespace, drop standalone digit tokens
   (printed line numbers interleave the verse in several sources). */
const norm = s => s
  .normalize('NFD').replace(/[̀-ͯ]/g, '')
  .toLowerCase().replace(/æ/g, 'ae')
  .replace(/[^a-z0-9]+/g, ' ')
  .replace(/\b\d+a?\b/g, ' ')
  .replace(/\s+/g, ' ').trim();

const stripTags = h => h.replace(/<[^>]+>/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
const hay = norm(stripTags(html));
const inPage = s => hay.includes(norm(s));

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) => readSrc(file).includes(norm(s));

let pass = 0, fail = 0; const misses = [];
const check = (label, ok) => { if (ok) pass++; else { fail++; misses.push(label); } };
const quote = (file, ...phrases) => phrases.forEach(p => {
  check(`page: "${p.slice(0, 58)}"`, inPage(p));
  check(`src[${file}]: "${p.slice(0, 58)}"`, inSrc(file, p));
});

/* ---------- structural guards ---------- */
check('no PENDING markers left on the page', !html.includes('PENDING-A'));

/* ---------- A1. the legend instrument (Instrument I) ---------- */
quote('tsba-discussion-1873.txt',
  'A short time back I discovered among the Assyrian tablets in the British Museum, an account of the flood; which, under the advice of our President, I now bring before the Society',
  'Read 3rd December, 1872');
quote('tsba-discussion-1873.txt',
  'On reconsidering the subject of the very curious paper on the Deluge, which was read by Mr. George Smith, on Tuesday evening last, before the Society of Biblical Archaeology, I have come to the conclusion that the series of Izdubar legends is neither more nor less than the local rendering of the old universal solar myth');
quote('chicago-tribune-1872.txt',
  'In this newly discovered inscription the account of the Deluge is put as a narrative into the mouth of Xisuthrus, or Noah',
  'He relates the wickedness of the world, the command to build the ark, its building, the filling of it, the Deluge, the resting of the ark on a mountain, the sending out of the birds, and other matters',
  'has a closer resemblance to the account translated by the Greeks from Berosus, the Chaldean historian, than to the Biblical history, but it does not differ materially from either',
  'The principal differences are as to the duration of the Deluge, the name of the mountain on which the ark rested, the sending out of birds');
quote('smith-1875-assyrian-discoveries.txt',
  'On cleaning one of them I found to my surprise and gratification that it contained the greater portion of seventeen lines of inscription belonging to the first column of the Chaldean account of the Deluge, and fitting into the only place where there was a serious blank in the story',
  'the telegram as published differs materially from the one I sent');
quote('smith-death.txt',
  'his translation of which was read before a meeting of the Society of Biblical Archaeology held on 3 Dec. 1872, at which Mr. Gladstone was present',
  'The interest of the discovery was accentuated by the modest way in which it was announced',
  'almost a household word in Great Britain');
quote('budge-1925.txt',
  'Smith took the tablet and began to read over the lines which Ready had brought to light',
  'I am the first man to read that after more than two thousand years of oblivion',
  'he jumped up and rushed about the room in a great state of excitement, and, to the astonishment of those present, began to undress himself');

/* ---------- A2. the hands (Instrument II) ---------- */
/* Sayce 1880 */
quote('sayce-1880.txt',
  'the minister of the city of Kis, he declared what he had (in mind)',
  'Man of Surippak, son of Ubara-tutu',
  'build a house, make a ship to preserve the sleep of plants (and) living beings',
  'thou shalt say unto them',
  'he has rejected me and',
  'I sent forth a dove and it left. The dove went, it returned, and',
  'a resting-place it did not find, and it came back',
  'I sent forth a raven and it left',
  'The raven went, and the carrion on the water it saw, and',
  'it did eat, it swam, and turned away, it did not come back',
  'the gods like flies over the sacrificer gathered');
/* Jastrow 1898 */
quote('jastrow-1898.txt',
  'To proclaim their resolve to the reed-huts',
  'Reed-hut, reed-hut, clay structure, clay structure',
  'Reed-hut, hear! Clay structure, give ear!',
  'are poetically used to designate the inhabitants of Shurippak',
  'Hear, Heavens ! and give ear, Earth !',
  'O man of Shurippak, son of Kidin-Marduk !',
  'Erect a structure, build a ship',
  'When Shamash will bring on the time, then the lord of the whirlstorm',
  'Will cause destruction to rain upon you in the evening',
  'When the seventh day approached',
  'I sent forth a dove',
  'But, finding no resting place, returned',
  'The raven flew off, and, seeing that the waters had decreased',
  'waded in the mud, but did not return',
  'The gods inhaled the odor',
  'The gods gathered like flies around the sacrificer');
/* Muss-Arnolt 1901 */
quote('muss-arnolt-1901.txt',
  'Their plan he told to a reed-hut, (saying)',
  'Reed-hut, reed-hut, clay-structure, clay-structure',
  'Reed-hut, hear; clay-structure, pay attention',
  'Thou man of Shurippak, son of Ubara-Tutu',
  'Build a house, construct a ship',
  'Upon you he will (for a time?) pour down rich blessing',
  'fowl [in plenty] and fish in abundance',
  'Herds of cattle and an abundant] harvest',
  'Shamash has appointed a time when the rulers of darkness',
  'at eventide will pour down upon you] a destructive rain',
  'So Zimmern, Jensen (1900); others, when he who sends heavy rains (Jeremias)',
  'I sent out a dove, and let her go',
  'The dove flew hither and thither',
  'but as there was no resting-place for her, she returned',
  'The raven flew away and saw the abatement of the waters',
  'She settled down to feed, went away, and returned no more',
  'the gods gathered like flies around the sacrificer');
/* Rogers 1912 — English */
quote('rogers-1912.txt',
  'And repeated their word to the reed hut',
  'O reed hut, reed hut, O, wall, wall',
  'O reed hut hearken, O wall attend',
  'O man of Shurippak, son of Ubaratutu',
  'Pull down thy house, build a ship',
  'spoke his message to the walls of the house within which Ut-napishtim',
  '[A time has Shamash appointed], on an evening the senders of rain',
  'Shall rain upon you a mighty rain-storm',
  'I sent forth a dove and let her go',
  'The dove flew away and came back',
  'For there was no resting place and she returned',
  'The raven flew away, she saw the abatement of the waters',
  'She drew near, she waded, she croaked (?) and came not back',
  'The gods smelt the savor',
  'The gods smelt the sweet savor',
  'The gods gathered like flies over the sacrificer',
  'Then I sent everything forth to the four quarters of',
  'I made a libation upon the mountain');
/* Rogers 1912 — transliteration */
quote('rogers-1912.txt',
  'ki-ik-kiš ki-ik-kiš i-gar i-gar',
  'ki-ik-ki-šu ši-me-ma i-ga-ru ḫi-is-sa-as',
  'ku-uk-ki',
  'nu-ši ša-mu-tu ki-ba-a-ti',
  'u-še-ṣi-ma summatu u-maš-šir',
  'il-lik summatu i-tu-ra-am-ma',
  'man-za-zu ul i-pa-aš-šim-ma is-saḫ-ra',
  'ilâni kî-ma zu-um-bi-e eli bêl-nikê ip-taḫ-ru',
  'Ut-napiš-tim ana ša-šu ma izzaka-ra a-na (ilu) Gilgameš');
/* Thompson 1928 */
quote('thompson-1928.txt',
  'Unto a reed-hut their counsel betray’d he: “O Reed-hut, O Reed-hut!',
  'Wall, wall! Hearken, O Reed-hut, consider, O Wall! O thou Mortal',
  'Thou of Shurippak, thou scion of Ubara-Tutu, a dwelling',
  'Pull down, (and) fashion a vessel (therewith)',
  'Booty of fish',
  'causing a plentiful rainfall (?) to come down upon you',
  'Two difficult lines',
  'when the seventh day dawn’d, I put forth a dove, and released (her)',
  '(But) to and fro went the dove, and return’d (for) a resting-place was not',
  'the raven went, too, and th’ abating of waters',
  'Saw; and she ate as she waded (and) splash’d, (unto me) not returning',
  'the gods smelt the savour, the gods the sweet savour',
  'Smelt; (aye,) the gods did assemble like flies o’er him making the off’ring');

/* Smith 1873 (TSBA) */
quote('smith-1873-tsba.txt',
  'their will revealed in the midst of',
  'hearing and he spoke to me thus',
  'make a great ship for thee',
  'Here there are about fifteen lines entirely lost. The absent passage probably described part of the building of the ark',
  'I sent forth a dove, and it left. The dove went and searched and',
  'a resting place it did not find, and it returned',
  'I sent forth a raven, and it left',
  'The raven went, and the corpses on the waters it saw, and',
  'it did eat, it swam, and wandered away, and did not return',
  'The gods collected at its burning, the gods collected at its good burning',
  'the gods like sumbe over the sacrifice gathered');
/* Smith 1876 (Chaldean Account of Genesis) */
quote('smith-1876-chaldean-genesis.txt',
  'their will he revealed in the midst',
  'I his will was hearing and he spake to me',
  'Surippakite son of Ubaratutu',
  'A flood Shamas made and',
  'he spake saying in the night : I will cause it to rain heavily',
  'I sent forth a dove and it left. The dove went and turned, and',
  'a resting-place it did not find, and it returned',
  'The raven went, and the decrease of the water it saw, and',
  'The gods collected at its savour, the gods collected at its good savour',
  'the gods like flies over the sacrifice gathered',
  'my first notice was inaccurate in several points, both as to the order and translation of the legends; but I had not expected it to be otherwise',
  'REVERSE OF INSCRIBED TERRA COTTA TABLET CONTAINING THE ACCOUNT OF THE DELUGE',
  'In this tablet there are sixteen fragments');

/* ---------- A3. the names (Instrument III) ---------- */
quote('pinches-1890.txt',
  'It has been found at last, the long wished-for reading of the name of the well-known hero, and it is neither Gistubar, nor Gisdubar, nor Gisdubarra, nor Izdubar, nor finally, Namrasit, but',
  'The text which gives it is from Babylonia, and is numbered 82-5-22, 915');
check('page: GILGAMES pivot', inPage('GILGAMES'));
check('src[pinches-1890.txt]: GILGAMES', inSrc('pinches-1890.txt', 'GILGAMES'));
quote('pinches-1890.txt', 'IZDUBAR-NIMROD', 'EINE ALTBABYLONISCHE HELDENSAGE');
quote('tablet-catalogue.txt',
  'Tsit-napishtim related the story which is inscribed on the Eleventh Tablet of the poem of Gilgamesh',
  'Fragment of a baked clay tablet inscribed with the Babylonian account of the Deluge',
  'No. K. 3375');
quote('jastrow-1898.txt',
  'form Izdubar, the reading Gilgamesh is to be preferred',
  'sends a special message to Parnapishtim');
quote('muss-arnolt-1901.txt', 'Per-napishtim then said unto Gilgamesh');
quote('thompson-1928.txt',
  'Uta-Napishtim (addressing him thus) unto Gilgamish answer’d',
  'Atra-hasis, another name for Uta-Napishtim');
quote('sayce-1880.txt', '(Izdubar) to him also speaks even to Xisuthrus');
quote('smith-1873-tsba.txt',
  'The text itself professes to belong to the time of a monarch whose name, written in monograms, I am unable to read phonetically. I therefore provisionally call him by the ordinary values of the signs of his name, Izdubar',
  'The hero of the Flood I have provisionally called Sisit; he corresponds, of course, to the Greek Xisuthrus, but no comparison of the two names can be made until we know the phonetic reading of the Cuneiform name');
quote('smith-1875-assyrian-discoveries.txt',
  'In the new fragments I found at Kouyunjik, I discovered that this hero bore the name of Hasisadra, which is the origin of the Greek form of his name, Xisithrus');
quote('smith-1876-chaldean-genesis.txt',
  'Hasisadra after this manner also said to Izdubar',
  'Izdubar, composite figures, and Hasisadra (Noah) in the ark');

/* ---------- A4. beside Genesis (Instrument IV) ---------- */
quote('kjv-genesis.txt',
  'And he sent forth a raven, which went forth to and fro, until the waters were dried up from off the earth',
  'Also he sent forth a dove from him',
  'But the dove found no rest for the sole of her foot, and she returned unto him into the ark',
  'And he stayed yet other seven days; and sent forth the dove; which returned not again unto him any more',
  'And Noah builded an altar unto the LORD; and took of every clean beast, and of every clean fowl, and offered burnt offerings on the altar',
  'And the LORD smelled a sweet savour; and the LORD said in his heart, I will not again curse the ground any more for man');
/* Smith's own dating of the copies */
quote('tablet-catalogue.txt', 'about 660 years before the Christian era');

/* ---------- C. selected counts from separate classifications ---------- */
/* layers: [year, isLegend, isContemporary1872] */
const LAYERS = [
  ['1872-tsba', false, true],
  ['1872-athenaeum', false, true],
  ['1872-tribune', false, true],
  ['1875-smith', false, false],
  ['1890s-dnb', true, false],
  ['1925-budge', true, false],
];
check(`6 layers (got ${LAYERS.length})`, LAYERS.length === 6);
check(`3 contemporary 1872 layers (got ${LAYERS.filter(l => l[2]).length})`, LAYERS.filter(l => l[2]).length === 3);
check(`2 legend layers (got ${LAYERS.filter(l => l[1]).length})`, LAYERS.filter(l => l[1]).length === 2);
check('gap 1925-1872 = 53', 1925 - 1872 === 53);

/* Independent classifications of the displayed readings.
   flies: keep/absent · food: keep/absent
   reed: keep = full address; kis = minister/city; absent = fragmentary warning without a wall */
const HANDS = [
  ['Smith', 1873, { reed: 'absent', food: 'absent', birds: 'keep', flies: 'keep' }], // warning survives in fragments; flies kept with untranslated "sumbe"
  ['Smith', 1876, { reed: 'absent', food: 'absent', birds: 'keep', flies: 'keep' }], // fragmentary warning, no wall rendered
  ['Sayce', 1880, { reed: 'kis', food: 'absent', birds: 'keep', flies: 'keep' }],
  ['Jastrow', 1898, { reed: 'keep', food: 'absent', birds: 'keep', flies: 'keep' }],
  ['Muss-Arnolt', 1901, { reed: 'keep', food: 'keep', birds: 'keep', flies: 'keep' }],
  ['Rogers', 1912, { reed: 'keep', food: 'keep', birds: 'keep', flies: 'keep' }],
  ['Thompson', 1928, { reed: 'keep', food: 'keep', birds: 'keep', flies: 'keep' }],
];
check(`7 hands (got ${HANDS.length})`, HANDS.length === 7);
const fliesKeep = HANDS.filter(h => h[2].flies === 'keep').length;
check(`flies simile kept by all hands that reach it (got ${fliesKeep}/${HANDS.length})`, fliesKeep === HANDS.length);
const foodAbsent = HANDS.filter(h => h[2].food === 'absent').length;
check(`4 hands lack the food-promise (got ${foodAbsent})`, foodAbsent === 4);
const reedAbsent = HANDS.filter(h => h[2].reed === 'absent').length;
check(`2 hands show fragmentary warnings without a rendered wall (got ${reedAbsent})`, reedAbsent === 2);
const reedApostrophe = HANDS.filter(h => h[2].reed === 'keep');
check(`full reed apostrophe first among these hands in 1898 (got ${reedApostrophe[0] && reedApostrophe[0][1]})`,
  reedApostrophe.length > 0 && reedApostrophe[0][1] === 1898);

/* flood-hero printed forms */
const floodForms = ['Xisuthrus', 'Sisit', 'Hasisadra', 'Adrakhasis', 'Parnapishtim', 'Tsit-napishtim', 'Per-napishtim', 'Ut-napishtim', 'Uta-Napishtim'];
check(`9 flood-hero forms (got ${floodForms.length})`, floodForms.length === 9);
floodForms.forEach(f => check(`page prints flood form "${f}"`, inPage(f)));
check('Izdubar era 1872→1890 = 18 years', 1890 - 1872 === 18);
check('page states 18 years', inPage('Izdubar for 18 years') || inPage('eighteen years'));

/* ---------- report ---------- */
console.log(`The First Man to Read It — 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('Selected normalized phrases and the separate count checks pass. ✓');
