// verify-the-size-of-an-egg.mjs: check aggregate arithmetic in the committed artifacts,
// source quotations when the XML is available, and selected figures on the static page.
//
// Three layers, because three different things can go wrong.
//   1. THE SPEC. measures.mjs is the whole definition of what counts as an amount. A
//      battery of hand-written strings pins the accept rule, the four classes and the
//      known refusals, so a "harmless" widening of a regex cannot pass silently.
//   2. THE ARITHMETIC. Every aggregate in data/measures.json, data/equivalences.json,
//      data/books.json and data/audit-result.json is recomputed here from the rows
//      beneath it. Shares must sum to one, decade means must be means over books, an
//      F1 must be the harmonic mean of the precision and recall printed beside it.
//   3. THE PAGE. The public page is served and driven in a real browser: selected figures
//      are compared against the artifacts as STRINGS, the highlighter's counts
//      are compared against what node computes for the same recipe, and the extractor the
//      page ships is compared byte for byte against the one the lab ran.
//
//   node verify-the-size-of-an-egg.mjs

import { readFileSync, existsSync } from 'node:fs';
import { createServer } from 'node:http';
import { extname, join } from 'node:path';
import * as M from './research/recipe-measurement/measures.mjs';
import { textOf } from './research/recipe-measurement/corpus.mjs';

const R = './research/recipe-measurement/data';
const P = './public/strata/the-size-of-an-egg';
const read = (p) => JSON.parse(readFileSync(p, 'utf8'));

