#!/usr/bin/env node
/**
 * verify-still-in-the-book.mjs — the gate for /strata/still-in-the-book/.
 *
 *   node verify-still-in-the-book.mjs            # check everything that needs no network
 *   node verify-still-in-the-book.mjs --online   # also re-download the current ICD-10-CM
 *                                                # release and look the word up again
 *
 * What it checks, in the order it matters:
 *
 *  1. THE PAGE AGAINST ITS DATA. Every figure printed in the prose of
 *     public/strata/still-in-the-book/index.html and in the stratum markdown has
 *     to be present in data.js, which is generated from the research artifacts.
 *     A number that drifts in the prose fails here.
 *  2. THE DATA AGAINST ITS SOURCES. The army columns must sum to the totals the
 *     page images print. Every ladder annotation must appear in the fetched text
 *     of the document it annotates. Every entry quoted from a dictionary must
 *     still be a substring of the scan it was cut from, when the scan is on disk.
 *  3. THE ABSENCES. The claim that a word is missing from an official
 *     nomenclature is only as good as the scan, so every volume reported as
 *     having no entry must also carry legible control vocabulary.
 *
 * The scans themselves are not in the repository (they are ~245 MB and
 * re-fetchable); when they are absent the entry re-cut is reported as skipped
 * rather than passed, which is the distinction that matters.
 */
import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';

const ROOT = dirname(fileURLToPath(import.meta.url));
const PAGE = join(ROOT, 'public', 'strata', 'still-in-the-book', 'index.html');
const DATAJS = join(ROOT, 'public', 'strata', 'still-in-the-book', 'data.js');
const MD = join(ROOT, 'src', 'content', 'strata', 'still-in-the-book.md');
const RESEARCH = join(ROOT, 'research', 'nostalgia');
const TEXTS = join(RESEARCH, 'cache', 'texts');

let failures = 0;
let checks = 0;
let skipped = 0;
const ok = (msg) => { checks++; process.stdout.write(`  ok    ${msg}\n`); };
const bad = (msg) => { checks++; failures++; process.stdout.write(`  FAIL  ${msg}\n`); };
const skip = (msg) => { skipped++; process.stdout.write(`  skip  ${msg}\n`); };
const section = (t) => process.stdout.write(`\n${t}\n`);
const assert = (cond, msg) => (cond ? ok(msg) : bad(msg));

const html = readFileSync(PAGE, 'utf8');
const md = readFileSync(MD, 'utf8');
const both = `${html}\n${md}`;
const D = JSON.parse(readFileSync(DATAJS, 'utf8').replace(/^window\.NOS=/, '').replace(/;\s*$/, ''));
const read = (f) => JSON.parse(readFileSync(join(RESEARCH, 'data', f), 'utf8'));

/* Numbers are quoted in the prose with thousands separators; look for both. */
const printed = (n) => {
  const plain = String(n);
  const grouped = Number(n).toLocaleString('en-GB');
  return both.includes(plain) || both.includes(grouped);
};

section('1 · the page against its data');

assert(D.shelf.length === 49 && printed(49), `the shelf is ${D.shelf.length} volumes and the page says so`);
const kinds = { lexicon: 0, psychiatric: 0, nomenclature: 0, army: 0 };
for (const v of D.shelf) kinds[v.kind] = (kinds[v.kind] || 0) + 1;
assert(printed(kinds.lexicon) && printed(kinds.nomenclature),
  `the composition is quoted: ${kinds.lexicon} lexicons, ${kinds.nomenclature} nomenclatures`);

const years = D.shelf.map((v) => v.year).filter(Boolean);
const y0 = Math.min(...years);
const y1 = Math.max(...years);
assert(both.includes(String(y0)) && both.includes(String(y1)), `the span ${y0} to ${y1} is quoted`);

/* the army */
const A = D.army;
assert(printed(A.white.printedCases) && printed(A.white.printedDeaths),
  `white troops: ${A.white.printedCases} cases and ${A.white.printedDeaths} deaths are on the page`);
assert(printed(A.colored.printedCases) && printed(A.colored.printedDeaths),
  `colored troops: ${A.colored.printedCases} cases and ${A.colored.printedDeaths} deaths are on the page`);
