// verify-is-the-voynich-manuscript-a-language.mjs: checks every number /strata/is-the-voynich-manuscript-a-language/
// states, by re-running the page's own engine (engine.mjs) on the page's own copy of the ZL transliteration
// and on the page's own table of the fifty CATMuS books.
//
//   node verify-is-the-voynich-manuscript-a-language.mjs                 # the page's files
//   node verify-is-the-voynich-manuscript-a-language.mjs --live          # also fetch ZL 3b from voynich.nu and
//                                                                        # check the page's copy is byte-identical
//   node verify-is-the-voynich-manuscript-a-language.mjs --catmus F.jsonl
//        also rebuild the fifty books' table from a text dump of CATMuS Medieval (one JSON object per row with
//        language, century, shelfmark, line_type, genre, script_type, verse, text; the repository's
//        research/voynich-measured/ has the script that makes one) and check the counts quoted from their text.
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it downloads
// engine.mjs, index.html and the data from https://artwaste.land (the bytes your browser runs).
// Exit 0 = every check passed.

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

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'is-the-voynich-manuscript-a-language';
const localDir = join(here, 'public/strata', slug);
const remote = `https://artwaste.land/strata/${slug}/`;
const LIVE = process.argv.includes('--live');
const ci = process.argv.indexOf('--catmus'); const CATMUS = ci > 0 ? process.argv[ci + 1] : null;
async function loadText(name) {
  const p = join(localDir, name); if (existsSync(p)) return readFileSync(p, 'utf8');
  const r = await fetch(remote + name); if (!r.ok) throw new Error(`${remote + name}: HTTP ${r.status}`); return r.text();
}
async function loadModule(name) {
  const p = join(localDir, name); if (existsSync(p)) return import(p);
  return import('data:text/javascript;base64,' + Buffer.from(await loadText(name)).toString('base64'));
}
console.error(`files: ${existsSync(localDir) ? localDir : remote}`);
const E = await loadModule('engine.mjs');
const ZL = await loadText('data/ZL3b-n.txt');
const HTML = (await loadText('index.html')).replace(/\s+/g, ' ');
const MS = JSON.parse(await loadText('data/manuscripts.json'));
const EXP = JSON.parse(await loadText('data/expected.json'));

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };
const says = s => HTML.includes(s);
const close = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;

// ── 1. the transliteration is the one named, and the engine reads it as the page says ──────────
const ZL_SHA = 'bf5b6d4ac1e3a51b1847a9c388318d609020441ccd56984c901c32b09beccafc';
ok(createHash('sha256').update(ZL).digest('hex') === ZL_SHA, `data/ZL3b-n.txt is ZL 3b (sha256 ${ZL_SHA.slice(0, 12)}...)`);
if (LIVE) {
  const r = await fetch('https://www.voynich.nu/data/ZL3b-n.txt'); const t = await r.text();
  ok(createHash('sha256').update(t).digest('hex') === ZL_SHA, 'voynich.nu still serves the same bytes (--live)');
}
const t0 = Date.now();
const V = E.measureVoynich(ZL);
console.error(`measureVoynich: ${Date.now() - t0} ms`);
ok(JSON.stringify(V) === JSON.stringify(Object.fromEntries(Object.entries(EXP).filter(([k]) => k !== 'zlSha256'))),
  'measureVoynich() on this machine reproduces data/expected.json exactly');
{
  const p = E.parseIVTFF('<f1r>      <! $L=A $H=1>\n<f1r.1,@P0>       <%>fa[c:o]hys.y{c\'y},ar<->ta?in<!@254;>\n<f1r.2,+P0>       sory.ckhar<$>\n');
  const w = p[0].lines[0].words;
  ok(w.join('|') === "fachys|yc'y|ar|ta?in" && p[0].lines[0].paraStart && p[0].lines[1].paraEnd && p[0].vars.L === 'A',
    'parser: first reading of [c:o], ligature braces dropped, comma and <-> are word spaces, comments removed, paragraph marks kept');
  ok(!E.isClean("yc'y") && !E.isClean('ta?in') && E.isClean('fachys'), 'words with an unreadable or odd glyph are left out of every count');
  ok(E.segment('qokchedy', 'bench').join(' ') === 'q o k ch e d y' && E.segment('cthaiin', 'bench+i').join(' ') === 'cth a iin',
    'the three cuts: ch and cth are one symbol in "bench"; iin also in "bench+i"');
}
// entropy on a text whose answer is known
{
  const st = E.symbolStream(Array(4000).fill('ab'));          // a b _ a b _ ... : every next symbol is certain
  ok(close(E.entropies(st).h2, 0, 1e-9) && close(E.entropies(st).h1, Math.log2(3), 1e-3), 'h2 of a fully predictable stream is 0; h1 of three equal symbols is log2 3');
}