let fails = 0;
let checks = 0;
const ok = (name, cond, extra = '') => {
  checks += 1;
  if (!cond) fails += 1;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? `   ${extra}` : ''}`);
};
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

console.log('\n── 1. the spec: what measures.mjs counts ──────────────────────────');

const cls = (t) => {
  const h = M.hitsOf(t);
  return {
    named: h.named.map((x) => x.text),
    vessel: h.vessel.map((x) => x.text),
    somatic: h.somatic.map((x) => x.text),
    indefinite: h.indefinite.map((x) => x.text),
  };
};
const counts = (t) => {
  const c = cls(t);
  return `${c.named.length}/${c.vessel.length}/${c.somatic.length}/${c.indefinite.length}`;
};

// [text, expected named/vessel/somatic/indefinite, why]
const SPEC = [
  ['1 cup sugar', '1/0/0/0', 'numeral governs an ambiguous unit'],
  ['put it in a cup and set aside', '0/0/0/0', 'a cup with no quantity is a container'],
  ['serve in a glass dish', '0/0/0/0', 'a glass with no quantity is a dish'],
  ['beat in a bowl', '0/0/0/0', 'a bowl with no quantity is a bowl'],
  ['a cup of milk', '1/0/0/0', 'the following "of" makes it an amount'],
  ['a glass of wine', '0/1/0/0', 'a glass is a vessel measure, not a named one'],
  ['a wineglassful', '0/1/0/0', 'the -ful suffix is enough on its own'],
  ['a pound flour', '1/0/0/0', 'a pound is not a container, so no "of" is needed'],
  ['a saltspoon salt', '1/0/0/0', 'same rule, graded spoon'],
  ['two spoonfuls of white wine', '0/1/0/0', 'a bare spoonful is whatever spoon you own'],
  ['three table-spoonsful of water', '1/0/0/0', 'the s-in-the-middle plural'],
  ['2 level tablespoons of baking powder', '1/0/0/0', 'a fill qualifier may stand between'],
  ['two additional tablespoonfuls of sugar', '1/0/0/0', 'so may an adjective'],
  ['to each gallon of juice', '1/0/0/0', 'each and every are determiners'],
  ['half a pint of cream', '1/0/0/0', 'a fraction word governing through an article'],
  ['three quarters of a pound of sugar', '1/0/0/0', 'a compound fraction'],
  ['butter the size of an egg', '0/0/1/0', 'the comparison frame'],
  ['a lump as large as a walnut', '0/0/1/0', 'the other comparison frame'],
  ['a small piece of butter', '0/0/1/0', 'an adjective inside the frame'],
  ['cover with a piece of paper', '0/0/0/0', 'paper is not an amount of food'],
  ['a little pepper and salt', '0/0/0/1', 'the shrug'],
  ['boil a few minutes', '0/0/0/0', 'a few minutes is a time, not an amount'],
  ['beat a little longer', '0/0/0/0', 'a little longer is manner, not an amount'],
  ['a few cloves', '0/0/0/1', 'a few of a thing is an amount'],
  ['flour enough to make a soft batter', '0/0/0/1', 'enough, with the noun in front'],
  ['as much water as will cover it', '0/0/0/1', 'as much X as will'],
  ['season to taste', '0/0/0/1', 'to taste'],
  ['three eggs and six shallots', '0/0/0/0', 'a bare count is not an amount'],
  ['1 tablespoonful melted butter', '1/0/0/0', 'the itemised list form'],
  ['a gill of sherry', '1/0/0/0', 'a legal volume'],
  ['a teacupful of cream', '0/1/0/0', 'a teacup is a vessel'],
];
for (const [text, want, why] of SPEC) {
  ok(`spec: ${why}`, counts(text) === want, `"${text}" → ${counts(text)} (want ${want})`);
}

ok('spec: a level teaspoon is a fill qualifier', M.scoreText('1 level teaspoon soda').level === 1);
ok('spec: a heaping teaspoon is the other one', M.scoreText('1 heaping teaspoon soda').heaping === 1);
ok('spec: a named oven heat is counted', M.scoreText('bake in a quick oven').namedOven === 1);
ok('spec: a degree only counts near an oven',
  M.scoreText('bake in a moderate oven at 350 degrees').degreeOven === 1
  && M.scoreText('boil the syrup to 238 degrees').degreeOven === 0);
ok('spec: a duration is counted', M.scoreText('bake forty minutes').duration === 1);
ok('spec: half an hour is a duration', M.scoreText('bake half an hour').duration === 1);
ok('spec: a doneness cue is counted separately', M.scoreText('bake until brown').doneness === 1);
ok('spec: the boundary units are the two graded spoons',
  JSON.stringify(M.BOUNDARY_UNITS) === JSON.stringify(['dessertspoon', 'saltspoon']));
ok('spec: unitTally names the unit', JSON.stringify(M.unitTally('2 cups flour and 1 gill milk'))
  === JSON.stringify({ cup: 1, gill: 1 }));

console.log('\n── 2. the arithmetic: artifacts recomputed from their own rows ────');

const books = read(`${R}/books.json`);
const meas = read(`${R}/measures.json`);
const equiv = read(`${R}/equivalences.json`);
const audit = read(`${R}/audit-result.json`);
const page = read(`${R}/page-data.json`);

ok('books: 74 transcriptions carry recipes', books.nBooks === 74, String(books.nBooks));
ok('books: 76 XML files in the dataset', books.nXmlFiles === 76, String(books.nXmlFiles));
ok('books: 76 catalogue records', books.nCatalogueRecords === 76, String(books.nCatalogueRecords));
ok('books: 2 files dropped for having no recipes', books.dropped.length === 2,
  books.dropped.map((d) => d.stem).join(','));
ok('books: every dropped file names its reason', books.dropped.every((d) => d.reason));
ok('books: the range is 1803 to 1922',
  books.yearRange[0] === 1803 && books.yearRange[1] === 1922, books.yearRange.join('–'));
ok('books: recipe total is the sum over books',
  books.nRecipes === books.books.reduce((a, b) => a + b.nRecipes, 0), String(books.nRecipes));
ok('books: every book has a year', books.books.every((b) => Number.isInteger(b.year)));
ok('books: years are sorted', books.books.every((b, i, a) => i === 0 || a[i - 1].year <= b.year));
ok('books: three dates are overridden by hand', books.overrides.length === 3);
ok('books: every override records what it changed and why',
  books.overrides.every((o) => o.was && o.year && o.why && o.why.length > 60));
ok('books: every override is applied', books.overrides.every(
  (o) => books.books.find((b) => b.stem === o.stem).year === o.year));
ok('books: the econ override moves 1815 to 1845',
  books.overrides.find((o) => o.stem === 'econ').was === 1815);
ok('books: every disagreement is listed', books.books.filter((b) => b.disagrees).length
  === books.disagreements.length, String(books.disagreements.length));
ok('books: the type tally the page prints is the corpus\'s own', (() => {
  const t = {};
  for (const b of books.books) t[b.type] = (t[b.type] || 0) + 1;
  return t.general === 51 && t.famous === 10 && t.charity === 6 && t.frugal === 4
    && t.encyclopedia === 2 && t.restaurant === 1
    && Object.values(t).reduce((a, c) => a + c, 0) === 74;
})());
ok('books: six books carry fewer than 60 marked recipes',
  books.books.filter((b) => b.nRecipes < 60).length === 6,
  books.books.filter((b) => b.nRecipes < 60).map((b) => `${b.stem}(${b.nRecipes})`).join(' '));
ok('books: the one book with no title of its own is named from MSU\'s list',
  books.titleFallbacks.length === 1 && books.titleFallbacks[0].stem === 'bart'
  && /title list/.test(books.titleFallbacks[0].from));
ok('books: no title is the whole title page',
  books.books.every((b) => b.title.length <= 60), String(Math.max(...books.books.map((b) => b.title.length))));

ok('measures: 74 books', meas.nBooks === 74);
ok('measures: 48,644 recipes', meas.nRecipes === 48644, String(meas.nRecipes));
ok('measures: recipe total is the sum over books',
  meas.nRecipes === meas.books.reduce((a, b) => a + b.nRecipes, 0));
ok('measures: word total is the sum over books',
  meas.nWords === meas.books.reduce((a, b) => a + b.words, 0));
ok('measures: amount total is the sum over books',
  meas.nAmounts === meas.books.reduce((a, b) => a + b.amounts, 0));
ok('measures: every book\'s amounts are its four class counts',
  meas.books.every((b) => b.amounts === b.counts.named + b.counts.vessel + b.counts.somatic + b.counts.indefinite));
ok('measures: every book\'s four shares sum to one',
  meas.books.every((b) => !b.share || near(b.share.named + b.share.vessel + b.share.somatic + b.share.indefinite, 1, 1e-9)));
ok('measures: every share is its count over the total',
  meas.books.every((b) => !b.share || near(b.share.named, b.counts.named / b.amounts, 1e-12)));
ok('measures: the boundary test moves exactly the two graded spoons',
  meas.books.every((b) => !b.share
    || near(b.share.named - b.shareBoundaryMoved.named,
      ((b.units.dessertspoon || 0) + (b.units.saltspoon || 0)) / b.amounts, 1e-12)));
ok('measures: every fraction of recipes is between 0 and 1',
  meas.books.every((b) => Object.values(b.frac).every((v) => v >= 0 && v <= 1)));
ok('measures: oven counts never exceed oven recipes',
  meas.books.every((b) => b.oven.named <= b.oven.recipes && b.oven.degrees <= b.oven.recipes));

const decadeOf = new Map();
for (const b of meas.books) {
  const d = Math.floor(b.year / 10) * 10;
  if (!decadeOf.has(d)) decadeOf.set(d, []);
  decadeOf.get(d).push(b);
}
ok('measures: the decade table covers every decade with a book',
  meas.decades.length === decadeOf.size, `${meas.decades.length} vs ${decadeOf.size}`);
let decadeOkay = true;
for (const d of meas.decades) {
  const rs = decadeOf.get(d.decade);
  const mean = (f) => rs.reduce((a, r) => a + f(r), 0) / rs.length;
  if (rs.length !== d.nBooks) decadeOkay = false;
  if (!near(d.shareNamed, mean((r) => r.share.named), 1e-12)) decadeOkay = false;
  if (!near(d.fracList, mean((r) => r.frac.list), 1e-12)) decadeOkay = false;
  if (d.nRecipes !== rs.reduce((a, r) => a + r.nRecipes, 0)) decadeOkay = false;
}
ok('measures: every decade figure is the mean over its books, not over its recipes', decadeOkay);

ok('equivalences: every row\'s value is its own ratio',
  equiv.groups.every((g) => g.rows.every((r) => near(r.perOne, r.nFrom / r.nTo, 1e-12))));
ok('equivalences: numerator and denominator follow the displayed unit order',
  equiv.groups.every((g) => g.rows.every((r) => `${r.from}->${r.to}` === g.key.split(':')[0])));
ok('equivalences: every group\'s value set is its rows\' values',
  equiv.groups.every((g) => {
    const seen = [...new Set(g.rows.map((r) => Number(r.perOne.toFixed(4))))].sort((a, b) => a - b);
    return JSON.stringify(seen) === JSON.stringify(g.values);
  }));
ok('equivalences: every group\'s book count is its distinct stems',
  equiv.groups.every((g) => g.books === new Set(g.rows.map((r) => r.stem)).size));
ok('equivalences: the candidate total is the sum over groups',
  equiv.nCandidates === equiv.groups.reduce((a, g) => a + g.n, 0), String(equiv.nCandidates));
ok('equivalences: every row carries source text',
  equiv.groups.every((g) => g.rows.every((r) => r.verbatim && r.verbatim.length > 10)));
ok('equivalences: every row belongs to a dated book',
  equiv.groups.every((g) => g.rows.every((r) => books.books.some((b) => b.stem === r.stem && b.year === r.year))));

const tsp = equiv.groups.find((g) => g.key === 'teaspoon->tablespoon');
ok('equivalences: the teaspoon-to-tablespoon group exists', Boolean(tsp));
ok('equivalences: the corpus gives both 3 and 4 teaspoons to the tablespoon',
  JSON.stringify(tsp.values) === JSON.stringify([3, 4]), JSON.stringify(tsp.values));
ok('equivalences: Lincoln 1884 states both answers herself',
  tsp.rows.filter((r) => r.stem === 'linc').length === 2
  && new Set(tsp.rows.filter((r) => r.stem === 'linc').map((r) => r.perOne)).size === 2);
ok('equivalences: Lincoln\'s two rows differ by what is in the spoon',
  tsp.rows.filter((r) => r.stem === 'linc').some((r) => /liquid/i.test(r.verbatim))
  && tsp.rows.filter((r) => r.stem === 'linc').some((r) => /dry/i.test(r.verbatim)));
ok('equivalences: Farmer 1896 states three, unconditionally',
  tsp.rows.some((r) => r.stem === 'bost' && r.perOne === 3));
const salt = equiv.groups.find((g) => g.key === 'saltspoon->teaspoon');
ok('equivalences: saltspoons to the teaspoon are 4 in two books and 8 in one',
  salt && JSON.stringify(salt.values) === JSON.stringify([4, 8]));
for (const [commodity, stem, denominator] of [
  ['sugar', 'gohk', 17], ['sugar', 'lady', 17], ['butter', 'lady', 17],
  ['cornmeal', 'gohk', 18], ['cornmeal', 'lady', 18],
  ['sugar_brown', 'gohk', 18], ['sugar_brown', 'lady', 18],
]) {
  const rows = equiv.groups.find((g) => g.key === `quart->pound:${commodity}`).rows;
  ok(`equivalences: ${stem} ${commodity}, ${denominator} ounces per quart is 16/${denominator} quarts per pound`,
    rows.some((r) => r.stem === stem && near(r.perOne, 16 / denominator, 1e-12)));
}

for (const half of ['dev', 'test']) {
  const h = audit[half];
  ok(`audit(${half}): 60 recipes`, h.sampleSize === 60);
  const cmps = Object.keys(h).filter((k) => k === 'readerVsReader' || k.startsWith('extractorVs'));
  ok(`audit(${half}): three comparisons`, cmps.length === 3, cmps.join(','));
  let arith = true;
  for (const k of cmps) {
    for (const row of [...h[k].rows, h[k].overall]) {
      const p = row.left ? row.tp / row.left : null;
      const r = row.right ? row.tp / row.right : null;
      if (p != null && !near(row.precision, p, 1e-12)) arith = false;
      if (r != null && !near(row.recall, r, 1e-12)) arith = false;
      if (p && r && !near(row.f1, (2 * p * r) / (p + r), 1e-12)) arith = false;
      if (row.tp > row.left || row.tp > row.right) arith = false;
    }
  }
  ok(`audit(${half}): every precision, recall and F1 is the arithmetic of its own counts`, arith);
  ok(`audit(${half}): the four shares sum to one`,
    Object.values(h.shares).every((s) => near(s.NAMED + s.VESSEL + s.SOMATIC + s.INDEFINITE, 1, 1e-9)));
}
ok('audit: the two samples share no recipe', (() => {
  const a = read(`${R}/audit-sample.json`).recipes.map((r) => `${r.stem}#${r.i}`);
  const b = new Set(read(`${R}/audit-sample-2.json`).recipes.map((r) => `${r.stem}#${r.i}`));
  return a.every((k) => !b.has(k));
})());
ok('audit: the held-out sample was drawn with a different seed',
  read(`${R}/audit-sample.json`).seed !== read(`${R}/audit-sample-2.json`).seed);