assert(printed(A.totalCases) && printed(A.totalDeaths),
  `the two tables add to ${A.totalCases} cases and ${A.totalDeaths} deaths, and the page prints both`);

/* the ladder */
/* The ladder is rendered from data, so only its endpoints and its shape are
   asserted in the prose — and the prose states both in words, which is exactly
   the kind of sentence that rots when the data changes underneath it. */
const first = D.rungs[0].year;
const last = D.rungs[D.rungs.length - 1].year;
const span = last - first;
assert(both.includes(String(first)), `the ladder's first rung (${first}) is named in the prose`);
assert(both.includes(String(last)) || both.includes('F43.20'), `the ladder's last rung (${last}) is named in the prose`);
const WORDS = { 7: 'seven', 127: 'A hundred and twenty-seven' };
assert(html.includes(WORDS[D.rungs.length] || '\u0000'),
  `the prose says the ladder has ${D.rungs.length} rungs, in words`);
assert(html.includes(WORDS[span] || '\u0000'),
  `the prose says the ladder spans ${span} years, in words`);
assert(both.includes('F43.20'), 'the current code F43.20 is on the page');
assert(both.includes('adjustment disorder') || both.includes('Adjustment disorder'),
  'the current rubric, adjustment disorder unspecified, is on the page');
for (const code of ['F98.8', 'F45.21', 'F45.22', 'Q13.2']) {
  assert(html.includes(code), `the neighbouring code ${code} is shown, so the reader can find the line themselves`);
}

/* the crossings */
const C = D.registers.crossings['sentimental over medical'];
assert(printed(C.w1) && printed(C.w5) && printed(C.w9),
  `all three crossing dates are printed, not just the convenient one (${C.w1}, ${C.w5}, ${C.w9})`);
assert(both.includes(`${C.decade}s`), `the decade the page actually claims (${C.decade}s) is stated`);
assert(printed(D.registers.probes.length), `the probe count (${D.registers.probes.length}) is stated`);
for (const e of D.registers.empty) {
  assert(html.includes(e), `the probe that returned nothing is named on the page: "${e}"`);
}

/* newspapers */
const n0 = Math.round(D.news.perMillion[D.news.decades.indexOf(1810)]);
const n1 = Math.round(D.news.perMillion[D.news.decades.indexOf(1960)]);
assert(printed(n0), `the first newspaper rate (${n0} per million, 1810s) is quoted`);
assert(printed(n1), `the last newspaper rate (${n1} per million, 1960s) is quoted`);

/* the four filings */
for (const f of D.nosologies.filings) {
  assert(D.nosologies.filings.length === 4, `four filings were found in one volume`);
  break;
}
assert(both.includes('four'), 'the page states the number of rival filings in words');

/* the synonym cloud */
const maxRefs = Math.max(...D.shelf.map((v) => (v.crossRefs || []).length));
assert(both.includes('eight') && maxRefs === 8,
  `the largest set of headwords redirecting to nostalgia is ${maxRefs}, and the page says eight`);

section('2 · the data against its sources');

/* the army arithmetic, redone here rather than trusted */
for (const which of ['white', 'colored']) {
  const t = A[which];
  const c = t.cases.reduce((a, b) => a + b, 0);
  const d = t.deaths.reduce((a, b) => a + b, 0);
  assert(c === t.printedCases, `${which}: year columns sum to ${c}, the page image prints ${t.printedCases}`);
  assert(d === t.printedDeaths, `${which}: death columns sum to ${d}, the page image prints ${t.printedDeaths}`);
}
assert(A.totalCases === A.white.printedCases + A.colored.printedCases
  && A.totalDeaths === A.white.printedDeaths + A.colored.printedDeaths,
'the combined totals are the sum of the two printed totals and nothing else');

