#!/usr/bin/env node
/* LITTLE MORE THAN A COMPILER — offline verifier.
 *
 * The page (public/strata/little-more-than-a-compiler/) makes one central quantitative claim
 * about a physical object: that roughly a quarter of the 1927 Oxford volume called
 * "The Tibetan Book of the Dead" is the translated Tibetan text. Everything else on the page
 * is either that claim's apparatus or a verbatim quotation from the volume.
 *
 * This file recomputes every figure the page can print, offline, with no browser, from the
 * files the page ships, and fails if any of them moves. Where the page prints a number in
 * WORDS in its prose ("seventy-six times", "twenty-seven times", "about a quarter"), the
 * prose is checked against the recomputed figure, so a corpus that changes without the prose
 * changing goes red.
 *
 *   A · The corpus re-derives from the scan. With the 8.4 MB source XML cached, the whole
 *       partition is rebuilt from scratch and must reproduce corpus.json exactly.
 *   B · The division table is the book's, not ours: re-derived from the running head the
 *       1927 compositor printed at the top of each page, with zero conflicts required.
 *   C · The headline figure, under all three partitions, and the internal arithmetic.
 *   D · The concordance: the eighteen Western words absent from the translated text, the
 *       vocabulary that is present only there, and the negative controls that make the
 *       search demonstrably capable of returning a non-zero answer.
 *   E · The brackets, the single occurrence of the book's title inside its own text, and
 *       the hand-transcribed passages checked back against the machine-read page.
 *   F · The three signed notes, with a planted fourth that the same code path must find.
 *   G · The plates exist, are referenced, and their per-page tallies match the corpus.
 *   H · The honesty disciplines the page commits to are on the page rather than in here.
 *   I · The machine reading measured against an independent HUMAN transcription of a second
 *       scanned copy, with the bias test the headline ratio needed, and two differential
 *       controls on the wikitext stripper in both directions it can be wrong.
 *
 * NEGATIVE CONTROL ON THE WHOLE FILE: empty any shipped file of this layer and this goes red.
 *
 * Run: node research/little-more-than-a-compiler/verify.mjs
 */