ok('audit: the readers agree with each other more closely than the extractor does with either',
  audit.test.readerVsReader.overall.f1 > audit.test.extractorVsC.overall.f1
  && audit.test.readerVsReader.overall.f1 > audit.test.extractorVsD.overall.f1);
ok('audit: the somatic class is the weakest on held-out data',
  audit.test.extractorVsC.rows[2].f1 === Math.min(...audit.test.extractorVsC.rows.map((r) => r.f1)));
ok('audit: recall on the vague classes is highest in the earliest era, against expectation', (() => {
  const e = audit.test.vagueRecallByEra.C;
  const keys = Object.keys(e).sort();
  return e[keys[0]].recall > e[keys[1]].recall && e[keys[0]].recall > e[keys[2]].recall;
})());

ok('bestiary: the use total is the sum over objects',
  page.bestiary.total === page.bestiary.items.reduce((a, i) => a + i.n, 0), String(page.bestiary.total));
ok('bestiary: the distinct count is the number of objects',
  page.bestiary.distinct === page.bestiary.items.length);
ok('bestiary: the egg leads it', page.bestiary.items[0].object === 'egg');
ok('bestiary: the walnut is second', page.bestiary.items[1].object === 'walnut');
ok('bestiary: every object carries an example',
  page.bestiary.items.every((i) => i.example && i.example.length > 10));