/* every ladder annotation must be in the document it annotates */
const ladder = read('ladder.json');
for (const rung of ladder) {
  const r = D.rungs.find((x) => x.year === rung.year);
  assert(!!r && !rung.error, `rung ${rung.year} fetched cleanly`);
  const hay = rung.hits.map((h) => h.context).join('  ').replace(/\s+/g, ' ');
  assert(hay.replace(/\s+/g, ' ').includes(r.quote.slice(0, 80).replace(/\s+/g, ' ')),
    `rung ${rung.year}: the quotation shown on the page is a slice of the fetched document`);
  assert(/^[0-9a-f]{64}$/.test(rung.sha256), `rung ${rung.year} carries a sha256 of what was fetched`);
}

/* every quoted dictionary entry must still be a substring of its own scan */
const normalise = (s) => s.replace(/([A-Za-z])[-¬]\s*\n\s*([a-z])/g, '$1$2').replace(/\s+/g, ' ');
let recut = 0;
for (const v of D.shelf) {
  if (v.status !== 'cut') continue;
  const p = join(TEXTS, `${v.id}.txt`);
  if (!existsSync(p)) continue;
  const raw = readFileSync(p);
  const sha = createHash('sha256').update(raw).digest('hex');
  if (sha !== v.sha256) { bad(`${v.id}: the scan on disk is not the one the entry was cut from`); continue; }
  const body = normalise(raw.toString('utf8'));
  if (!body.includes(v.ocr)) { bad(`${v.id}: the quoted entry is no longer a substring of its scan`); continue; }
  recut++;
}
if (recut) ok(`${recut} quoted entries re-cut from their own scans and matched byte for byte`);
else skip('the scans are not on disk (245 MB, gitignored); re-run research/nostalgia/dictionaries.mjs to re-check the quotations');

section('3 · the absences');

const absent = D.shelf.filter((v) => v.status === 'absent');
assert(absent.length === 12, `${absent.length} volumes contain no occurrence of the word at all`);
for (const v of absent) {
  const total = Object.values(v.control || {}).reduce((a, b) => a + b, 0);
  assert(total > 30,
    `${v.year} ${v.work.slice(0, 44)}: ${total} control terms legible, so the zero is the book's`);
}
const rcp = absent.filter((v) => /Royal College/.test(v.work));
const rcpYears = [...new Set(rcp.map((v) => v.year))].sort();
assert(rcpYears.length === 6 && both.includes('six'),
  `the Royal College nomenclature is absent in ${rcpYears.length} distinct editions (${rcpYears.join(', ')})`);

section('4 · the current code book');

if (process.argv.includes('--online')) {
  const url = 'https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10CM/2026/icd10cm-table%20and%20index-2026.zip';
  const tmp = join(RESEARCH, 'cache', 'class', 'icd10cm-2026.zip');
  if (!existsSync(tmp)) {
    const res = await fetch(url);
    if (!res.ok) { bad(`could not download the ICD-10-CM release: HTTP ${res.status}`); }
    else {
      const { writeFileSync, mkdirSync } = await import('node:fs');
      mkdirSync(dirname(tmp), { recursive: true });
      writeFileSync(tmp, Buffer.from(await res.arrayBuffer()));
    }
  }
  if (existsSync(tmp)) {
    const xml = execFileSync('unzip', ['-p', tmp, 'icd10cm-index-2026.xml'], { maxBuffer: 1 << 30 }).toString('utf8');
    const m = /<mainTerm>\s*<title>Nostalgia<\/title>\s*<code>([^<]+)<\/code>/.exec(xml);
    assert(!!m, 'the word is a main term in the current index');
    if (m) assert(m[1] === 'F43.20', `the current code is ${m[1]}, and the page says F43.20`);
  }
} else {
  const rung = ladder.find((r) => r.year === 2026);
  assert(!!rung && rung.found, 'the 2026 rung records that the word was found in the release that was fetched');
  assert(/^[0-9a-f]{64}$/.test(rung.sha256),
    `the release is pinned: sha256 ${rung.sha256.slice(0, 24)}…  (pass --online to download it again and look the word up live)`);
}

process.stdout.write(`\n${failures ? 'FAILED' : 'PASS'} — ${checks - failures}/${checks} checks passed`
  + (skipped ? `, ${skipped} skipped` : '') + '\n');
process.exit(failures ? 1 : 0);
