#!/usr/bin/env node
// verify-ink-with-nothing-under-it.mjs: checks /strata/ink-with-nothing-under-it/ ("Ink With Nothing Under It").
//
//   node verify-ink-with-nothing-under-it.mjs           # every figure, recomputed from the census records
//   node verify-ink-with-nothing-under-it.mjs --live    # also ask archive.org itself about the Blondel page
//   node verify-ink-with-nothing-under-it.mjs --mutate  # also corrupt the records on purpose; checks must go red
//
// Needs only Node 18+. Inside the repository it reads the local files; from an empty directory it
// downloads the page, census.json, data.json, adjudication.jsonl and search-inside.json from
// https://artwaste.land into ./ink-with-nothing-under-it-files/. Exit 0 = every check passed.
//
// What it checks:
//  A. the census, recomputed from its per-page records: how many items were drawn and why each
//     excluded one was, how many usable pages lost body text (and other printed text), by date,
//     kind and OCR engine, with Wilson 95% intervals; lines lost per thousand; the planted-line
//     recall by width; the final count of each class of flagged band;
//  B. the adjudication: agreement between the classifiers and the author on the bands re-examined,
//     and the second-engine witness (words read in the missing bands that the page's layer lacks);
//  C. the search-inside probes: every probe word came back with no hit, every control was found on
//     its own page;
//  D. that the page states each of these figures, and that data.json agrees with the records;
//  E. with --live: fetches the Internet Archive's own hOCR for the Blondel page (item
//     coursdarchitectu00blon, leaf 897) and confirms no word box overlaps the three lines
//     (image rows 682 to 894 of that leaf), none of their distinctive words is in the leaf's
//     text, and "Chambor", printed lower on the same page, is.
// What it does NOT check: that a band called "body text" is body text. That was done by looking,
// twice; the calls are in adjudication.jsonl, with the classifier's first call beside each.

import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { gunzipSync } from 'node:zlib';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'ink-with-nothing-under-it';
const LIVE = process.argv.includes('--live');
const MUTATE = process.argv.includes('--mutate');
const FILES = ['index.html', 'census.json', 'data.json', 'adjudication.jsonl', 'search-inside.json'];
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'census.json'))) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const read = (f) => readFileSync(join(dir, f), 'utf8');

function wilson(k, n, z = 1.959964) {
  const p = k / n, d = 1 + z * z / n;
  const c = (p + z * z / (2 * n)) / d, h = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d;
  return [Math.max(0, c - h), Math.min(1, c + h)];
}
const pct = (x) => (100 * x).toFixed(1);