ok('bestiary: every example comes from a book at the earliest recorded year',
  page.bestiary.items.every((i) => i.exampleYear === i.first
    && books.books.some((b) => b.stem === i.exampleStem && b.year === i.first)));
ok('bestiary: every object\'s years lie inside the corpus',
  page.bestiary.items.every((i) => i.first >= 1803 && i.last <= 1922 && i.first <= i.last));

console.log('\n── 3. the claims the prose makes ─────────────────────────────────');

const byStem = new Map(meas.books.map((b) => [b.stem, b]));
const bost = byStem.get('bost');
const linc = byStem.get('linc');

ok('claim: the lowest indefinite share of 74 books is Farmer 1896, and her 1904 book is third', (() => {
  const low = [...meas.books].sort((a, b) => a.share.indefinite - b.share.indefinite).slice(0, 3);
  return low[0].stem === 'bost' && low[2].stem === 'fcsc';
})());
ok('claim: the highest named share is also Farmer 1896',
  [...meas.books].sort((a, b) => b.share.named - a.share.named)[0].stem === 'bost');
ok('claim: Farmer 1896 uses the word "level" once inside her 1,424 recipes',
  bost.counts.levelWord === 1 && bost.nRecipes === 1424, `${bost.counts.levelWord} in ${bost.nRecipes}`);