// ── 2. every Voynich number in the prose ───────────────────────────────────────────────────────
const S = V.segs;
ok(says(`${S.eva.h2.toFixed(2)} to ${S['bench+i'].h2.toFixed(2)} bits`) && S.eva.h2 < S.bench.h2 && S.bench.h2 < S['bench+i'].h2,
  `h2 rises with each more generous cut: ${S.eva.h2.toFixed(3)}, ${S.bench.h2.toFixed(3)}, ${S['bench+i'].h2.toFixed(3)} (prose: "2.03 to 2.36")`);
const M = MS.manuscripts;
ok(M.length === 50 && says('<b>50 books</b>'), `50 books with at least ${MS.minWords} words`);
const printed = M.filter(m => m.script === 'Print');
ok(printed.length === 8 && says('Forty-two are manuscripts; eight are early printed books') && says('handwritten only (42)'), `8 printed, 42 handwritten`);
const words = M.reduce((s, m) => s + m.words, 0);
ok(words > 775000 && words < 825000 && says('about 800,000 words'), `about 800,000 words (${words})`);
const cents = [...new Set(M.map(m => m.century))].sort((a, b) => a - b);
ok(cents[0] === 9 && cents.at(-1) === 16 && says('from the ninth to the sixteenth century'), `centuries ${cents.join(', ')}`);
const langs = new Set(M.map(m => m.language));
ok(['Latin', 'French', 'Castilian', 'Middle Dutch', 'Italian'].every(l => langs.has(l)) && langs.size === 5, `languages: ${[...langs].join(', ')}`);
const h2s = M.map(m => m.h2);
ok(says(`${Math.min(...h2s).toFixed(2)} to ${Math.max(...h2s).toFixed(2)}`) && Math.min(...h2s) > S['bench+i'].h2,
  `every book's h2 (${Math.min(...h2s).toFixed(3)} to ${Math.max(...h2s).toFixed(3)}) is above the Voynich's most generous cut`);
const lowest = M.reduce((a, b) => a.h2 < b.h2 ? a : b);
ok(lowest.language === 'French' && lowest.century === 13 && lowest.verse === 'verse' && says('a thirteenth-century French verse manuscript at 3.06'),
  `the most predictable book is ${lowest.shelfmark} (${lowest.language}, ${lowest.century}th c., ${lowest.verse})`);
const third = (S['bench+i'].h2 - S.eva.h2) / (lowest.h2 - S.eva.h2);
ok(third > 0.28 && third < 0.36 && says('closes about a third of the gap'), `the generous cut closes ${(100 * third).toFixed(1)}% of the gap`);

const g = V.lastGlyphs.find(t => t.g === 'g'), m = V.lastGlyphs.find(t => t.g === 'm');
ok(g.edge / g.n > 0.78 && g.edge / g.n < 0.8 && m.edge / m.n > 0.69 && m.edge / m.n < 0.71,
  `line-final share: -g ${g.edge}/${g.n}, -m ${m.edge}/${m.n} (Currier's unnamed 85% symbol is neither exactly)`);