import { readFileSync, existsSync, statSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

import {
  parseLeaves, jointSplit, splitByFeature, divisionOf, checkDivisions, repairPageNumbers,
  DIVISIONS, H_THRESHOLD, LEAD_THRESHOLD, IA_ITEM,
} from './build-corpus.mjs'
import { searchAll, search, findInLine, bracketMask, bracketLoad } from '../../public/strata/little-more-than-a-compiler/concordance.js'
import { stripWikitext, tokens as wsTokens, bagCompare, pageQuality, WS_OFFSET } from './two-scans.mjs'

const __dir = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.join(__dir, '..', '..')
const PAGE_DIR = path.join(ROOT, 'public', 'strata', 'little-more-than-a-compiler')
const PAGE = readFileSync(path.join(PAGE_DIR, 'index.html'), 'utf8')
const CORPUS = JSON.parse(readFileSync(path.join(PAGE_DIR, 'corpus.json'), 'utf8'))
const NUMBERS = JSON.parse(readFileSync(path.join(__dir, 'numbers.json'), 'utf8'))
const DATA_SRC = readFileSync(path.join(PAGE_DIR, 'data.js'), 'utf8')
const INSTRUMENT_SRC = readFileSync(path.join(PAGE_DIR, 'instrument.js'), 'utf8')
const DATA = await import('../../public/strata/little-more-than-a-compiler/data.js')

let pass = 0, fail = 0
const ok = m => { pass++; console.log('  \x1b[32m✓\x1b[0m ' + m) }
const bad = m => { fail++; console.log('  \x1b[31m✗ ' + m + '\x1b[0m') }
const eq = (got, want, label) => got === want
  ? ok(`${label} = ${JSON.stringify(got)}`)
  : bad(`${label}: expected ${JSON.stringify(want)}, got ${JSON.stringify(got)}`)
const between = (got, lo, hi, label) => (got >= lo && got <= hi)
  ? ok(`${label} = ${typeof got === 'number' ? got.toFixed(2) : got} (within ${lo}–${hi})`)
  : bad(`${label}: ${got} is outside ${lo}–${hi}`)
const flat = s => String(s).replace(/\s+/g, ' ')
const inPage = (needle, label) => flat(PAGE).includes(flat(needle))
  ? ok(label)
  : bad(label + ' — NOT ON THE PAGE: «' + String(needle).slice(0, 76) + '»')
const inData = (needle, label) => flat(DATA_SRC).includes(flat(needle))
  ? ok(label)
  : bad(label + ' — NOT IN data.js: «' + String(needle).slice(0, 76) + '»')

const C = CORPUS.counts.splitJ
const TOTAL = Object.values(C).reduce((a, b) => a + b, 0)
const share = k => 100 * CORPUS.counts[k].translation / TOTAL

/* ============================================================ A · re-derive from the scan */

console.log('\nA · the corpus re-derives from the Internet Archive scan')

const XML_PATH = path.join(__dir, '.cache', 'djvu.xml')
if (!existsSync(XML_PATH)) {
  console.log(`  \x1b[33m•\x1b[0m source XML not cached; run "node ${path.relative(ROOT, path.join(__dir, 'build-corpus.mjs'))}" to fetch it.`)
  console.log('    Sections B onward check the shipped corpus against itself and against the page.')
} else {
  const leaves = parseLeaves(readFileSync(XML_PATH, 'utf8'))
  eq(leaves.length, 300, 'leaves parsed from the scan')

  // Recount from scratch, exactly as build-corpus.mjs does, and require an exact match.
  const { pages } = repairPageNumbers(leaves)
  const recount = { translation: 0, notesOnTranslation: 0, editorProse: 0, woodroffe: 0, apparatus: 0 }
  for (const lf of leaves) {
    const body = lf.lines.slice(1)
    const k = jointSplit(body)
    const div = divisionOf(lf.leaf)
    body.forEach((l, i) => {
      const isBody = i < k
      if (div.voice === 'KDS') recount[isBody ? 'translation' : 'notesOnTranslation'] += l.nw
      else if (div.voice === 'EW') recount.editorProse += l.nw
      else if (div.voice === 'JW') recount.woodroffe += l.nw
      else recount.apparatus += l.nw
    })
  }
  for (const key of Object.keys(recount)) eq(recount[key], C[key], `re-derived word count, ${key}`)

  // The two thresholds sit in a valley, not on a slope. Re-derive the histogram and check
  // that both are in a genuinely sparse region, so a small change to either would not move
  // the answer. This is what makes them a reading of the type rather than a tuned parameter.
  const heights = [], leads = []
  for (const lf of leaves) {
    const body = lf.lines.slice(1)
    for (const l of body) {
      heights.push(l.h)
      if (l.lead != null && l.lead > 20 && l.lead < 100) leads.push(l.lead)
    }
  }
  const density = (arr, at, w) => arr.filter(v => v >= at - w && v <= at + w).length / arr.length
  const hValley = density(heights, H_THRESHOLD, 1)
  const hPeakLo = density(heights, 29, 1), hPeakHi = density(heights, 38, 1)
  ;(hValley < hPeakLo / 3 && hValley < hPeakHi / 3)
    ? ok(`the type-height threshold ${H_THRESHOLD} sits in a valley (${(100 * hValley).toFixed(2)}% of lines, against ${(100 * hPeakLo).toFixed(1)}% and ${(100 * hPeakHi).toFixed(1)}% at the two modes)`)
    : bad(`the type-height threshold ${H_THRESHOLD} is not in a valley: ${hValley} vs ${hPeakLo}/${hPeakHi}`)
  const lValley = density(leads, LEAD_THRESHOLD, 1)
  const lPeakLo = density(leads, 48, 1), lPeakHi = density(leads, 64, 1)
  ;(lValley < lPeakLo / 3 && lValley < lPeakHi / 3)
    ? ok(`the line-pitch threshold ${LEAD_THRESHOLD} sits in a valley (${(100 * lValley).toFixed(2)}%, against ${(100 * lPeakLo).toFixed(1)}% and ${(100 * lPeakHi).toFixed(1)}%)`)
    : bad(`the line-pitch threshold ${LEAD_THRESHOLD} is not in a valley: ${lValley} vs ${lPeakLo}/${lPeakHi}`)

  /* ------------------------------------------- B · the division table is the book's own */

  console.log('\nB · the divisions come from the running heads, not from us')

  const dc = checkDivisions(leaves)
  eq(dc.conflicts.length, 0, 'running heads that contradict the division table')
  ;(dc.agreed >= 100)
    ? ok(`running heads that positively name their own division: ${dc.agreed}`)
    : bad(`only ${dc.agreed} running heads name a division; expected at least 100`)

  // NEGATIVE CONTROL. Move one division boundary by ten leaves and the same checker must
  // find conflicts. A checker that cannot go red is not a check.
  const saved = DIVISIONS.map(d => ({ ...d }))
  const introIdx = DIVISIONS.findIndex(d => d.id === 'introduction')
  const bookIdx = DIVISIONS.findIndex(d => d.id === 'book1')
  DIVISIONS[introIdx].to += 12
  DIVISIONS[bookIdx].from += 12
  const doctored = checkDivisions(leaves)
  DIVISIONS[introIdx].to = saved[introIdx].to
  DIVISIONS[bookIdx].from = saved[bookIdx].from
  ;(doctored.conflicts.length > 0)
    ? ok(`negative control: shifting the Introduction/Book I boundary by twelve leaves produces ${doctored.conflicts.length} head conflicts`)
    : bad('negative control FAILED: the running-head check passed a deliberately wrong division table')
  eq(checkDivisions(leaves).conflicts.length, 0, 'the division table is restored and clean again')

  // the printed page ranges each division spans, re-derived
  const range = id => {
    const d = DIVISIONS.find(x => x.id === id)
    const ps = []
    for (let leaf = d.from; leaf <= d.to; leaf++) if (pages.has(leaf)) ps.push(pages.get(leaf))
    return ps.length ? [Math.min(...ps), Math.max(...ps)] : null
  }
  for (const [id, want] of [['introduction', [1, 81]], ['book1', [85, 152]], ['book2', [155, 196]],
    ['appendices', [197, 209]], ['addenda', [211, 241]]]) {
    const got = range(id)
    eq(got && got.join('-'), want.join('-'), `printed page range of ${id}`)
  }
}

/* ================================================================== C · the headline figure */

console.log('\nC · the headline figure and the arithmetic behind it')

eq(TOTAL, 106291, 'total words the scanner read in the volume')
eq(C.translation, 28316, 'words of translated text')
between(share('splitJ'), 26, 28, 'translation share, the partition the page reports')
between(share('splitH'), 26, 28, 'translation share, type size alone')
between(share('splitL'), 26, 29, 'translation share, line pitch alone')

const spread = ['splitH', 'splitL', 'splitJ'].map(share)
;(Math.max(...spread) - Math.min(...spread) < 1.5)
  ? ok(`the three partitions agree to within ${(Math.max(...spread) - Math.min(...spread)).toFixed(2)} percentage points`)
  : bad(`the three partitions differ by ${(Math.max(...spread) - Math.min(...spread)).toFixed(2)} points, too much to call it "about a quarter"`)

// The page says, in prose, "about a quarter". Check that against the number.
between(share('splitJ'), 22.5, 29.9, 'the prose claim "about a quarter" against the computed share')
inPage('about a quarter', 'the page says "about a quarter" and the arithmetic supports it')

// "About half the printed pages carry translated text" — the other half of the finding.
const transPages = CORPUS.divisions
  .filter(d => ['book1', 'book2', 'appendices'].includes(d.id))
  .reduce((a, d) => a + d.pageCount, 0)
eq(transPages, 123, 'printed pages carrying any translated text')
between(100 * transPages / 248, 45, 55, 'those pages as a share of the volume\'s 248 arabic pages')
inPage('it looks about half translation. Weigh the ink and it is about a quarter',
  'the page states the page-extent/word-count contrast that is the finding')

// "roughly two-fifths of the words on those very pages are the editor's footnotes"
const onTransPages = CORPUS.divisions
  .filter(d => ['book1', 'book2', 'appendices'].includes(d.id))
  .reduce((a, d) => ({ text: a.text + d.bodyWords, note: a.note + d.noteWords }), { text: 0, note: 0 })
const noteShare = 100 * onTransPages.note / (onTransPages.text + onTransPages.note)
between(noteShare, 36, 44, 'note share of the words on the translated pages (the page says two-fifths)')

// internal consistency: the division table must add up to the counts
const sumDiv = CORPUS.divisions.reduce((a, d) => a + d.bodyWords + d.noteWords, 0)
eq(sumDiv, TOTAL, 'the per-division table sums to the total')

// the split-agreement figure the page prints
const sa = CORPUS.splitAgreement
between(100 * sa.linesDiffer / sa.linesConsidered, 0, 4,
  'lines the two independent signals assign differently, per cent')
;(flat(INSTRUMENT_SRC).includes('Almost all of those are a single line'))
  ? ok('the page characterises the disagreement honestly')
  : bad('the page does not characterise the split disagreement')

/* ============================================================== D · the vocabulary partition */

console.log('\nD · the concordance, and four negative controls')

// The twenty words of the Western frame that the page says occur nowhere in the translated
// text. Each must be ABSENT there and PRESENT in the apparatus: an absence with nothing to
// contrast it against would be satisfied by a broken search.
const ABSENT = ['Egypt', 'Egyptian', 'Osiris', 'Plato', 'Pythagoras', 'Gnostic', 'Purgatory',
  'Christian', 'Christianity', 'Bible', 'Theosophy', 'Blavatsky', 'Celtic', 'Occidental',
  'Europe', 'America', 'evolution', 'science']
let absentOk = 0
for (const w of ABSENT) {
  const r = searchAll(CORPUS.corpora, w, { whole: true })
  const elsewhere = r.notesOnTranslation.hits + r.editorProse.hits + r.woodroffe.hits
  if (r.translation.hits === 0 && elsewhere > 0) absentOk++
  else bad(`"${w}": ${r.translation.hits} in the translated text, ${elsewhere} elsewhere — the page's claim does not hold`)
}
eq(absentOk, ABSENT.length, 'words of the Western frame absent from the translated text and present in the apparatus')
inPage('Every one of them occurs in the apparatus. Not one of them occurs in the translated text',
  'the page states the partition it computes')

// The reverse direction, with the exact figures the page prints in words.
const nobly = searchAll(CORPUS.corpora, 'O nobly-born', { whole: true })
eq(nobly.translation.hits, 76, '"O nobly-born" in the translated text')
eq(nobly.editorProse.hits, 0, '"O nobly-born" in the editor\'s own prose')
inPage('appears seventy-six times in the translation and never once in the editor', 'the page prints those two figures in words')

const thou = searchAll(CORPUS.corpora, 'thou', { whole: true })
eq(thou.translation.hits, 269, '"thou" in the translated text')
eq(thou.editorProse.hits, 1, '"thou" in the editor\'s own prose')
inPage('appears 269 times against one', 'the page prints those two figures')

const egyptian = searchAll(CORPUS.corpora, 'Egyptian', { whole: true })
const egyptianTotal = Object.values(egyptian).reduce((a, r) => a + r.hits, 0)
eq(egyptianTotal, 27, '"Egyptian" in the whole volume')
eq(egyptian.translation.hits, 0, '"Egyptian" in the translated text')
inData('the word Egyptian occurs twenty-seven times in the volume', 'the claim audit prints that figure in words')
;(/twenty-six times/.test(DATA_SRC))
  ? bad('the claim audit still says "twenty-six times"; the recomputed figure is 27')
  : ok('no stale "twenty-six times" left in the claim audit')

// --- NEGATIVE CONTROL 1. The substring/whole-word distinction the page invites the reader
// to break must actually break in the way the page says it does.
const hadesWhole = search(CORPUS.corpora.translation, 'Hades', { whole: true })
const hadesLoose = search(CORPUS.corpora.translation, 'Hades', { whole: false })
eq(hadesWhole.hits, 0, 'negative control: "Hades" as a whole word in the translated text')
;(hadesLoose.hits > 0)
  ? ok(`negative control: "Hades" as a substring finds ${hadesLoose.hits} hit(s) in the translated text, exactly as the page warns`)
  : bad('negative control FAILED: the page claims a substring search finds "Hades" in the translated text, and it does not')
inPage('search <span class="mono">Hades</span>', 'the page names that control and invites the reader to run it')

const evoLoose = search(CORPUS.corpora.translation, 'evolution', { whole: false })
;(evoLoose.hits > 0)
  ? ok(`negative control: "evolution" as a substring finds ${evoLoose.hits} hit(s) (revolution) in the translated text`)
  : bad('negative control FAILED: "evolution" as a substring should match "revolution"')

// --- NEGATIVE CONTROL 2. A planted line. The absence results above are only worth having if
// the same unmodified search would find the word had it been there. Doctor the DATA, never
// the code or the result list: the planted line enters the real corpus and must be found by
// the same call.
const planted = CORPUS.corpora.translation.concat([
  { p: 999, d: 'book1', t: 'and the Egyptian Book of the Dead, as Plato and Pythagoras also taught in Europe,' },
])
const withPlant = search(planted, 'Egyptian', { whole: true })
eq(withPlant.hits, 1, 'negative control: a planted line puts "Egyptian" into the translated corpus and the same search finds it')
const withPlantPlato = search(planted, 'Plato', { whole: true })
eq(withPlantPlato.hits, 1, 'negative control: the same planted line is found searching for "Plato"')
eq(search(CORPUS.corpora.translation, 'Egyptian', { whole: true }).hits, 0,
  'and the undoctored corpus is unchanged afterwards')

// --- NEGATIVE CONTROL 3. Case handling.
eq(search(CORPUS.corpora.translation, 'BARDO', { whole: true, caseSensitive: false }).hits,
   search(CORPUS.corpora.translation, 'Bardo', { whole: true, caseSensitive: false }).hits,
   'negative control: the case-insensitive search is genuinely case-insensitive')
;(search(CORPUS.corpora.translation, 'BARDO', { whole: true, caseSensitive: true }).hits <
  search(CORPUS.corpora.translation, 'Bardo', { whole: true, caseSensitive: true }).hits)
  ? ok('negative control: the case-sensitive search genuinely distinguishes case')
  : bad('negative control FAILED: case sensitivity has no effect')

/* ======================================================================== E · the brackets */

console.log('\nE · the brackets, and the title inside its own text')

const bl = bracketLoad(CORPUS.corpora.translation)
eq(bl.total, C.translation, 'bracket census covers every word of the translated text')
between(100 * bl.share, 5, 7, 'share of the translated text inside the volume\'s square brackets')
;(bl.spans > 500) ? ok(`bracketed spans in the translated text: ${bl.spans}`) : bad(`only ${bl.spans} bracketed spans found`)

const bod = search(CORPUS.corpora.translation, 'Book of the Dead', { whole: true })
eq(bod.hits, 1, '"Book of the Dead" inside the translated text')
eq(bod.bracketed, 1, 'and it is inside the volume\'s square brackets')
eq(bod.lines[0].p, 196, 'and it is on printed page 196')
;(bod.lines[0].t.includes('Here endeth'))
  ? ok(`the single occurrence is: «${bod.lines[0].t.trim()}»`)
  : bad(`the single occurrence is not the expected line: «${bod.lines[0].t.trim()}»`)
inPage('[Here endeth the Tibetan Book of the Dead]', 'the page prints that line verbatim')

// NEGATIVE CONTROL 4. The bracket mask must actually distinguish inside from outside.
const maskTest = 'plain [inside] plain'
const m = bracketMask(maskTest)
;(m[0] === 0 && m[maskTest.indexOf('inside')] === 1 && m[maskTest.length - 1] === 0)
  ? ok('negative control: the bracket mask marks inside and outside differently on a constructed line')
  : bad('negative control FAILED: the bracket mask does not distinguish inside from outside')
eq(findInLine('a [word] here', 'word', { whole: true })[0].bracketed, true,
  'negative control: a hit inside brackets is reported as bracketed')
eq(findInLine('a word here', 'word', { whole: true })[0].bracketed, false,
  'negative control: a hit outside brackets is reported as unbracketed')

// The hand-transcribed passages must still be the same page of the same book. Compare each
// transcription against the independent machine-read text of its printed page: a transcription
// that drifted, or that was quietly improved, loses token overlap and this goes red.
console.log('\n  the hand-transcribed passages, against the machine reading of the same page')
const tokens = s => new Set(String(s).toLowerCase().match(/[a-z]{3,}/g) || [])
for (const psg of DATA.PASSAGES) {
  const pageLines = CORPUS.corpora.translation.filter(r => r.p === psg.page).map(r => r.t).join(' ')
  const a = tokens(psg.paras.join(' ')), b = tokens(pageLines)
  let hit = 0
  for (const t of a) if (b.has(t)) hit++
  const overlap = hit / a.size
  ;(overlap >= 0.9)
    ? ok(`passage ${psg.id}: ${(100 * overlap).toFixed(1)}% of its word types are on the machine reading of page ${psg.page}`)
    : bad(`passage ${psg.id}: only ${(100 * overlap).toFixed(1)}% overlap with page ${psg.page} — the transcription has drifted`)
  ;(psg.paras.some(p => p.includes('[')))
    ? ok(`passage ${psg.id} carries the volume's brackets`)
    : bad(`passage ${psg.id} has no brackets, so it cannot demonstrate the bracket layer`)
}

/* ==================================================================== F · the signed notes */

console.log('\nF · the notes the volume signs back to the translator')

const SIGNATURE = /[—–-]{1,3}\s*L[aā]ma\s+Kazi\s+Dawa[\s-]?Samdup\s*\.?\s*$/
const signed = CORPUS.corpora.notesOnTranslation.filter(r => SIGNATURE.test(r.t.trim()))
eq(signed.length, 3, 'notes in the volume closing with the translator\'s name')
eq(signed.map(s => s.p).join(','), '85,91,119', 'the printed pages they fall on')
eq(CORPUS.signedNotes.count, 3, 'and the shipped corpus records the same count')
inPage('The number of such places, in a volume of roughly nineteen thousand words of annotation on the translated pages, is three',
  'the page states the count, and states what it does and does not mean')
inPage('It does not mean three notes are his and the rest are not',
  'the page refuses the stronger claim the number would support if you did not read the book')

// NEGATIVE CONTROL 5. Plant a fourth. It enters the same corpus and must be found by the
// same unmodified predicate.
const plantedNotes = CORPUS.corpora.notesOnTranslation.concat([
  { p: 998, d: 'book1', t: 'a note that ends in the signature the volume uses.—Lama Kazi Dawa-Samdup.' },
])
eq(plantedNotes.filter(r => SIGNATURE.test(r.t.trim())).length, 4,
  'negative control: a planted fourth signed note is found by the same predicate')

const notesWordCount = CORPUS.corpora.notesOnTranslation.reduce((a, r) => a + r.t.split(/\s+/).filter(Boolean).length, 0)
between(notesWordCount, 18000, 20500, 'words of annotation on the translated pages (the page says roughly nineteen thousand)')

/* ============================================================================ G · the plates */

console.log('\nG · the plates, and their per-page tallies')

for (const pl of CORPUS.plates) {
  const p = path.join(PAGE_DIR, 'plates', pl.file)
  existsSync(p) && statSync(p).size > 40000
    ? ok(`${pl.file} (${Math.round(statSync(p).size / 1024)} KB)`)
    : bad(`${pl.file} missing or suspiciously small`)
}
const p96 = CORPUS.plates.find(p => p.file === 'p96.jpg')
eq(p96.printedPage, 96, 'the hero plate is printed page 96')
eq(p96.bodyLines, 14, 'lines of text type on page 96')
eq(p96.noteLines, 32, 'lines of note type on page 96')
;(/Fourteen lines of the translated text; thirty-two lines/.test(p96.caption))
  ? ok('the caption for page 96 states that tally in words, and it matches')
  : bad('the caption for page 96 does not state the tally it shows: ' + p96.caption)
const p1 = CORPUS.plates.find(p => p.file === 'p1.jpg')
eq(p1.printedPage, 1, 'the second plate is printed page 1')
;(p1.noteLines > p1.bodyLines * 4)
  ? ok(`page 1 really is mostly footnote: ${p1.bodyLines} lines of text against ${p1.noteLines} of note`)
  : bad(`page 1 is not mostly footnote (${p1.bodyLines} vs ${p1.noteLines}), so the page's description of it is wrong`)
;(/gets two lines in, and is taken over by its own first footnote/.test(p1.caption))
  ? ok('the caption for page 1 describes what the tally shows')
  : bad('the caption for page 1 does not describe the tally: ' + p1.caption)

// The seventeen treatises, and the seven the volume says correspond
eq(DATA.TREATISES.length, 17, 'treatises listed in the block-print footnote')
eq(DATA.TREATISES.filter(t => t.inManuscript).length, 7, 'of them the volume says correspond to its manuscript')
eq(DATA.TREATISES.filter(t => t.inManuscript).map(t => t.n).join(','), '1,2,3,4,5,6,8',
  'and they are exactly the ones the volume names')
inData('Herein, the treatises numbered 1, 2, 3, 4, 5, 6, 8 correspond', 'the volume\'s own sentence is quoted verbatim')

// the marker score the page prints, recomputed here from the shipped corpus
const ms = CORPUS.markerScore
const mrate = k => ms[k].opensWithAMark / ms[k].pages
;(mrate('splitJ') > mrate('splitH') && mrate('splitH') > mrate('splitL'))
  ? ok(`the footnote-marker test ranks the partitions joint > height > pitch (${ms.splitJ.opensWithAMark}/${ms.splitJ.pages}, ${ms.splitH.opensWithAMark}/${ms.splitH.pages}, ${ms.splitL.opensWithAMark}/${ms.splitL.pages}), and the reported one wins`)
  : bad(`the footnote-marker test does not prefer the reported partition: ${JSON.stringify(ms)}`)
eq(CORPUS.divisionCheck.conflicts, 0, 'running-head conflicts recorded in the shipped corpus')
eq(CORPUS.divisionCheck.headsAgreeing, 108, 'running heads that name their own division')
;(flat(INSTRUMENT_SRC).includes('only the comparison between'))
  ? ok('the page says the marker test is one-sided rather than presenting it as a pass rate')
  : bad('the page presents the marker test without naming its one-sidedness')

// The translator's name as the volume prints it: the macron is on Lāma, not on Kazi.
// (Title page: "according to Lāma Kazi Dawa-Samdup's English Rendering".)
;(/K\u0101zi/.test(PAGE) || /K\u0101zi/.test(DATA_SRC) || /K\u0101zi/.test(INSTRUMENT_SRC))
  ? bad('the translator\'s name is spelt "Kāzi" somewhere; the 1927 volume prints "Lāma Kazi Dawa-Samdup"')
  : ok('the translator\'s name is spelt as the volume prints it, macron on Lāma only')
;(/L\u0101ma Kazi Dawa-Samdup/.test(DATA_SRC))
  ? ok('and the volume\'s own form appears verbatim in the quotations')
  : bad('the volume\'s form "Lāma Kazi Dawa-Samdup" is not quoted anywhere')

/* ============================================================== H · the honesty disciplines */

console.log('\nH · the honesty disciplines, on the page rather than in this file')

inPage('nobody can now separate Dawa-Samdup', 'the page says the mixture in the apparatus is not separable')
inPage('Anyone who tells you what proportion of the Introduction is his is guessing',
  'and refuses to guess')
inPage('The text is OCR, not a transcription', 'the page names the machine reading as machine reading')
inPage('Word count is one measure of a book and not the only one', 'names the limit of its own measure')
inPage('there is no honest number to report', 'says where it declines to report a number')
inPage('We did not read the Tibetan', 'names the first thing it did not check')
inPage('We did not compare the 1927 English against its Tibetan source',
  'says it is not a judgement about the translation')
inPage('We did not measure the 1957 third edition by word count', 'names the measurement it declined to make')
inPage('We did not survey the literature exhaustively for a prior count',
  'the page names the limit of its own priority search')
inPage('This page claims the measurement and its method, not priority', 'and says so in those words')
// the one published estimate it does set itself beside, verbatim and attributed
inPage('comprise', 'the published estimate is quoted')
inPage('some two thirds of the entire book', 'Lopez\'s figure is quoted verbatim')
inPage('The Immanent Frame, 23 March 2011', 'and attributed to a source a reader can reach')
inPage('It is an estimate with no stated method, and it is about a\n    different object',
  'and the page says why it is not the same measurement')
// the readout that compares them must be computed, not asserted
;(flat(INSTRUMENT_SRC).includes('Two thirds is 66.7%'))
  ? ok('the comparison with the published estimate is computed at load time')
  : bad('the comparison with the published estimate is not computed')
;(/\b73\.4\b/.test(PAGE)) ? bad('the apparatus share is hardcoded in the markup')
  : ok('the apparatus share is not hardcoded in the markup')
between(100 * (TOTAL - C.translation) / TOTAL, 70, 76,
  'apparatus share of the 1927 first edition, against Lopez\'s two thirds for the accreted one')
inPage('of whom I <strong>was</strong> a recognized disciple',
  'the page records the one-word difference in the quoted Preface sentence')
inPage('We checked the first edition only, so we cannot say which text was being quoted',
  'and states the limit of that observation instead of scoring a point with it')
;(/nobody appears to have measured it/.test(PAGE))
  ? bad('the page still implies nobody has measured this; that was never checked')
  : ok('no unchecked novelty claim left in the lede')
// xliv + 248 = 292, the figure the lede uses for the volume's extent
eq(44 + 248, 292, 'the volume\'s extent, roman front matter plus arabic pages')
inPage('292 pages', 'and the lede prints it')
inData('The correction is not a criticism of Evans-Wentz. It is his own text.', 'the claim audit declines the cheap reading')
inData('this page is not an argument for that', 'the claim audit refuses the conclusion the finding invites')

// every command the page prints must run
for (const cmd of ['research/little-more-than-a-compiler/verify.mjs', 'research/little-more-than-a-compiler/build-corpus.mjs']) {
  existsSync(path.join(ROOT, cmd)) ? ok(`the page prints "node ${cmd}" and that file exists`)
    : bad(`the page prints a command that does not run: node ${cmd}`)
}

// the page must actually read the corpus rather than hardcode it
;(INSTRUMENT_SRC.includes("fetch('./corpus.json')"))
  ? ok('the page derives its figures from corpus.json at load time')
  : bad('the page no longer loads corpus.json — its figures may be hardcoded')
;(/\b26\.6\b|\b28,316\b/.test(PAGE))
  ? bad('the headline figure is hardcoded in the markup; it must be computed from the corpus')
  : ok('no headline figure is hardcoded in the markup')

// the source is named, so a reader can go and get it
inPage(IA_ITEM, 'the page names the Internet Archive item it was built from')

/* ========================================= I · the reading measured against a human one */

console.log('\nI · what the machine reading is worth, against an independent transcription')

const TS = JSON.parse(readFileSync(path.join(PAGE_DIR, 'two-scans.json'), 'utf8'))

;(TS.pagesCompared >= 200)
  ? ok(`pages compared against the Wikisource transcription: ${TS.pagesCompared}`)
  : bad(`only ${TS.pagesCompared} pages compared; the measurement is too thin to quote`)
between(100 * TS.overall.agreement, 94, 99, 'overall token agreement with the independent transcription')
eq(TS.overall.myTokens + 0, TS.overall.myTokens, 'token total is a number')
;(TS.overall.myTokens >= 60000)
  ? ok(`tokens behind that figure: ${TS.overall.myTokens}`)
  : bad(`only ${TS.overall.myTokens} tokens behind the agreement figure`)

// THE BIAS TEST, which is the reason the comparison is on the page at all. The headline is a
// ratio, so a uniform error cancels and a biased one does not.
between(100 * TS.onTranslated.agreement, 94, 99, 'agreement on pages of translated text')
between(100 * TS.onEditor.agreement, 94, 99, "agreement on pages of the editor's prose")
;(Math.abs(100 * TS.bias) < 0.5)
  ? ok(`the two sides of the division are read ${Math.abs(100 * TS.bias).toFixed(2)} points apart, so the error cancels out of the ratio`)
  : bad(`the two sides are read ${(100 * TS.bias).toFixed(2)} points apart, which is large enough to move the headline ratio`)
;(TS.onDisplay.agreement < TS.onTranslated.agreement)
  ? ok('display pages (contents, half-titles) are read worst, as the page says')
  : bad('the page claims display pages are read worst and they are not')

// The negative result must stay on the page: the plan died and the death is the useful part.
eq(TS.unproofreadPagesAreMachineText, false,
  'the data records that Wikisource\'s unproofread pages are NOT machine text')
inPage('Wikisource', 'the page names the source of the independent transcription')
inPage('turns out to be a review state rather than a text state', 'and records why the two-machine comparison does not exist')

// The page must compute these rather than hold them
;(INSTRUMENT_SRC.includes("fetch('./two-scans.json')"))
  ? ok('the page reads the comparison from two-scans.json at load time')
  : bad('the page no longer loads two-scans.json')
;(/\b96\.33\b|\b96\.51\b/.test(PAGE))
  ? bad('the agreement figures are hardcoded in the markup')
  : ok('no agreement figure is hardcoded in the markup')

// The offset between the two scans, re-derived by content rather than trusted.
eq(WS_OFFSET, 6, 'the offset from Archive leaf to Wikisource page number')
;(/recall of the machine/i.test(TS.method))
  ? ok('the shipped method note says the measure is recall, not a symmetric error rate')
  : bad('the method note does not state that the measure is one-sided')
between(100 * TS.overall.missedByMachine / TS.overall.theirTokens, 0, 8,
  'words the human transcribed that the machine did not read, as a share of theirs')

/* --- the wikitext stripper, with a differential control ---
 * The measured agreement depends entirely on reading Wikisource's markup back to plain words.
 * A stripper that leaked template names or swallowed real text would report a disagreement that
 * is ours, not the scanner's. Two controls: a constructed page whose printed text is known, and
 * a deliberately BROKEN stripper that must score worse on the real pages than the real one does.
 */
const WS_CACHE = path.join(__dir, '.cache', 'wikisource-pages.json')
{
  const sample = "<noinclude><pagequality level=\"3\" user=\"x\" /></noinclude>{{c|{{larger|{{uc|Introduction}}}}}}<ref name=p1>This Introduction is based upon ''explanatory'' notes.</ref> [[Author:Foo|Bar]] {{nsl2|p. 80|#80}}"
  const got = wsTokens(stripWikitext(sample)).sort().join(' ')
  const want = ['introduction', 'this', 'introduction', 'based', 'upon', 'explanatory', 'notes', 'bar'].sort().join(' ')
  eq(got, want, 'the stripper returns exactly the printed words of a constructed page')
  ;(!/larger|noinclude|pagequality|nsl|author/i.test(stripWikitext(sample)))
    ? ok('and leaks no template name, tag name or link target')
    : bad('the stripper leaks markup into the text: ' + stripWikitext(sample).slice(0, 120))
}

if (!existsSync(WS_CACHE)) {
  console.log('  \x1b[33m•\x1b[0m Wikisource pages not cached; run two-scans.mjs to fetch them for the differential control.')
} else if (!existsSync(XML_PATH)) {
  console.log('  \x1b[33m•\x1b[0m source XML not cached; skipping the differential control.')
} else {
  const ws = JSON.parse(readFileSync(WS_CACHE, 'utf8'))
  const leaves = parseLeaves(readFileSync(XML_PATH, 'utf8'))
  // TWO differential controls, in the two directions a stripper can be wrong.
  //
  // (1) OVER-DELETION is the direction that can corrupt the number. The agreement figure is
  //     RECALL of the machine's tokens, so a stripper that swallows real printed words shrinks
  //     the human side and drives agreement down. A stripper that drops whole template
  //     CONTENTS rather than just template names does exactly that, and must score worse.
  // (2) LEAKAGE cannot corrupt the number, and the control proves it rather than assuming it:
  //     a stripper that leaves template names in adds junk to the human side, which a recall
  //     measure ignores. That is a real property of the metric and it is stated on the page,
  //     so it is asserted here rather than left as folklore.
  const overDeleting = raw => raw
    .replace(/<noinclude>[\s\S]*?<\/noinclude>/g, ' ')
    .replace(/\{\{[^{}]*\}\}/g, ' ')       // whole template, contents and all
    .replace(/<[^>]+>/g, ' ')
    .replace(/[\[\]|']/g, ' ')
  const leaking = raw => raw
    .replace(/<noinclude>[\s\S]*?<\/noinclude>/g, ' ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/[{}[\]|']/g, ' ')            // braces gone, template NAMES left behind
  let realShared = 0, cutShared = 0, leakShared = 0, mineTotal = 0
  let realTheirs = 0, leakTheirs = 0, n = 0
  for (const lf of leaves) {
    const e = ws[lf.leaf + WS_OFFSET]
    if (!e || !e.exists) continue
    const mine = wsTokens(lf.lines.map(l => l.t).join(' '))
    if (mine.length < 40) continue
    const good = wsTokens(stripWikitext(e.raw))
    if (good.length < 40) continue
    const cut = wsTokens(overDeleting(e.raw))
    const leak = wsTokens(leaking(e.raw))
    n++
    mineTotal += mine.length
    realShared += bagCompare(mine, good).shared
    cutShared += bagCompare(mine, cut).shared
    leakShared += bagCompare(mine, leak).shared
    realTheirs += good.length
    leakTheirs += leak.length
  }
  const realAg = realShared / mineTotal, cutAg = cutShared / mineTotal, leakAg = leakShared / mineTotal
  ;(Math.abs(100 * realAg - 100 * TS.overall.agreement) < 0.05)
    ? ok(`the shipped agreement figure re-derives from the cache over ${n} pages: ${(100 * realAg).toFixed(2)}%`)
    : bad(`re-derived agreement ${(100 * realAg).toFixed(2)}% does not match the shipped ${(100 * TS.overall.agreement).toFixed(2)}%`)
  ;(realAg - cutAg > 0.01)
    ? ok(`control 1: a stripper that swallows template contents scores ${(100 * cutAg).toFixed(2)}% against the real one at ${(100 * realAg).toFixed(2)}%, so the measure does detect a stripper that eats printed words`)
    : bad(`control 1 FAILED: an over-deleting stripper scores ${(100 * cutAg).toFixed(2)}%, indistinguishable from the real ${(100 * realAg).toFixed(2)}%`)
  ;(leakTheirs > realTheirs && Math.abs(leakAg - realAg) < 0.005)
    ? ok(`control 2: a leaking stripper adds ${leakTheirs - realTheirs} junk tokens and moves the figure by ${(100 * Math.abs(leakAg - realAg)).toFixed(3)} points, confirming the measure is recall and ignores junk on the human side`)
    : bad(`control 2 FAILED: leakage produced ${leakTheirs - realTheirs} extra tokens and moved the figure ${(100 * Math.abs(leakAg - realAg)).toFixed(3)} points, so the metric is not behaving as the page describes`)

  // and the claim that killed the two-machine comparison, re-counted from the cache
  let lvl1 = 0, lvl1WithMarkup = 0
  for (const e of Object.values(ws)) {
    if (!e.exists) continue
    if (pageQuality(e.raw) !== 1) continue
    const body = e.raw.replace(/<noinclude>[\s\S]*?<\/noinclude>/g, '')
    if (body.trim().length < 60) continue
    lvl1++
    if (/''/.test(body)) lvl1WithMarkup++
  }
  eq(lvl1WithMarkup, lvl1,
    `every one of the ${lvl1} unproofread pages carries italic markup, so none of them is raw machine text`)
}

/* ---------------------------------------------------------------------------- summary ---- */

console.log(`\n${pass + fail} checks · ${pass} pass · ${fail} fail`)
process.exit(fail === 0 ? 0 : 1)