ok('claim: Lincoln uses it once too, in 809 recipes',
  linc.counts.levelWord === 1 && linc.nRecipes === 809);
ok('claim: Lincoln heaps fourteen times more often than Farmer, per recipe', (() => {
  const rate = (b) => b.counts.heapWord / b.nRecipes;
  const ratio = rate(linc) / rate(bost);
  return ratio > 13.5 && ratio < 14.5;
})(), `${(linc.counts.heapWord / linc.nRecipes) / (bost.counts.heapWord / bost.nRecipes)}`);
ok('claim: Rorer 1902 repeats "level" inside her recipes instead',
  byStem.get('rore').counts.levelWord > 150, String(byStem.get('rore').counts.levelWord));
ok('claim: a pre-Farmer book beats most later books on cup-and-spoon rate', (() => {
  const rate = (b) => ((b.units.cup || 0) + (b.units.teaspoon || 0) + (b.units.tablespoon || 0)) / b.words * 1000;
  const pre = meas.books.filter((b) => b.year < 1896).sort((a, b) => rate(b) - rate(a))[0];
  const laterBeaten = meas.books.filter((b) => b.year > 1896 && rate(b) < rate(pre)).length;
  return pre.year < 1896 && laterBeaten > 10;
})());

const oven = meas.books.reduce((a, b) => ({
  recipes: a.recipes + b.oven.recipes, named: a.named + b.oven.named, degrees: a.degrees + b.oven.degrees,
}), { recipes: 0, named: 0, degrees: 0 });
ok('claim: most oven recipes name the heat with an adjective',
  oven.named / oven.recipes > 0.5, `${oven.named}/${oven.recipes}`);