function checks(census, data, adj, probes, html, quiet = false) {
  let pass = 0, fail = 0;
  const ok = (cond, label) => {
    if (cond) { pass++; if (!quiet) console.log('  ok   ' + label); }
    else { fail++; if (!quiet) console.log('  FAIL ' + label); }
  };
  const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
    .replace(/<[^>]+>/g, ' ').replace(/&amp;/g, '&').replace(/&middot;/g, '·').replace(/\s+/g, ' ');
  const says = (s) => ok(text.includes(s), `page says "${s}"`);
  const rows = census.rows, ok_ = rows.filter((r) => r.status === 'ok');

  if (!quiet) console.log('A. the census, from its records');
  ok(rows.length === 300, `300 items drawn (${rows.length})`);
  const per = (s) => rows.filter((r) => r.stratum === s).length;
  ok(per('before-1800') === 100 && per('1800-1899') === 100 && per('1900-1928') === 100, '100 in each date stratum');
  ok(ok_.length === 213, `213 usable pages (${ok_.length})`); says('Of the 300 items, 213 gave a usable page');
  const st = {}; for (const r of rows) st[r.status] = (st[r.status] || 0) + 1;
  const ex = [['excluded:no-hocr', 68, '68 had no hOCR at all'], ['excluded:unavailable', 8, '8 files would not download'],
    ['excluded:unverified-page-match', 5, '5 failed the same-page check'], ['excluded:restricted', 4, '4 were access-restricted'],
    ['excluded:multi-book', 2, '2 held several books in one item']];
  for (const [k, n, s] of ex) { ok(st[k] === n, `${k} = ${n} (${st[k]})`); says(s); }
  ok(rows.filter((r) => r.status === 'excluded:no-hocr').every((r) => /^ABBYY/.test(r.ocr || '')), 'all 68 no-hOCR items credit ABBYY FineReader');

  const summ = (sel) => {
    const n = sel.length, a = sel.filter((r) => r.A > 0).length, ab = sel.filter((r) => r.A > 0 || r.B > 0).length;
    return { n, a, ab, ci: wilson(a, n), ciab: wilson(ab, n) };
  };
  const all = summ(ok_);
  ok(all.a === 26, `26 pages lost body text (${all.a})`);
  ok(all.ab === 58, `58 lost body or other printed text (${all.ab})`);
  says('26 of 213'); says('58 of 213');
  says(`${pct(all.a / all.n)}% (95% interval ${pct(all.ci[0])}% to ${pct(all.ci[1])}%)`);
  says(`${pct(all.ab / all.n)}% (${pct(all.ciab[0])}% to ${pct(all.ciab[1])}%)`);
  const tableRow = (label, s) => {
    const want = `${label} ${s.n} ${s.a} ${pct(s.a / s.n)}% (${pct(s.ci[0])} to ${pct(s.ci[1])}) ${s.ab}`;
    ok(text.includes(want), `table row "${want}"`);
  };
  tableRow('Printed before 1800', summ(ok_.filter((r) => r.stratum === 'before-1800')));
  tableRow('1800 to 1899', summ(ok_.filter((r) => r.stratum === '1800-1899')));
  tableRow('1900 to 1928', summ(ok_.filter((r) => r.stratum === '1900-1928')));
  const news = summ(ok_.filter((r) => r.kind === 'newspaper or periodical')), other = summ(ok_.filter((r) => r.kind === 'other'));
  tableRow('Newspapers and periodicals', news); tableRow('Everything else', other);
  tableRow('All', all);
  const ratio = (news.a / news.n) / (other.a / other.n);
  ok(ratio > 2.5 && ratio < 3.5, `newspapers about three times as likely (${ratio.toFixed(2)})`);
  if (ratio > 2.5 && ratio < 3.5) says('a page of a newspaper was about three times as likely to have lost body text');
  const ab = summ(ok_.filter((r) => r.engine === 'ABBYY')), te = summ(ok_.filter((r) => r.engine === 'tesseract'));
  ok(ab.n === 20 && ab.a === 0 && te.n === 193 && te.a === 26, `ABBYY 0 of 20, tesseract 26 of 193 (${ab.a}/${ab.n}, ${te.a}/${te.n})`);
  says('0 of 20 ABBYY pages against 26 of 193 tesseract pages');

  const lined = ok_.filter((r) => !r.whole_page);
  ok(ok_.filter((r) => r.whole_page).length === 2, 'two printed pages with an empty text layer, left out of the line rate');
  ok(ok_.every((r) => r.whole_page === (r.n_lines === 0 && r.A > 0)), 'whole_page is exactly: empty layer and missing body text');
  ok(ok_.filter((r) => r.n_lines === 0 && r.n_cand === 0).length === 2, 'the other two empty-layer pages flag nothing (blank images)');
  says('Two printed pages have an empty text layer'); says('Two more printed pages have an empty layer');
  const lost = lined.reduce((s, r) => s + (r.A_lines || 0), 0), tl = lined.reduce((s, r) => s + (r.n_lines || 0) + (r.A_lines || 0), 0);
  const top = lined.reduce((m, r) => (r.A_lines > m.A_lines ? r : m), lined[0]);
  const rate = 1000 * lost / tl, rate2 = 1000 * (lost - top.A_lines) / (tl - top.n_lines - top.A_lines);
  ok(lost === 532, `532 body lines lost on pages with a layer (${lost})`); says('532 lines');
  says(`${rate.toFixed(1)} per thousand text lines; ${top.A_lines} of them on one page, and ${rate2.toFixed(1)} per thousand without it`);

  const P = ok_.flatMap((r) => r.plants || []);
  const bin = (lo, hi) => { const q = P.filter(([w]) => w >= lo && w < hi); return [q.length, q.filter(([, f]) => f).length]; };
  for (const [lo, hi, label] of [[0, 1 / 6, 'under a sixth of the text block'], [1 / 6, 0.5, 'a sixth to a half'], [0.5, 1.01, 'half or more'], [0, 1.01, 'all']]) {
    const [n, f] = bin(lo, hi); const want = `${label} ${n} ${f} ${pct(f / n)}%`;
    ok(text.includes(want), `recall row "${want}"`);
  }
  const cls = { A: 0, B: 0, C: 0, D: 0, H: 0 };
  for (const r of ok_) for (const k of Object.keys(cls)) cls[k] += r[k] || 0;
  const nb = Object.values(cls).reduce((a, b) => a + b, 0);
  ok(nb === 656, `656 flagged bands (${nb})`); says('All 656 flagged bands');
  for (const [k, s] of [['A', '86 body text'], ['B', '188 other printed text'], ['C', '352 not text'], ['D', '13 covered after all'], ['H', '17 handwriting']]) {
    ok(cls[k] === Number(s.split(' ')[0]), `${k} = ${s.split(' ')[0]} (${cls[k]})`); says(s);
  }
  says(`${cls.C} against ${cls.A + cls.B}`);
  says(`Five pages failed that`); ok(st['excluded:unverified-page-match'] === 5, 'five same-page failures');
  { const [n, f] = bin(0.5, 1.01), [n2, f2] = bin(0, 1 / 6);
    says(`${pct(f / n)}% and ${pct(f2 / n2)}%`);
    if (f / n >= 0.75 && f / n < 0.85) says('A full line missing from a book page is found four times in five');
    else ok(false, 'wide-line recall is about four in five'); }

  const cNotes = adj.filter((a) => a.final === 'C');
  const struct = cNotes.filter((a) => /rule|border|box|frame|edge|margin|gutter|background|show-through|bleed/i.test(a.note)).length;
  ok(struct === 270, `270 of the not-text notes name a structural cause (${struct})`);
  says(`named in ${struct} of the ${cNotes.length}`);
  if (!quiet) console.log('B. the adjudication');
  const byCand = new Map(adj.map((a) => [a.cand, a]));
  ok(adj.length === 656, `656 adjudicated bands (${adj.length})`);
  for (const r of ok_) {
    const f = r.n_cand ? Array.from({ length: r.n_cand }, (_, i) => byCand.get(`${r.id}#c${i}`)?.final) : [];
    if (f.filter((x) => x === 'A').length !== r.A) { ok(false, `${r.id}: A count agrees with adjudication`); }
  }
  ok(true, 'per-page A counts agree with adjudication.jsonl');
  const rev = adj.filter((a) => a.reviewed);
  const agree = rev.filter((a) => a.agent === a.author).length;
  ok(rev.length === 333 && agree === 298, `re-examined 333, agreed 298 (${rev.length}, ${agree})`);
  says(`Of the 333 bands I looked at again, I agreed with the classifier on 298 (${pct(agree / rev.length)}%)`);
  const hand = rev.filter((a) => a.author === 'H' && a.agent !== 'H').length;
  ok(hand === 17, `17 of the disagreements were handwriting (${hand})`);
  says(`${['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'][hand]} of the other ${rev.length - agree} were the handwriting`);
  const AB = rev.filter((a) => a.agent === 'A' && a.author === 'B').length, other2 = rev.length - agree - hand;
  ok(AB > other2 / 2, `most of the other ${other2} were body text moved to other text (${AB})`);
  const finA = adj.filter((a) => a.final === 'A');
  const readW = finA.reduce((s, a) => s + (a.tesseract_read ?? 0), 0);
  const absW = finA.reduce((s, a) => s + (a.tesseract_absent_words ?? 0), 0);
  ok(finA.every((a) => a.reviewed), 'every final body-text call was re-examined by the author');
  ok(absW === 917, `917 words absent from the page's whole layer (${absW})`);
  ok(readW === 1150, `1,150 words of five letters or more read (${readW})`);
  says('It read 1,150 words of five letters or more, and 917 of them appear nowhere');
  const pagesW = new Set(finA.filter((a) => a.tesseract_absent_words > 0).map((a) => a.cand.split('#')[0]));
  ok(pagesW.size === 23, `words found on 23 of the 26 pages (${pagesW.size})`); says('On 23 of the 26 pages');

  if (!quiet) console.log('C. the search-inside probes');
  for (const r of probes.results) {
    for (const [w, hits] of Object.entries(r.probes)) ok(Array.isArray(hits) && hits.length === 0, `${r.item}: ${w} has no hit`);
    if (r.control) for (const [w, hits] of Object.entries(r.control)) ok(Array.isArray(hits) && hits.includes(r.page_index), `${r.item}: control ${w} found on page ${r.page_index}`);
  }

  if (!quiet) console.log('D. data.json against the records');
  ok(data.pages.length === 26, `data.json lists 26 pages (${data.pages.length})`); says('all 26');
  for (const p of data.pages) {
    const r = rows.find((x) => x.id === p.id);
    if (!r || r.A_lines !== p.lines_lost || r.n_lines !== p.text_lines) ok(false, `${p.id} matches its record`);
  }
  ok(true, 'every data.json page matches its census record');
  return { pass, fail };
}