const topFirst = V.firstGlyphs.slice().sort((a, b) => b.edge / b.n - a.edge / a.n).slice(0, 2).map(t => t.g).join('');
ok(topFirst === 'pt', `the letters most bound to the line start are p and t (${topFirst})`);
ok(V.inner.lastInfo >= S.eva.lastInfo * 0.9 && V.inner.firstInfo > 0.1, `without first and last paragraph lines the effect stays (end ${V.inner.lastInfo.toFixed(3)}, start ${V.inner.firstInfo.toFixed(3)})`);
const vS = S.eva.same / S.eva.nullSame, vO = S.eva.one / S.eva.nullOne, vP = V.neighboursByPage.same / V.neighboursByPage.nullSame;
ok(vS > 1.4 && vS < 1.55 && vP > 1.2 && vP < vS, `the same word twice: ${vS.toFixed(2)} x shuffled (30-line runs), ${vP.toFixed(2)} x (pages)`);
const maxSame = Math.max(...M.map(m => m.same / m.nullSame));
ok(maxSame < 1 && says(`the most repetitive at ${maxSame.toFixed(2)}`), `every book repeats less than chance; highest ${maxSame.toFixed(3)}`);
const hb = V.across.herbalBio, rest = V.across.rest;
ok(hb.acSame === 6 && Math.round(hb.expected) === 20 && rest.acSame === 0 && Math.round(rest.expected) === 11,
  `across the line break: ${hb.acSame} (expected ${hb.expected.toFixed(1)}) in herbal+biological, ${rest.acSame} (expected ${rest.expected.toFixed(1)}) elsewhere`);
ok(V.agree === 179 && V.labelled === 184 && says('179 of 184'), `blind split agrees with Currier on ${V.agree} of ${V.labelled}`);
const dis = V.map.filter(p => p.L && p.cluster !== p.L).map(p => p.folio).sort().join(' ');
ok(dis === 'f102v2 f58r f58v f88v f99v', `the five disagreements: ${dis}`);
ok(V.map.filter(p => p.folio === 'f58r' || p.folio === 'f58v').every(p => p.H === '3') && V.map.filter(p => p.H === '3' && p.L && p.folio !== 'f58r' && p.folio !== 'f58v').every(p => p.L === 'B'),
  "f58r and f58v are Davis's scribe 3, whose other labelled pages are all B");
const herb = V.map.filter(p => p.I === 'H' && (p.L === 'A' || p.L === 'B'));
ok(herb.every(p => p.cluster === p.L), `all ${herb.length} labelled herbal pages land on Currier's side`);
ok(V.scribes.herbalB.hit - V.scribes.herbalB.majority <= 2, `scribes within herbal B: ${V.scribes.herbalB.hit}/${V.scribes.herbalB.n} vs ${V.scribes.herbalB.majority} by always guessing the commonest`);

// ── 3. the other books' line edges, and the pre-registration ───────────────────────────────────
const endPass = M.filter(x => x.lastInfo >= S.eva.lastInfo), startPass = M.filter(x => x.firstInfo >= S.eva.firstInfo);
ok(endPass.length === 3 && endPass.every(x => x.script !== 'Print'), `three books reach the Voynich at the line end, all handwritten: ${endPass.map(x => x.shelfmark).join('; ')}`);
ok(endPass.filter(x => x.verse === 'verse' && x.language === 'French').length === 2 && endPass.some(x => x.shelfmark.includes('Lázaro Galdiano')), 'two French verse, one Castilian treatise');
ok(startPass.length === 1 && startPass[0].shelfmark === 'Paris, Mazarine, Inc. 59' && startPass[0].script === 'Print', 'one book passes it at the line start: the printed Mazarine Inc. 59');
const z = n => M.find(x => x.shelfmark.includes(n)).topLast[0];
ok(z('Reg.lat. 1616').g === 'z' && Math.round(100 * z('Reg.lat. 1616').share) === 61 && z('Bodmer').g === 'z' && Math.round(100 * z('Bodmer').share) === 55, 'words in z end a line 61% and 55% of the time in the two verse books');
const seen = new Set(MS.seenBeforePreregistration), unseen = M.filter(x => !seen.has(x.shelfmark));
ok(seen.size === 21 && unseen.length === 29, '21 books seen before the pre-registration, 29 scored');
ok(unseen.every(x => x.h2 >= 2.6), 'prediction 1 held: no unseen book under 2.60 bits');
ok(unseen.filter(x => x.verse === 'prose' && x.lastInfo >= 0.089).length === 0, 'prediction 2 held');
ok(unseen.filter(x => x.firstInfo >= 0.149).map(x => x.shelfmark).join() === 'Paris, Mazarine, Inc. 59', 'prediction 3 failed, on Mazarine Inc. 59 alone');
ok(unseen.every(x => x.same / x.nullSame < 1), 'prediction 4 held');
const oneFail = unseen.filter(x => x.one / x.nullOne >= 1);
const top3 = oneFail.slice().sort((a, b) => b.one / b.nullOne - a.one / a.nullOne).slice(0, 3);
ok(oneFail.length === 6 && top3.every(x => x.language === 'Latin' && x.century <= 10) && says(`${(top3[2].one / top3[2].nullOne).toFixed(2)} to ${(top3[0].one / top3[0].nullOne).toFixed(2)}`),
  `prediction 5 failed on six; the top three are ninth- and tenth-century Latin treatises at ${top3.map(x => (x.one / x.nullOne).toFixed(2)).join(', ')}`);