ok('claim: fewer than 100 recipes in the whole corpus give a temperature in degrees',
  oven.degrees < 100, String(oven.degrees));
ok('claim: two books account for most of those', (() => {
  const top = [...meas.books].sort((a, b) => b.oven.degrees - a.oven.degrees).slice(0, 2);
  return (top[0].oven.degrees + top[1].oven.degrees) / oven.degrees > 0.8;
})());
ok('claim: Blot 1868 is one of them',
  [...meas.books].sort((a, b) => b.oven.degrees - a.oven.degrees).slice(0, 2).some((b) => b.stem === 'hand'));

const quotes = page.quotes;
ok('quote: Farmer\'s passage says "measured level" three times',
  (quotes.farmerLevel.text.match(/measured level/g) || []).length === 3, quotes.farmerLevel.text.slice(0, 70));
ok('quote: Lincoln states the unmarked measure is a full one',
  /All these measures mean a full measure/.test(quotes.lincolnDefault.text));
ok('quote: Lincoln lists the half-pint cup divided into quarters and thirds',
  /tin measuring-cups holding half a pint, and divided into quarters and thirds/.test(quotes.lincolnCups.text));
ok('source: the popular claim is quoted, not paraphrased',
  /introduced standard measures/.test(page.sources.claimMassMoments.quote)
  && page.sources.claimMassMoments.url.startsWith('https://'));
ok('source: every outside source carries a URL and a quotation',
  Object.values(page.sources).every((s) => s.url && s.quote && s.what));
ok('source: the modern standard is cited to NIST',
  /3 teaspoons \(exactly\)/.test(page.sources.nist.quote));
ok('note: the Hale row is attributed to the printed book, with its caveat',
  /the book, not the transcription/.test(page.haleNote) && /only that one digitised copy/i.test(page.haleNote));
ok('quote: Lincoln starts with a heaping spoonful and shakes it until just rounded over',
  /heaping spoonful/.test(quotes.lincolnHeaping.text)
  && /shake it slightly until it is just rounded over/.test(quotes.lincolnHeaping.text));
ok('quote: Lincoln names the level spoon as the marked case',
  /even or scant teaspoonful/.test(quotes.lincolnHeaping.text));
ok('quote: Blot tells the reader to bore a hole in the range',
  /bore a hole/.test(quotes.blotThermometer.text));
ok('quote: every quote carries its book and year',
  Object.values(quotes).every((q) => q.title && q.year && q.author));