async function live() {
  console.log('E. live, from archive.org');
  let pass = 0, fail = 0;
  const ok = (c, l) => { if (c) { pass++; console.log('  ok   ' + l); } else { fail++; console.log('  FAIL ' + l); } };
  const base = 'https://archive.org/download/coursdarchitectu00blon/';
  const idx = JSON.parse(gunzipSync(Buffer.from(await (await fetch(base + 'coursdarchitectu00blon_hocr_pageindex.json.gz')).arrayBuffer())).toString());
  const [, , s, e] = idx[897];
  const r = await fetch(base + 'coursdarchitectu00blon_hocr.html', { headers: { Range: `bytes=${s}-${e - 1}` } });
  let buf = Buffer.from(await r.arrayBuffer());
  if (r.status === 200) buf = buf.subarray(s, e); // a server that ignores ranges sends the whole file
  const h = buf.toString('utf8');
  ok(/ppageno 897/.test(h), 'got the hOCR for leaf 897');
  const boxes = [...h.matchAll(/class="ocrx_word"[^>]*title="[^"]*?bbox (\d+) (\d+) (\d+) (\d+)[^"]*"[^>]*>([^<]*)</g)]
    .map((m) => ({ y0: +m[2], y1: +m[4], t: m[5] }));
  const dec = (t) => t.replace(/&#x27;|&#39;|&apos;/g, "'").replace(/&amp;/g, '&').trim();
  const over = boxes.filter((b) => b.y1 > 700 && b.y0 < 880 && dec(b.t));
  ok(over.length === 1 && dec(over[0].t) === 'im[', `over image rows 700 to 880 the only word box is the fragment "im[" (${over.map((b) => dec(b.t)).join(' ') || 'none'})`);
  const words = boxes.map((b) => dec(b.t)).join(' ');
  for (const w of ['pourtant', 'ordinairement', 'impair', 'Anciens']) ok(!words.includes(w), `"${w}" is not in the leaf's text`);
  ok(words.includes('Chambor'), '"Chambor" is in the leaf\'s text');
  const i = words.indexOf('contniucs'), j = words.indexOf("n'en faut");
  ok(i >= 0 && j > i && !/pourtant|quatre pouces|demy|Anciens/.test(words.slice(i, j)), 'the layer runs from "contniucs" to "n\'en faut" with none of the three lines between');
  return { pass, fail };
}

const census = JSON.parse(read('census.json')), data = JSON.parse(read('data.json'));
const adj = read('adjudication.jsonl').split('\n').filter(Boolean).map((l) => JSON.parse(l));
const probes = JSON.parse(read('search-inside.json')), html = read('index.html');
let { pass, fail } = checks(census, data, adj, probes, html);
if (LIVE) { const l = await live(); pass += l.pass; fail += l.fail; }
if (MUTATE) {
  console.log('M. mutants: each must make the checks fail');
  const clone = (x) => JSON.parse(JSON.stringify(x));
  const muts = [
    ['one page loses its dropped line', () => { const c = clone(census); const r = c.rows.find((r) => r.A === 1 && r.status === 'ok'); r.A = 0; return [c, data, adj]; }],
    ['one excluded item counted as usable', () => { const c = clone(census); c.rows.find((r) => r.status === 'excluded:restricted').status = 'ok'; return [c, data, adj]; }],
    ['a planted hole silently found', () => { const c = clone(census); const p = c.rows.find((r) => r.status === 'ok' && r.plants.some(([, f]) => !f)).plants.find(([, f]) => !f); p[1] = true; return [c, data, adj]; }],
    ['the author agrees once more', () => { const a = clone(adj); const x = a.find((x) => x.reviewed && x.agent !== x.author); x.author = x.agent; return [census, data, a]; }],
    ['a probe word found after all', () => { const p = clone(probes); p.results[1].probes.Scituate = [1]; return [census, data, adj, p]; }],
  ];
  let red = 0;
  for (const [name, f] of muts) {
    const [c, d, a, p] = f();
    const r = checks(c, d, a, p || probes, html, true);
    console.log(`  ${r.fail > 0 ? 'ok  ' : 'FAIL'} mutant "${name}" -> ${r.fail} failing`);
    if (r.fail > 0) red++; else fail++;
  }
  console.log(`  ${red}/${muts.length} mutants caught`);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