// ── 4. the measures respond as they should (controls on the Voynich itself) ────────────────────
{
  const pages = E.parseIVTFF(ZL);
  const VL = E.paragraphLines(pages).map(l => l.words.filter(E.isClean).map(w => [...w])).filter(l => l.length);
  const r = E.rng(1);
  const shuffledInLines = VL.map(l => E.shuffle(l, r));
  const sh = E.measureLines(shuffledInLines, 3);
  ok(sh.lastInfo < 0.01 && sh.firstInfo < 0.01, `shuffling words inside each line erases the line effect (end ${sh.lastInfo.toFixed(4)}, start ${sh.firstInfo.toFixed(4)})`);
  const doubled = VL.map(l => l.flatMap((w, i) => i % 4 === 0 ? [w, w] : [w]));
  const d = E.measureLines(doubled, 3);
  ok(d.same / d.nullSame > 3, `doubling every fourth word drives the repeat ratio up (${(d.same / d.nullSame).toFixed(2)})`);
  const flat = VL.flat(); const rw = []; let k = 0; const rr = E.rng(2); const fl = E.shuffle(flat, rr);
  for (const l of VL) rw.push(l.map(() => fl[k++]));
  const all = E.measureLines(rw, 3);
  ok(all.same / all.nullSame > 0.85 && all.same / all.nullSame < 1.15, `words shuffled across the whole text repeat at chance (${(all.same / all.nullSame).toFixed(2)})`);
}

// ── 5. optional: rebuild the fifty from a CATMuS text dump ─────────────────────────────────────
if (CATMUS) {
  const rows = readFileSync(CATMUS, 'utf8').trim().split('\n').map(JSON.parse);
  ok(rows.length === MS.rowsRead, `CATMuS dump has ${rows.length} rows (table built from ${MS.rowsRead})`);
  const by = new Map();
  for (const r of rows) { if (r.line_type && !/^(DefaultLine|default)$/.test(r.line_type)) continue; if (!by.has(r.shelfmark)) by.set(r.shelfmark, []); by.get(r.shelfmark).push(r); }
  let same = 0;
  for (const x of M) { const L = by.get(x.shelfmark).map(r => E.wordsOfLine(r.text)).filter(l => l.length); const y = E.measureLines(L); if (close(y.h2, x.h2) && close(y.lastInfo, x.lastInfo) && close(y.firstInfo, x.firstInfo) && close(y.same, x.same)) same++; }
  ok(same === 50, `all 50 rows of data/manuscripts.json recomputed exactly (${same})`);
  const mad = by.get('Madrid, Fundación Lázaro Galdiano, mss 289'); let n = 0, e = 0, sN = 0, sE = 0;
  for (const r of mad) { const L = E.wordsOfLine(r.text); L.forEach((w, i) => { const last = i === L.length - 1; if (w.at(-1).includes('ᷤ')) { n++; if (last) e++; } else if (w.at(-1) === 's') { sN++; if (last) sE++; } }); }
  ok(n === 312 && e === 309 && sN === 8124 && sE === 726 && says('309 of the 312') && says('726 of 8,124'), `raised s: ${e} of ${n} line-final; plain s: ${sE} of ${sN}`);
  const maz = by.get('Paris, Mazarine, Inc. 59'); const de = maz.filter(r => r.text.trim().toLowerCase().startsWith('de ')).length;
  ok(maz.length === 1880 && de === 704 && says('704 of its 1,880 lines'), `Mazarine Inc. 59: ${de} of ${maz.length} lines begin "De"`);
} else console.log('(skip) the counts quoted from CATMuS text itself (309/312, 704/1,880) need --catmus <dump>');

console.log(`\n${passes} passed, ${fails} failed`);
process.exit(fails ? 1 : 0);