// Read the original XML directly, without the recipe parser or equivalence generator.
// Whitespace differs at block and table-cell boundaries; word order and punctuation must not.
const compact = (s) => s.replace(/\s+/g, '');
if (books.books.every((b) => existsSync(`${R}/enc/${b.stem}.xml`))) {
  const xml = new Map(books.books.map((b) => [b.stem, readFileSync(`${R}/enc/${b.stem}.xml`, 'utf8')]));
  const original = new Map([...xml].map(([stem, src]) => [stem, compact(textOf(src))]));
  ok('source: every sampled recipe retains the original words in their original order',
    page.samples.every((s) => {
      const recipes = [...xml.get(s.stem).matchAll(/<recipe\b[^>]*>([\s\S]*?)<\/recipe>/g)];
      return compact(`${s.heading} ${s.text}`) === compact(textOf(recipes[s.i][1]));
    }));
  ok('source: every conversion quotation is present in its transcription',
    equiv.groups.every((g) => g.rows.every((r) => original.get(r.stem).includes(compact(r.verbatim)))));
  ok('source: every bestiary example is present in its cited book',
    page.bestiary.items.every((i) => original.get(i.exampleStem).includes(compact(i.example))));
  ok('source: every cookbook passage is present in its transcription',
    Object.values(quotes).every((q) => original.get(q.stem).includes(compact(q.text))));
} else {
  console.log('  (source quotation checks skipped: run node research/recipe-measurement/fetch.mjs)');
}

console.log('\n── 4. what the page ships ────────────────────────────────────────');

ok('page: the extractor the page ships is the one the lab ran',
  readFileSync(`${P}/measures.mjs`, 'utf8') === readFileSync('./research/recipe-measurement/measures.mjs', 'utf8'));
const dataJs = readFileSync(`${P}/data.js`, 'utf8');
ok('page: data.js is a module exporting DATA', /^export const DATA = \{/.test(dataJs));
// the file ends with a trailing `// em-dash-ok` marker, because Hale 1839's printed table row
// carries an em dash and a verbatim quotation is never edited to suit a house style
ok('page: data.js carries the verbatim-quotation marker', /\/\/ em-dash-ok/.test(dataJs));
ok('page: data.js matches the committed artifact',
  JSON.stringify(JSON.parse(dataJs.replace(/^export const DATA = /, '').replace(/;\s*(\/\/[^\n]*)?\s*$/, '')))
  === JSON.stringify(page));
const html = readFileSync(`${P}/index.html`, 'utf8');
for (const tag of ['</script>', '</body>', '</html>']) {
  ok(`page: ${tag} is present`, html.includes(tag));
}
ok('page: canonical URL is set', html.includes('href="https://artwaste.land/strata/the-size-of-an-egg/"'));
ok('page: JSON-LD parses', (() => {
  const m = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
  try { JSON.parse(m[1]); return true; } catch { return false; }
})());
ok('page: no em dash in the page\'s own prose', !/—/.test(html.replace(/<script[\s\S]*?<\/script>/g, '')));

const SITE = './public/';
if (!existsSync(`${P}/index.html`)) {
  ok('browser: the static page exists', false);
} else {
  const types = {
    '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
    '.woff2': 'font/woff2', '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml',
    '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain', '.xml': 'text/xml',
  };
  const server = createServer((req, res) => {
    let p = decodeURIComponent(req.url.split('?')[0]);
    if (p.endsWith('/')) p += 'index.html';
    try {
      const buf = readFileSync(join(SITE, p));
      res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' });
      res.end(buf);
    } catch { res.writeHead(404); res.end('404'); }
  });
  await new Promise((r) => server.listen(8188, r));

  let chromium;
  try {
    ({ chromium } = await import('playwright'));
  } catch {
    try { ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default); } catch { /* none */ }
  }
  if (!chromium) {
    console.log('  (skipping the browser pass: playwright not installed)');
    server.close();
  } else {
    const browser = await chromium.launch();
    const pg = await browser.newPage({ viewport: { width: 1200, height: 1000 } });
    const errs = [];
    pg.on('pageerror', (e) => errs.push(String(e)));
    pg.on('console', (m) => { if (m.type() === 'error' && !/404|Failed to load resource/.test(m.text())) errs.push(m.text()); });
    await pg.goto('http://localhost:8188/strata/the-size-of-an-egg/', { waitUntil: 'networkidle' });
    await pg.waitForTimeout(700);

    ok('browser: no JavaScript errors', errs.length === 0, errs.slice(0, 2).join(' | '));
    ok('browser: 74 dots in the scatter',
      (await pg.locator('#scatter circle').count()) === 74);
    ok('browser: 148 dots in the unit chart (two series over 74 books)',
      (await pg.locator('#units circle').count()) === 148);
    ok('browser: the recipe is marked up', (await pg.locator('#recipe mark').count()) > 0);

    // the page's own highlighter, checked against node on the same text
    const sample = page.samples[0];
    const domCounts = await pg.evaluate(() => {
      const n = (c) => document.querySelectorAll(`#recipe mark.${c}`).length;
      return { named: n('m-named'), vessel: n('m-vessel'), somatic: n('m-somatic'), indefinite: n('m-indef') };
    });
    const nodeCounts = M.hitsOf(sample.text);
    // marks can be swallowed when spans overlap, so the browser count is a floor
    ok('browser: the browser marks the same amounts node finds',
      domCounts.named + domCounts.vessel + domCounts.somatic + domCounts.indefinite
      <= nodeCounts.named.length + nodeCounts.vessel.length + nodeCounts.somatic.length + nodeCounts.indefinite.length
      && domCounts.named + domCounts.vessel + domCounts.somatic + domCounts.indefinite > 0,
      JSON.stringify(domCounts));
    const tally = await pg.locator('#tally').textContent();
    ok('browser: the tally reports node\'s counts exactly',
      tally.includes(`Named ${nodeCounts.named.length}`)
      && tally.includes(`Vessel ${nodeCounts.vessel.length}`)
      && tally.includes(`Somatic ${nodeCounts.somatic.length}`)
      && tally.includes(`Indefinite ${nodeCounts.indefinite.length}`), tally.slice(0, 80));

    const samplesShown = await pg.evaluate((n) => {
      const texts = [];
      for (let i = 0; i < n; i++) {
        texts.push(document.querySelector('#recipe').textContent);
        document.querySelector('#next').click();
      }
      return texts;
    }, page.samples.length);
    ok('browser: Next recipe visits every sample without dropping or moving words',
      (await pg.locator('#next').textContent()) === 'Next recipe'
      && samplesShown.every((text, i) => compact(text)
        === compact(`${page.samples[i].heading} ${page.samples[i].text}`)));

    // the numbers in the prose, as strings
    const text = await pg.locator('main').innerText();
    const wants = [
      [String(oven.degrees), 'the degree-oven count'],
      [oven.recipes.toLocaleString('en-US'), 'the oven-recipe count'],
      [String(page.equivalences.total), 'the equivalence count'],
      [String(page.bestiary.distinct), 'the number of distinct comparison objects'],
      [page.bestiary.total.toLocaleString('en-US'), 'the number of comparisons'],
      [String(bost.counts.heapWord), 'Farmer\'s heaping-word count'],
      [String(linc.counts.heapWord), 'Lincoln\'s heaping-word count'],
      [String(byStem.get('rore').counts.levelWord), "Rorer's level count"],
      [meas.nRecipes.toLocaleString('en-US'), 'the recipe count'],
      [meas.nAmounts.toLocaleString('en-US'), 'the amount-expression count'],
      [`${(100 * audit.test.readerVsReader.overall.f1).toFixed(1)}%`, 'the held-out reader agreement'],
      [`${(100 * audit.test.extractorVsC.overall.f1).toFixed(1)}%`, 'the held-out extractor score'],
    ];
    for (const [s, why] of wants) ok(`browser: the page prints ${why}`, text.includes(s), s);

    ok('browser: the page prints the corpus citation', text.includes('Feeding America'));
    ok('browser: the page names its own weakest class', /somatic/i.test(text) && /upper bound/i.test(text));

    for (const [w, name] of [[390, 'phone'], [768, 'tablet'], [1440, 'desktop']]) {
      await pg.setViewportSize({ width: w, height: 900 });
      await pg.waitForTimeout(220);
      const over = await pg.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      ok(`browser: no horizontal overflow at ${w}px (${name})`, over <= 1, `overflow ${over}`);
    }

    await browser.close();
    server.close();
  }
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASS' : `${fails} FAILED`}   ${checks - fails}/${checks}`);
process.exit(fails === 0 ? 0 : 1);
