// verify-canvas-ratio.mjs: the canvas proportion lookup at /tools/canvas-ratio/,
// checked offline.
//
//   node verify-canvas-ratio.mjs        (a few seconds)
//
// The tool hands a stranger a count of real paintings that share the shape of
// their own rectangle. Six things have to be true for that to be honest, and
// each is a family below.
//
//   1. THE PAGE RUNS THE ENGINE THIS FILE DRIVES. ratio-engine.mjs and parse.mjs
//      in public/tools/canvas-ratio/ are byte for byte the files in
//      research/canvas-proportions/. If the page could drift from them, every
//      number below would be about a different instrument.
//   2. THE PAGE COUNTS THE SAME PAINTINGS THE STRATUM COUNTS. values.bin is
//      rebuilt here, from the committed record set, by an independent
//      implementation of the quantise-sort-delta-LEB128 packing, and must come
//      out byte-identical to both the tool's copy and the stratum's.
//   3. THE ENGINE AGREES WITH THE STRATUM'S OWN INLINE COPY. The counting
//      functions are extracted out of the stratum's HTML and run side by side
//      with the lifted module over a spread of targets and tolerances.
//   4. THE REAL ENGINE OVER REAL DATA GIVES THE REAL ANSWERS. Counts at named
//      proportions are checked against the numbers the stratum page publishes in
//      its own table, which came from a separate offline analysis.
//   5. IT REFUSES RATHER THAN GUESSES. Unparseable strings, frames, panels,
//      ovals, depths, shapes past the end of the encoded range, windows that run
//      off that end, and tolerances that swallow their own neighbourhood: each
//      must come back with a named reason and no number.
//   6. THE STATE IS IN THE URL AND SURVIVES THE ROUND TRIP, and the page's own
//      prose is clean. Not the parsed state: the counts. A link that reopens on
//      a neighbouring answer is the page's own warning turned against it.
//   7. THE READER SEES THOSE ANSWERS. Families 1 to 6 drive the engine. This one
//      drives the page: a real browser loads it over a real server and every
//      rendered number, percentile and drawn strip is compared with what the
//      engine returns. Five mutations that put wrong numbers in front of a
//      reader (every card showing one catalogue's count, every count multiplied
//      by ten, a percentile printed after assess() refused it, every strip drawn
//      from the wrong catalogue, strips halved and smoothed) all left this file
//      at 120 of 120 green, because nothing here had ever loaded the page.
import { readFileSync, existsSync, statSync } from 'fs';
import http from 'node:http';
import { extname } from 'node:path';
import zlib from 'node:zlib';
import * as E from './research/canvas-proportions/ratio-engine.mjs';

const ROOT = new URL('./', import.meta.url).pathname;
const TOOL = ROOT + 'public/tools/canvas-ratio/';
const LAB = ROOT + 'research/canvas-proportions/';
const STRATUM = ROOT + 'public/strata/widen-the-window/';

let pass = 0, fail = 0;
const log = [];
const ok = (c, m) => { (c ? pass++ : fail++); log.push(`  ${c ? '✓' : '✗ FAIL'} ${m}`); };

const KEYS = ['aic', 'met', 'nga', 'wd'];
const asAB = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);

// ── family 1: the page runs the engine this file drives ─────────────────────
log.push('\n[1] the page runs the engine this verifier drives (byte for byte):');
for (const f of ['ratio-engine.mjs', 'parse.mjs']) {
  const a = existsSync(TOOL + f) ? readFileSync(TOOL + f) : null;
  const b = readFileSync(LAB + f);
  ok(a !== null && a.equals(b), `${f} in the tool is identical to research/canvas-proportions/${f}`);
}
const page = readFileSync(TOOL + 'index.html', 'utf8');
ok(/from '\.\/ratio-engine\.mjs'/.test(page), 'the page imports ratio-engine.mjs from its own directory (not a copy elsewhere)');
ok(/fetch\('\.\/values\.bin'\)/.test(page), 'the page loads values.bin from its own directory');
ok(/fetch\('\.\/catalogues\.json'\)/.test(page), 'the page loads catalogues.json from its own directory');
ok(!/countIn\s*=\s*function|function countIn/.test(page.slice(page.indexOf('<script type="module">'))),
  'the page defines no counting function of its own: all of it comes from the module');

// ── family 2: the tool counts the paintings the record set holds ────────────
log.push('\n[2] values.bin is the committed record set, repacked here from scratch:');
{
  // An independent repack. This does not import the build script: if both were
  // wrong in the same way the check would be worthless.
  const text = zlib.gunzipSync(readFileSync(LAB + 'data/works-min.tsv.gz')).toString('utf8');
  const per = { aic: [], met: [], nga: [], wd: [] };
  let rows = 0;
  for (const line of text.split('\n')) {
    if (!line) continue;
    rows++;
    const f = line.split('\t');
    const h = Number(f[1]), w = Number(f[2]);
    const r = h > w ? h / w : w / h;
    if (r >= 1 && r <= 3) per[f[0]].push(Math.round(Math.log(r) * 1e6));
  }
  ok(rows === 720147, `the record set holds ${rows.toLocaleString('en-US')} usable paintings`);
  const chunks = [];
  const index = {};
  let off = 0;
  for (const k of KEYS) {
    const qs = per[k].sort((a, b) => a - b);
    const bytes = [];
    let prev = 0;
    for (const v of qs) {
      let d = v - prev; prev = v;
      while (d >= 0x80) { bytes.push((d & 0x7f) | 0x80); d >>>= 7; }
      bytes.push(d);
    }
    const buf = Buffer.from(bytes);
    index[k] = { offset: off, bytes: buf.length, n: qs.length };
    chunks.push(buf); off += buf.length;
  }
  const rebuilt = Buffer.concat(chunks);
  const shipped = readFileSync(TOOL + 'values.bin');
  const stratum = readFileSync(STRATUM + 'values.bin');
  ok(rebuilt.equals(shipped), `values.bin in the tool is exactly what the record set repacks to (${rebuilt.length.toLocaleString('en-US')} bytes)`);
  ok(shipped.equals(stratum), 'and is byte-identical to the copy /strata/widen-the-window/ ships, so the two pages cannot disagree');

  const meta = JSON.parse(readFileSync(TOOL + 'catalogues.json', 'utf8'));
  ok(KEYS.every((k) => meta.index[k].offset === index[k].offset && meta.index[k].bytes === index[k].bytes && meta.index[k].n === index[k].n),
    'catalogues.json describes that file correctly, catalogue by catalogue');
  // Every printed total has to be a real count, not a rounded headline.
  const usable = {}, outside = {};
  for (const line of text.split('\n')) {
    if (!line) continue;
    const f = line.split('\t');
    const h = Number(f[1]), w = Number(f[2]);
    const r = h > w ? h / w : w / h;
    usable[f[0]] = (usable[f[0]] || 0) + 1;
    if (r > 3) outside[f[0]] = (outside[f[0]] || 0) + 1;
  }
  ok(meta.catalogues.every((c) => c.usable === usable[c.key]),
    'the usable count printed for each catalogue is the number of records it has');
  ok(meta.catalogues.every((c) => c.outside === outside[c.key]),
    `the "longer than 3:1" count is real: ${meta.totals.outside.toLocaleString('en-US')} paintings the tool refuses to count on`);
  ok(meta.catalogues.every((c) => c.usable === c.encoded + c.outside),
    'usable = encoded + longer than 3:1, in every catalogue, so nothing is quietly dropped');
  ok(meta.totals.usable === 720147 && meta.totals.encoded === 711555,
    `totals: ${meta.totals.usable.toLocaleString('en-US')} usable, ${meta.totals.encoded.toLocaleString('en-US')} inside 1:1 to 3:1`);
}

// ── load what the page loads ────────────────────────────────────────────────
const META = JSON.parse(readFileSync(TOOL + 'catalogues.json', 'utf8'));
const VALS = E.decode(asAB(readFileSync(TOOL + 'values.bin')), META.index);

// ── family 3: the lifted engine equals the stratum's inline engine ──────────
log.push('\n[3] the lifted engine agrees with the stratum page\'s own inline copy:');
{
  // Pull the inline functions straight out of the stratum's HTML, brace-matched,
  // and run them. No copy of them is kept in this file.
  const html = readFileSync(STRATUM + 'index.html', 'utf8');
  function extract(name) {
    const at = html.indexOf('function ' + name + '(');
    if (at < 0) throw new Error('inline function not found in the stratum page: ' + name);
    let i = html.indexOf('{', at), depth = 0;
    for (let j = i; j < html.length; j++) {
      if (html[j] === '{') depth++;
      else if (html[j] === '}') { depth--; if (!depth) return html.slice(at, j + 1); }
    }
    throw new Error('unbalanced braces around ' + name);
  }
  const names = ['decode', 'lowerB', 'upperB', 'countIn', 'totalIn', 'simplest', 'neighbourPercentile'];
  const parts = names.map(extract);
  const src = parts.join('\n');
  // "It extracted more than 900 characters" was the old assertion here, and it
  // could not fail: extract() throws when it finds nothing. What has to be true
  // is that each function came out whole, and that what came out is the
  // stratum's own key-indexed implementation rather than a second copy of the
  // module this file already imports.
  ok(parts.every((p, i) => new RegExp('^function ' + names[i] + '\\s*\\(').test(p) && p.trim().endsWith('}')),
    `all ${names.length} inline functions came out of the stratum page as complete definitions`);
  ok(/VALS\[k\]/.test(src) && !/\bimport\b/.test(src) && !/countIn\(v,/.test(src),
    'and they are the stratum\'s own copy, indexed by catalogue key, not the module\'s array-taking version');

  const dataLine = html.split('\n').find((l) => l.includes('<script id="data"'));
  const D = JSON.parse(dataLine.slice(dataLine.indexOf('>') + 1, dataLine.lastIndexOf('</script>')));
  const make = new Function('D', 'LO', 'HI', 'QU', 'KEYS', `
    "use strict"; var VALS = null;
    ${src}
    return { setVals: function(v){ VALS = v; }, decode: decode, countIn: countIn,
             totalIn: totalIn, simplest: simplest, neighbourPercentile: neighbourPercentile };
  `);
  const S = make(D, D.lo, D.hi, D.qu, KEYS);

  const theirs = S.decode(asAB(readFileSync(STRATUM + 'values.bin')));
  S.setVals(theirs);
  ok(KEYS.every((k) => theirs[k].length === VALS[k].length && theirs[k].every((v, i) => v === VALS[k][i])),
    'the two decoders produce identical arrays from the same bytes');

  const TARGETS = [1, 1.1, 6 / 5, 5 / 4, 4 / 3, 1.3333, Math.SQRT2, 1.5, 1.58, E.PHI, 1.6180339887, 5 / 3, Math.sqrt(3), 16 / 9, 2, 2.35, 2.5, 2.75];
  const EPSES = [0.001, 0.0025, 0.005, 0.01, 0.03, 0.06];
  let countChecked = 0, pctChecked = 0, simpChecked = 0, bad = 0;
  for (const t of TARGETS) {
    for (const eps of EPSES) {
      if (t * (1 + eps) > 3) continue;
      for (const k of KEYS) {
        if (S.countIn(k, t, eps) !== E.countIn(VALS[k], t, eps)) bad++;
        countChecked++;
        if (S.neighbourPercentile(k, t, eps) !== E.neighbourPercentile(VALS[k], t, eps)) bad++;
        pctChecked++;
      }
      const a = S.simplest(t, eps), b = E.simplest(t, eps);
      if ((a === null) !== (b === null) || (a !== null && a !== b.text)) bad++;
      simpChecked++;
    }
  }
  ok(bad === 0, `${countChecked} window counts, ${pctChecked} neighbour percentiles and ${simpChecked} simplest-fraction answers, all identical across the two implementations`);
  ok(KEYS.every((k) => S.totalIn(k) === E.totalIn(VALS[k])), 'and the two report the same totals per catalogue');

  // A comparison that has never been seen to fail is not evidence. The same
  // extracted code is run again with one constant wrong, and has to disagree.
  const W = make(D, D.lo, D.hi, D.qu * 2, KEYS);
  W.setVals(theirs);
  let caught = 0;
  for (const t of TARGETS) {
    for (const eps of EPSES) {
      if (t * (1 + eps) > 3) continue;
      for (const k of KEYS) if (W.countIn(k, t, eps) !== E.countIn(VALS[k], t, eps)) caught++;
    }
  }
  ok(caught > 0.9 * countChecked,
    `and that comparison can fail: with the quantisation constant doubled the same code disagrees on ${caught} of ${countChecked}`);
}

// ── family 4: real answers over real data ───────────────────────────────────
log.push('\n[4] the engine over the committed data returns the published answers:');
{
  // These are the counts the stratum page prints in its own named-proportions
  // table, produced offline by analyse.mjs. The tool's live engine has to
  // reproduce them exactly, at the same window of plus or minus half a percent.
  const PUBLISHED = {
    '1.0000': [105, 158, 91, 15251],
    '1.2000': [144, 255, 240, 33858],
    '1.2500': [167, 278, 224, 35859],
    '1.3333': [136, 258, 257, 26781],   // 4:3 exactly
    '1.4142': [71, 114, 68, 14632],     // root 2
    '1.5000': [95, 140, 79, 16313],
    '1.6000': [41, 56, 42, 5898],       // 8:5
    '1.6180': [21, 38, 30, 5089],       // the golden ratio
    '1.6667': [24, 62, 38, 4899],
    '1.7321': [13, 30, 21, 2514],       // root 3
    '2.0000': [23, 64, 16, 3349],
    '1.4000': [54, 112, 82, 16598],
  };
  const AS_TYPED = { '1.3333': 4 / 3, '1.4142': Math.SQRT2, '1.6180': E.PHI, '1.6667': 5 / 3, '1.7321': Math.sqrt(3), '1.2000': 6 / 5, '1.2500': 5 / 4, '1.5000': 3 / 2, '1.6000': 8 / 5, '1.4000': 7 / 5, '1.0000': 1, '2.0000': 2 };
  let matched = 0, missed = [];
  for (const [label, want] of Object.entries(PUBLISHED)) {
    const t = AS_TYPED[label];
    const got = KEYS.map((k) => E.countIn(VALS[k], t, 0.005));
    if (got.every((g, i) => g === want[i])) matched++;
    else missed.push(`${label}: got ${got.join('/')}, page prints ${want.join('/')}`);
  }
  ok(missed.length === 0, `all ${matched} named proportions match the counts the stratum page publishes` + (missed.length ? ': ' + missed.join('; ') : ''));

  // The vetted standalone run, reproduced: 4:3 at a one per cent window.
  const t43 = 4 / 3, e1 = 0.01;
  const got = KEYS.map((k) => [E.countIn(VALS[k], t43, e1), E.neighbourPercentile(VALS[k], t43, e1)]);
  ok(got[0][0] === 212 && got[1][0] === 436 && got[2][0] === 450 && got[3][0] === 47976,
    `4:3 at ±1%: ${got.map((g) => g[0].toLocaleString('en-US')).join(' / ')} paintings across the four catalogues`);
  ok(Math.round(got[0][1] * 100) === 83 && Math.round(got[1][1] * 100) === 92 &&
     Math.round(got[2][1] * 100) === 100 && Math.round(got[3][1] * 100) === 75,
    `and neighbour percentiles ${got.map((g) => Math.round(g[1] * 100)).join(' / ')}`);

  // Percentages are of the encoded set, and the page says so; check the arithmetic.
  const pcts = KEYS.map((k) => E.countIn(VALS[k], t43, e1) / E.totalIn(VALS[k]) * 100);
  ok(pcts.map((p) => p.toFixed(2)).join('/') === '6.35/5.78/10.87/6.89',
    `the shares printed are counts over encoded totals: ${pcts.map((p) => p.toFixed(2) + '%').join(' / ')}`);

  // The whole point of the instrument: a stranger's own rectangle, end to end.
  const cases = [
    ['76.2 x 101.6 cm', 4 / 3],
    ['24 by 36 in', 1.5],
    ['29 3/4 x 41', 41 / 29.75],
    ['1920x1080 px', 16 / 9],
    ['210 x 297 mm', 297 / 210],
    ['3:2', 1.5],
    ['16:9', 16 / 9],
    ['12 3/8 in. × 7 in.', 12.375 / 7],
    ['5 ft x 3 ft', 5 / 3],
    ['8x10"', 1.25],
    ['1.618', 1.618],
  ];
  let chainOk = 0;
  for (const [text, want] of cases) {
    const p = E.parseInput(text);
    if (p.ok && Math.abs(p.ratio - want) < 1e-12) chainOk++;
    else missed.push(`${text} -> ${p.ok ? p.ratio : p.reason}`);
  }
  ok(chainOk === cases.length, `${chainOk} of ${cases.length} real input forms parse to the right ratio, including mixed fractions and the unit between the numbers`);

  // A whole answer, computed the way the page computes it.
  const p = E.parseInput('76.2 x 101.6 cm');
  const a = E.assess(p.ratio, 0.005);
  ok(p.ok && a.ok && a.percentile.ok, 'a stretched 30 by 40 inch canvas, given in centimetres, is answerable');
  ok(E.countIn(VALS.nga, p.ratio, 0.005) === 257 && E.simplest(p.ratio, 0.005).text === '4:3',
    'and comes back 4:3, with 257 National Gallery paintings inside half a per cent of it');

  // The sensitivity the page warns about, measured rather than asserted.
  const exact = E.countIn(VALS.wd, 4 / 3, 0.01), typed = E.countIn(VALS.wd, 1.3333, 0.01);
  ok(exact === 47976 && typed === 47799,
    `the page's stated window sensitivity is real: 4:3 exactly gives ${exact.toLocaleString('en-US')}, 1.3333 gives ${typed.toLocaleString('en-US')}`);
  ok(page.includes('47,976') && page.includes('47,799'),
    'and the page prints exactly those two numbers when it makes that point');
}

// ── family 5: it refuses rather than guesses ────────────────────────────────
log.push('\n[5] handed something it cannot answer, it refuses by name:');
{
  const REFUSED_INPUT = [
    ['', 'empty', 'an empty box'],
    ['hello', 'no-pair', 'prose with no measurement in it'],
    ['A4', 'no-pair', 'a paper size name it was never taught'],
    ['Framed: 30 x 40 cm', 'only-frame-or-mount', 'a frame, which is not the picture'],
    ['Mount: 20 x 25 in', 'only-frame-or-mount', 'a mount'],
    ['3 panels, each: 91.5 × 61 cm', 'multi-part-work', 'a work in several panels, which has no single shape'],
    ['oval 30 x 40 cm', 'approximate-or-not-rectangular', 'an oval'],
    ['approx 30 x 40 cm', 'approximate-or-not-rectangular', 'an approximation'],
    ['diam 30 cm', 'approximate-or-not-rectangular', 'a tondo given by diameter'],
    ['20 x 30 x 5 cm', 'three-dimensional', 'three numbers, which means a depth'],
    ['0 x 40 cm', 'no-pair', 'a side of zero'],
    ['5:0', 'zero-side', 'a proportion against zero'],
    ['137.2 x 101.9 cm; 137.2 x 120 cm', 'ambiguous-multiple', 'two unlabelled measurements that disagree by more than one per cent'],
    [42, 'no-string', 'something that is not text at all'],
    ['9'.repeat(400), 'not-finite', 'a number too large to divide into anything finite'],

    // MIXED UNITS. Two sides measured on two different rulers. Each of these
    // used to be answered, confidently and wrongly, by dropping one of the two
    // units on the floor: "30 in x 40 cm" printed 1.3333 : 1 where the truth is
    // 1.9050, and wrote a permalink saying both sides were inches.
    ['30 in x 40 cm', 'mixed-units', 'thirty inches by forty centimetres, which is not a ratio of anything'],
    ['20 in x 25 cm', 'mixed-units', 'twenty inches by twenty-five centimetres'],
    ['16 in x 20 cm', 'mixed-units', 'sixteen inches by twenty centimetres'],
    ['24 in x 36 cm', 'mixed-units', 'twenty-four inches by thirty-six centimetres'],
    ['5 ft x 10 in', 'mixed-units', 'feet against inches'],
    ['1920 px x 1080 pt', 'mixed-units', 'pixels against points'],

    // DUAL-UNIT LABELS THAT CONTRADICT THEMSELVES. A museum label states one
    // object twice. Both statements are read here; when they disagree by more
    // than one per cent the object cannot be identified and no number is given.
    // "24 x 36 in (61 x 61 cm)" used to answer 1.0000 : 1, a square, off the
    // centimetre pair alone, while the inch pair in the same string said 1.5.
    ['24 x 36 in (61 x 61 cm)', 'ambiguous-multiple', 'a label whose inch pair says 1.5 and whose centimetre pair says a square'],
    ['9 x 12 in (100 x 100 cm)', 'ambiguous-multiple', 'a label whose two pairs disagree by a third'],
    ['20 x 30 in (50 x 80 cm)', 'ambiguous-multiple', 'a label whose two pairs disagree by seven per cent'],

    // A CONTRADICTION MUST NOT BE DECIDED BY PUNCTUATION.
    ['30 x 40 cm, 50 x 60 cm', 'ambiguous-multiple', 'two contradicting measurements separated by a comma'],
    ['30 x 40 cm; 50 x 60 cm', 'ambiguous-multiple', 'the same two separated by a semicolon'],
    ['30 x 40 cm. 50 x 60 cm', 'ambiguous-multiple', 'the same two separated by a full stop'],

    // A SIGN IS NOT PUNCTUATION. "-5 x 10" used to answer 2.0000 : 1 and write
    // ?h=5&w=10, with the minus gone from both the answer and the link.
    ['-5 x 10', 'nonpositive', 'a negative side written first'],
    ['5 x -10', 'nonpositive', 'a negative side written second'],
    ['-30 x -40 cm', 'nonpositive', 'both sides negative'],
  ];
  const seenReasons = new Set();
  for (const [text, reason, what] of REFUSED_INPUT) {
    const r = E.parseInput(text);
    const named = !r.ok && (reason === null ? !!r.reason : r.reason === reason);
    if (!r.ok) seenReasons.add(r.reason);
    // A refusal that still carries a number is a refusal something downstream
    // can quietly use. Nothing measurable may survive one.
    const carriesNothing = r.ratio === undefined && r.h === undefined && r.w === undefined && r.unit === undefined;
    ok(named && !!E.INPUT_REFUSALS[r.reason] && carriesNothing,
      `${what}: refused as "${r.ok ? 'ACCEPTED ' + r.ratio.toFixed(4) : r.reason}", with a sentence to show the reader and no number attached`);
  }

  // The identical contradiction, twice, differing only in the character between
  // the two measurements. Before the fix the comma was answered and the
  // semicolon refused, and the comma is the more natural thing to type.
  {
    const a = E.parseInput('30 x 40 cm, 50 x 60 cm'), b = E.parseInput('30 x 40 cm; 50 x 60 cm');
    ok(a.ok === b.ok && a.reason === b.reason,
      `punctuation does not decide the verdict: comma gives "${a.ok ? a.ratio : a.reason}" and semicolon gives "${b.ok ? b.ratio : b.reason}"`);
  }

  // Every named input refusal must be reachable from a real string. A refusal
  // the code cannot produce is dead prose, and asserting that dead prose exists
  // is how two of these survived a hundred and twenty green checks.
  {
    const declared = Object.keys(E.INPUT_REFUSALS).sort();
    const missing = declared.filter((k) => !seenReasons.has(k));
    ok(missing.length === 0,
      `all ${declared.length} named input refusals are reachable: every one is produced by a string in the list above` +
      (missing.length ? `; unreachable: ${missing.join(', ')}` : ''));
    const undeclared = [...seenReasons].filter((k) => !E.INPUT_REFUSALS[k]);
    ok(undeclared.length === 0, 'and no refusal fires without a sentence written for it' + (undeclared.length ? `: ${undeclared.join(', ')}` : ''));
  }

  // The mixed-unit strings are not merely refused, they are refused instead of
  // the specific wrong answers the reviewer found. Naming the wrong answer is
  // what keeps this from passing again if the refusal is ever loosened.
  {
    const WAS_WRONG = [
      ['30 in x 40 cm', 1.3333, 1.9050],
      ['20 in x 25 cm', 1.2500, 2.0320],
      ['16 in x 20 cm', 1.2500, 2.0320],
      ['24 in x 36 cm', 1.5000, 1.6933],
      ['24 x 36 in (61 x 61 cm)', 1.0000, 1.5000],
    ];
    let held = 0;
    for (const [text, wrong, truth] of WAS_WRONG) {
      const r = E.parseInput(text);
      if (!r.ok) held++;
      else if (Math.abs(r.ratio - truth) < 5e-5 && Math.abs(r.ratio - wrong) > 5e-5) held++;
    }
    ok(held === WAS_WRONG.length,
      `and none of the ${WAS_WRONG.length} strings that used to print a confident wrong ratio prints one now`);
  }

  // A SWEEP RATHER THAN A LIST. The four mixed-unit strings above are the ones a
  // reviewer happened to try. This builds them by the hundred thousand, from
  // known sides in known units, and holds the whole parser to one rule: when it
  // answers, the answer is the ratio those two sides really have. Whether it
  // answers at all is its business; what it may never do is answer wrongly.
  {
    const CM = { cm: 1, mm: 0.1, m: 100, in: 2.54, ft: 30.48 };
    const NAMES = { cm: ['cm', 'centimetres'], mm: ['mm'], m: ['m'], in: ['in', 'in.', 'inches', '"'], ft: ['ft', 'feet'] };
    const SEPS = [' x ', ' × ', ' by ', 'x'];
    const units = Object.keys(CM);
    let seed = 20260806;
    const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
    const pick = (a) => a[Math.floor(rnd() * a.length)];

    let answered = 0, refusedCount = 0, mixedAnswered = 0, liars = [];
    for (let i = 0; i < 120000; i++) {
      const a = Math.round((5 + rnd() * 200) * 10) / 10;
      const b = Math.round((5 + rnd() * 200) * 10) / 10;
      const ua = pick(units), ub = pick(units);
      const sep = pick(SEPS);
      const twoSided = rnd() < 0.5;               // a unit written after each side
      const text = twoSided
        ? a + ' ' + pick(NAMES[ua]) + sep + b + ' ' + pick(NAMES[ub])
        : a + sep + b + ' ' + pick(NAMES[ua]);
      const A = a * CM[ua], B = b * (twoSided ? CM[ub] : CM[ua]);
      const truth = Math.max(A, B) / Math.min(A, B);
      const mixed = twoSided && ua !== ub;        // and the two units differ
      const r = E.parseInput(text);
      if (!r.ok) { refusedCount++; continue; }
      answered++;
      if (mixed) mixedAnswered++;
      if (Math.abs(r.ratio - truth) / truth > 1e-9 && liars.length < 4) liars.push(`${text} -> ${r.ratio.toFixed(4)}, truth ${truth.toFixed(4)}`);
    }
    ok(liars.length === 0,
      `over 120,000 generated dimension strings the parser answered ${answered.toLocaleString('en-US')} times and refused ${refusedCount.toLocaleString('en-US')}, and every answer was the ratio those two sides really have` +
      (liars.length ? `; wrong: ${liars.join(' | ')}` : ''));
    ok(mixedAnswered === 0,
      'and not one string carrying a different unit on each side was answered at all');
    ok(answered > 40000,
      `while one unit on both sides is still answered, ${answered.toLocaleString('en-US')} times, so this is a refusal of mixed units and not of measurement`);
  }

  // range refusals
  const RANGE = [
    [3.5, 0.005, 'above-range', 'a 3.5:1 panorama, past the end of what was encoded'],
    [10, 0.005, 'above-range', 'a 10:1 scroll'],
    [2.995, 0.005, 'window-past-range', 'a shape whose window would run past 3:1'],
    [-1, 0.005, 'not-a-ratio', 'a negative ratio'],
    [Infinity, 0.005, 'not-a-ratio', 'an infinite ratio'],
    [NaN, 0.005, 'not-a-ratio', 'a ratio that is not a number'],
  ];
  for (const [t, eps, reason, what] of RANGE) {
    const a = E.assess(t, eps);
    ok(!a.ok && a.reason === reason && !!E.REFUSALS[reason], `${what}: refused as "${a.ok ? 'ANSWERED' : a.reason}"`);
  }
  ok(E.assess(2.999, 0.005).ok === false && E.assess(2.9, 0.005).ok === true,
    'the boundary is where the window crosses 3:1, not an arbitrary cut-off');

  // percentile refusals, which are narrower than the count refusals
  const p1 = E.assess(2.9, 0.005);
  ok(p1.ok && !p1.percentile.ok && p1.percentile.reason === 'neighbourhood-past-range',
    'at 2.9:1 the counts are given but the neighbour percentile is refused: the shapes 12% longer were never encoded');
  const p2 = E.assess(1.5, 0.11);
  ok(p2.ok && !p2.percentile.ok && p2.percentile.reason === 'too-few-neighbours',
    `at a ±11% window the percentile is refused: only ${p2.percentile.coverage.used} comparison windows survive outside the window itself`);
  const p3 = E.assess(1, 0.005);
  ok(p3.ok && p3.percentile.ok && p3.percentile.oneSided && p3.percentile.coverage.belowRange === 80,
    'at 1:1 the percentile is given but flagged one-sided, because no rectangle has a long side shorter than its short side');
  const p4 = E.assess(4 / 3, 0.005);
  ok(p4.ok && p4.percentile.ok && !p4.percentile.oneSided && p4.percentile.coverage.used === 154,
    `in the middle of the range it answers in full: ${p4.percentile.coverage.used} neighbours compared`);

  // and the refused percentile really is withheld, not computed and hidden
  ok(E.neighbourPercentile(VALS.wd, 1.5, 0.12) === null,
    'when the window swallows the whole neighbourhood the percentile function itself returns nothing, rather than a fraction of nothing');

  // simplest() refuses too, rather than reaching for a huge denominator
  ok(E.simplest(1.618034, 0.0001) === null,
    'at a tight window on the golden ratio there is no simple whole-number match, and none is invented');
  ok(E.simplest(1.618034, 0.005).text === '13:8',
    'widen it and the honest answer appears: 13:8, which is a Fibonacci pair and not the golden ratio itself');

  // Every named range refusal must be reachable too, and by the same rule: the
  // check is that a real (t, eps) produces it, not that a string exists for it.
  {
    const produced = new Set();
    for (const [t, eps] of [[3.5, 0.005], [2.995, 0.005], [-1, 0.005], [2.9, 0.005], [1.5, 0.11]]) {
      const a = E.assess(t, eps);
      if (!a.ok) produced.add(a.reason);
      else if (a.percentile && !a.percentile.ok) produced.add(a.percentile.reason);
    }
    const declared = Object.keys(E.REFUSALS).sort();
    const missing = declared.filter((k) => !produced.has(k));
    ok(missing.length === 0,
      `all ${declared.length} named range refusals are reachable from a real shape and window` +
      (missing.length ? `; unreachable: ${missing.join(', ')}` : ''));
  }
  ok(page.includes('INPUT_REFUSALS[r.reason]') && page.includes('REFUSALS[a.reason]'),
    'and the page prints those sentences rather than its own paraphrase of them');
}

// ── family 6: the URL grammar, and the page's prose ─────────────────────────
log.push('\n[6] the whole query state round-trips through the address bar:');
{
  const STATES = [
    { mode: 'dims', h: 76.2, w: 101.6, unit: 'cm', eps: 0.005 },
    { mode: 'dims', h: 29.75, w: 41, unit: null, eps: 0.012 },
    { mode: 'dims', h: 1920, w: 1080, unit: 'px', eps: 0.001 },
    { mode: 'dims', h: 210, w: 297, unit: 'mm', eps: 0.0075 },
    { mode: 'ratio', ratio: 1.618034, eps: 0.0025 },
    { mode: 'ratio', ratio: 4 / 3, eps: 0.12 },
    { mode: 'ratio', ratio: 2.5, eps: 0.05 },
  ];
  let tripped = 0;
  for (const s of STATES) {
    const q = E.encodeQuery(s);
    const back = E.decodeQuery('?' + q);
    // Exact equality, not a tolerance. This line used to allow the ratio back at
    // six decimal places, which is to say it asserted the rounding that made the
    // share button write a link to a different answer.
    const same = back && back.mode === s.mode && back.eps === E.clampEps(s.eps) &&
      (s.mode === 'dims'
        ? back.h === s.h && back.w === s.w && back.unit === s.unit
        : back.ratio === s.ratio);
    const stable = E.encodeQuery(back) === q;
    // and the text the page puts back in the box parses to the identical ratio,
    // because the page answers from that box and not from the query it came in on
    const re = E.parseInput(E.stateToText(back));
    const reparses = re.ok && re.ratio === back.ratio;
    if (same && stable && reparses) tripped++;
    else log.push(`      (state ${q} came back as ${JSON.stringify(back)})`);
  }
  ok(tripped === STATES.length, `${tripped} of ${STATES.length} states encode to a URL, decode back unchanged, re-encode to the same URL, and re-parse from the box`);

  // THE LINK HAS TO REPRODUCE THE ANSWER, NOT A NEIGHBOURING ONE. Round-tripping
  // the parsed state was never enough: the counts are two binary searches over
  // quantised logarithms, so a ratio rounded into the URL lands on a different
  // integer bound and comes back a different number of paintings. The page makes
  // a feature of exactly that sensitivity in its Honest limits section, so this
  // check is on the counts a reader sees, not on the state behind them.
  //
  // At six decimal places, which is what encodeQuery used to write, 2.3% of
  // ratios printed at least one different count when the link was reopened, and
  // the reviewer's own example (31/24, Wikidata 24,678) reopened at 24,673.
  {
    const countsAt = (t, eps) => KEYS.map((k) => E.countIn(VALS[k], t, eps));
    const same = (a, b) => a.every((x, i) => x === b[i]);

    const typed = E.parseInput('31/24');
    const link = E.decodeQuery('?' + E.encodeQuery({ mode: 'ratio', ratio: typed.ratio, eps: 0.005 }));
    const boxAgain = E.parseInput(E.stateToText(link));
    ok(same(countsAt(typed.ratio, 0.005), countsAt(link.ratio, 0.005)) &&
       same(countsAt(typed.ratio, 0.005), countsAt(boxAgain.ratio, 0.005)) &&
       countsAt(typed.ratio, 0.005)[3] === 24678,
      `the reviewer's case reopens on its own answer: 31/24 gives ${countsAt(typed.ratio, 0.005)[3].toLocaleString('en-US')} Wikidata paintings, and so does its link`);

    // A sweep wide enough that a rounding of any kind shows up. Deterministic,
    // so a failure here is reproducible rather than a story about a random seed.
    let seed = 20260806, drifted = 0, tried = 0, worst = null;
    const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
    for (let i = 0; i < 40000; i++) {
      const t = 1 + rnd() * 1.9;
      const eps = 0.001 + rnd() * 0.05;
      if (t * (1 + eps) > E.HI) continue;
      tried++;
      const mine = countsAt(t, eps);
      const back = E.decodeQuery('?' + E.encodeQuery({ mode: 'ratio', ratio: t, eps }));
      const theirs = countsAt(back.ratio, back.eps);
      // and the box the page refills from that link, which is what it answers on
      const box = E.parseInput(E.stateToText(back));
      const boxCounts = countsAt(box.ratio, back.eps);
      if (!same(mine, theirs) || !same(mine, boxCounts)) {
        drifted++;
        const gap = Math.max(...mine.map((x, j) => Math.abs(x - theirs[j])));
        if (!worst || gap > worst.gap) worst = { t, eps, gap, mine, theirs };
      }
    }
    ok(drifted === 0,
      `over ${tried.toLocaleString('en-US')} ratio and tolerance pairs, every link reopens on the identical four counts` +
      (worst ? `; worst drift ${worst.mine.join('/')} became ${worst.theirs.join('/')} at ${worst.t}` : ''));

    // The same, for the two-sided form, where the URL carries h and w.
    let dimsDrift = 0;
    for (const [h, w] of [[76.2, 101.6], [29.75, 41], [1920, 1080], [210, 297], [1 / 3, 2], [31, 24], [12.375, 7], [0.7, 1.9]]) {
      const t = Math.max(h, w) / Math.min(h, w);
      if (t * 1.005 > E.HI) continue;
      const back = E.decodeQuery('?' + E.encodeQuery({ mode: 'dims', h, w, unit: 'cm', eps: 0.005 }));
      const box = E.parseInput(E.stateToText(back));
      if (!same(countsAt(t, 0.005), countsAt(back.ratio, 0.005)) || !same(countsAt(t, 0.005), countsAt(box.ratio, 0.005))) dimsDrift++;
    }
    ok(dimsDrift === 0, 'and the two-sided form reopens on its own counts as well, including sides that are not round numbers');
  }

  ok(E.decodeQuery('?h=76.2&w=101.6&unit=cm&eps=0.5').ratio === 101.6 / 76.2,
    'a hand-written deep link gives the ratio it should: ?h=76.2&w=101.6&unit=cm&eps=0.5');
  ok(E.decodeQuery('?r=0.75&eps=1').ratio === 4 / 3,
    'a ratio below 1 is inverted rather than refused, because long over short is the measure');
  ok(E.decodeQuery('?r=1.5&eps=99').eps === 0.12 && E.decodeQuery('?r=1.5&eps=0').eps === 0.001,
    'a tolerance outside the supported range is clamped to it, not obeyed');
  ok(E.decodeQuery('?eps=1') === null && E.decodeQuery('') === null,
    'a link with no shape in it decodes to nothing, and the page falls back to its own example');
  ok(E.decodeQuery('?h=76.2&w=101.6&unit=furlongs&eps=0.5').unit === null,
    'an unknown unit is dropped rather than displayed as though it meant something');
  ok(E.decodeQuery('?h=0&w=10&eps=1') === null && E.decodeQuery('?r=-2&eps=1') === null,
    'a link carrying a zero or negative side decodes to nothing');

  // the page documents that grammar where a reader (or a model) can find it
  for (const p of ['?h=', '?r=', 'eps', 'unit']) {
    ok(page.includes(p), `the page's URL grammar block documents ${p}`);
  }
  ok(/<details class="hood" id="grammar">/.test(page), 'the grammar is in a details block on the page, not only in this file');
  ok(page.includes('/tools/canvas-ratio/?h=76.2&amp;w=101.6&amp;unit=cm&amp;eps=0.5'),
    'and it shows a working deep link a reader can copy');

  // WHAT THE GRAMMAR BLOCK CLAIMS ABOUT REFUSALS HAS TO BE WHAT IT DOES. It used
  // to say "refusals are linkable too", which was true of the three range
  // refusals and of none of the input refusals, because no parameter here
  // carries a string.
  {
    const linkable = ['above-range', 'window-past-range', 'neighbourhood-past-range', 'too-few-neighbours'];
    const fromURL = new Set();
    for (const q of ['?r=3.5&eps=0.5', '?r=2.995&eps=0.5', '?r=2.9&eps=0.5', '?r=1.5&eps=11']) {
      const s = E.decodeQuery(q);
      const a = E.assess(s.ratio, s.eps);
      if (!a.ok) fromURL.add(a.reason);
      else if (!a.percentile.ok) fromURL.add(a.percentile.reason);
    }
    ok(linkable.every((k) => fromURL.has(k)),
      `every refusal the page calls linkable really is reachable from a URL alone: ${[...fromURL].join(', ')}`);
    // and there is no parameter that could carry the string the other kind is about
    const params = [...page.matchAll(/<tr><td><code>([a-z]+)<\/code><\/td>/g)].map((m) => m[1]);
    ok(params.length === 5 && !params.includes('q') && !params.includes('text'),
      `the grammar table declares ${params.join(', ')} and nothing that carries typed text`);
    ok(!/refusals are linkable too/.test(page),
      'the sentence that claimed all refusals are linkable is gone from the page');
    ok(page.includes('a refusal about what you typed is not') && page.includes('empties the address bar'),
      'and the page says which refusals are linkable, which are not, and what it does with the address bar instead');
    ok(/function clearURL\(\)/.test(page) && /clearURL\(\);\n\s*return false;/.test(page),
      'which is code on the page and not only a promise: an unreadable box clears the query rather than leaving the previous answer in it');
    // And it is ONE gate rather than a rule each control remembers separately,
    // which is what let the tolerance slider walk around it.
    ok(/function applyState\(\)/.test(page) && !/el\('eps'\)\.addEventListener\('input', \(\) => \{\n\s*state\.eps = clampEps[^}]*syncURL\(\); render\(\);/.test(page),
      'every control goes through one gate: the slider calls applyState() rather than rendering on its own');
  }

  // the social card is this tool's own, not the site default
  {
    const card = ROOT + 'public/media/tool-canvas-ratio.png';
    ok(existsSync(card), 'the tool ships its own og card at public/media/tool-canvas-ratio.png');
    ok(page.includes('<meta property="og:image" content="https://artwaste.land/media/tool-canvas-ratio.png" />') &&
       page.includes('<meta property="og:image:width" content="1280" />') &&
       page.includes('<meta property="og:image:height" content="800" />'),
      'og:image points at it, at 1280 by 800');
    ok(page.includes('"image":"https://artwaste.land/media/tool-canvas-ratio.png"'),
      'and so does the JSON-LD block, so a card and a crawler see the same picture');
    ok(!/og:image" content="https:\/\/artwaste\.land\/og\/default\.png/.test(page),
      'the site-wide default card is no longer what this page offers');
    // the file really is a 2:1.6 image of that size, read out of the PNG header
    const png = readFileSync(card);
    const w = png.readUInt32BE(16), h = png.readUInt32BE(20);
    ok(png.subarray(1, 4).toString() === 'PNG' && w === 2560 && h === 1600,
      `and the file itself is a ${w} by ${h} PNG, exactly twice the size declared, so it is not upscaled`);
  }

  // house rules
  const prose = page.replace(/<!--[\s\S]*?-->/g, '');
  ok(!/[—–]/.test(prose), 'the page carries no em dashes and no en dashes (the house rule)');
  ok(!/[—–]/.test(readFileSync(LAB + 'ratio-engine.mjs', 'utf8')), 'nor does the engine it ships');
  ok(/rel="stylesheet" href="\/fonts\/fonts\.css"/.test(page), 'the page uses the site fonts');
  ok(/<link rel="canonical" href="https:\/\/artwaste\.land\/tools\/canvas-ratio\/"/.test(page), 'it carries its canonical URL');
  ok(/"@type":"WebApplication"/.test(page), 'and a WebApplication JSON-LD block');
  ok(/<script src="\/media\/home-banner\.js" defer><\/script>/.test(page), 'and the site banner');

  // the honesty the brief is built on, stated on the page and not only here
  const MUST_SAY = [
    ['never added together', 'that the four catalogues are never pooled'],
    ['is not a percentage of paintings', 'that a percentage of catalogued paintings is not a percentage of paintings'],
    ['whatever each catalogue recorded dimensions for', 'what "a painting" means here'],
    ['Aspect-ratio calculators are everywhere and free', 'that free aspect-ratio calculators already exist'],
    ['Fechner', 'Fechner 1876'],
    ['Trott', 'Trott 2015'],
    ['the instrument, not the finding', 'that the novelty claimed is the instrument, not the finding'],
    ['This tool is not that argument', 'that it is not running the stratum\'s golden-ratio argument'],
  ];
  for (const [needle, what] of MUST_SAY) ok(page.includes(needle), `the page states ${what}`);
  ok(page.includes('/strata/widen-the-window/'), 'and links to the stratum the data came from');

  // WHAT THE REFUSAL LIST PROMISES, THE PARSER HAS TO DO. Each sentence added to
  // that list is paired here with the string that makes it true, so the prose
  // cannot outlive the behaviour it describes.
  {
    const PROMISED = [
      ['Two sides measured on two different rulers', '30 in x 40 cm', 'mixed-units'],
      ['A label that contradicts itself', '24 x 36 in (61 x 61 cm)', 'ambiguous-multiple'],
      ['it does not depend on whether you separated the two with a comma or a semicolon', '30 x 40 cm, 50 x 60 cm', 'ambiguous-multiple'],
      ['A negative side', '-5 x 10', 'nonpositive'],
      ['answered only if the two readings agree to within one per cent', '30 x 43 in. (76.2 x 109.2 cm)', null],
    ];
    for (const [claim, text, reason] of PROMISED) {
      const r = E.parseInput(text);
      const holds = reason === null ? r.ok : (!r.ok && r.reason === reason);
      ok(page.includes(claim) && holds,
        `the page's claim "${claim}" is what "${text}" actually does (${r.ok ? r.ratio.toFixed(4) + ' : 1' : r.reason})`);
    }
    // and the two numbers that claim names are the arithmetic they say they are
    ok(page.includes('1.3333 : 1 where the truth is 1.9050') &&
       (76.2 / 40).toFixed(4) === '1.9050' && (30 / 40 < 1 ? 40 / 30 : 30 / 40).toFixed(4) === '1.3333',
      'and the wrong answer it names, 1.3333 against a true 1.9050, is exactly the arithmetic of reading 30 inches as 30 centimetres');
  }

  // Every citation on the page has to be one the repository already verified.
  // A URL typed from memory is the easiest way for a page like this to lie, so
  // no outbound link is allowed that is not in data/quotes.json.
  const quotes = JSON.parse(readFileSync(LAB + 'data/quotes.json', 'utf8'));
  const allowed = new Set(quotes.map((q) => q.url));
  const hrefs = [...page.matchAll(/href="(https?:[^"]+)"/g)].map((m) => m[1]);
  const stray = hrefs.filter((h) => !allowed.has(h) && !h.startsWith('https://artwaste.land'));
  ok(hrefs.length > 0 && stray.length === 0,
    `all ${hrefs.length} outbound links are URLs data/quotes.json records as fetched and checked` + (stray.length ? `; stray: ${stray.join(', ')}` : ''));
  ok(hrefs.includes(quotes.find((q) => q.id.startsWith('trott')).url) && hrefs.includes(quotes.find((q) => q.id.startsWith('green')).url),
    'and both prior-art claims link to the source the repository actually read');
  const joined = quotes.find((q) => q.id === 'trott-2015-not-joined');
  ok(page.includes(joined.text),
    'the one sentence quoted on this page is quoted verbatim from data/quotes.json, not paraphrased from memory');
  const green = quotes.find((q) => q.id.startsWith('green'));
  ok(page.includes('5:4 for tall pictures and 3:4 for wide ones') &&
     green.text.includes('a 5:4 ratio') && green.text.includes('a 3:4 ratio'),
    "and Fechner's result is reported in the ratios Green's summary actually gives, 5:4 and 3:4, not tidied up");
  ok(page.includes('943 to 944') && green.cite.includes('943 to 944'),
    'with the page reference the repository recorded when it read the paper');

  // The catalogue links the page renders come from the distillation report.
  const distil = JSON.parse(readFileSync(LAB + 'data/distil-report.json', 'utf8'));
  ok(META.catalogues.every((c) => (distil.corpora[c.key].source || '').startsWith(c.url)),
    'every catalogue link in catalogues.json is the URL the distillation actually pulled from');

  // Anything the page states as a figure in prose, rather than printing from a
  // file at runtime, is checked here against the artifact it came out of.
  const findings = JSON.parse(readFileSync(LAB + 'data/findings.json', 'utf8'));
  const audits = [
    ['aic', '99.57% agreement over 3,495 records'],
    ['met', '99.65% over 7,921'],
    ['nga', '100% over 4,176'],
  ];
  for (const [k, claim] of audits) {
    const a = distil.corpora[k].parserAudit;
    const rate = a.rate === 1 ? '100' : (a.rate * 100).toFixed(2);
    ok(page.includes(claim) && claim.includes(rate) && claim.includes(a.checked.toLocaleString('en-US')),
      `the ${k} parser audit the page quotes ("${claim}") is what distil-report.json records`);
  }
  ok(page.includes('98.27% and 99.28%') &&
     (distil.crossDatabaseAudit.met.rate * 100).toFixed(2) === '98.27' &&
     (distil.crossDatabaseAudit.nga.rate * 100).toFixed(2) === '99.28',
    'the cross-database agreement rates the page quotes are the ones in distil-report.json');

  {
    // The Metropolitan department split, counted here out of the record set.
    const text = zlib.gunzipSync(readFileSync(LAB + 'data/works-min.tsv.gz')).toString('utf8');
    let asian = 0, met = 0;
    for (const line of text.split('\n')) {
      if (!line.startsWith('met\t')) continue;
      met++;
      if (line.split('\t')[10] === 'Asian Art') asian++;
    }
    ok(page.includes('4,053 of its 8,324 usable paintings') && asian === 4053 && met === 8324,
      `the Metropolitan department split the page prints is a real count: ${asian.toLocaleString('en-US')} of ${met.toLocaleString('en-US')}`);
    ok(page.includes('<b>1.93</b>') && findings.traditions['Asian Art'].median.toFixed(2) === '1.93' &&
       page.includes('<b>1.32</b>') && findings.traditions['European Paintings'].median.toFixed(2) === '1.32',
      'and the two department medians it quotes are the ones in findings.json');
  }
  ok(page.includes('701 KB') && Math.round(statSync(TOOL + 'values.bin').size / 1024) === 701,
    'the file size the page quotes for its own measurements is the size of that file');
  ok(page.includes('1.4143') && (297 / 210).toFixed(4) === '1.4143' && Math.abs(297 / 210 - Math.SQRT2) < 1e-4,
    'the A4 figure the page quotes is what 210 by 297 mm actually is, and it is a rounding of root 2 rather than root 2');

  // the tool ships what it needs and nothing enormous
  for (const f of ['index.html', 'ratio-engine.mjs', 'parse.mjs', 'values.bin', 'catalogues.json']) {
    ok(existsSync(TOOL + f), `ships ${f} (${(statSync(TOOL + f).size / 1024).toFixed(0)} KB)`);
  }
  ok(statSync(TOOL + 'values.bin').size < 800 * 1024, 'the measurements are under 800 KB, small enough to load on a phone');
}

// ── family 7: the page a reader actually sees ───────────────────────────────
//
// Everything above this line drives the engine. A page can import that engine
// and still print something else: pass the wrong catalogue's array to a strip,
// multiply a count by ten, print a percentile assess() refused, and every check
// above stays green while every number a reader sees is wrong. So this family
// serves public/ over a real HTTP server, loads the tool in Chromium, and holds
// the rendered card against what the engine returns, catalogue by catalogue.
log.push('\n[7] a real browser loads the page and every number on it is the engine\'s:');
{
  const MIME = {
    '.html': 'text/html; charset=utf-8', '.mjs': 'text/javascript', '.js': 'text/javascript',
    '.json': 'application/json', '.bin': 'application/octet-stream', '.css': 'text/css',
    '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.woff': 'font/woff',
  };
  const server = http.createServer((req, res) => {
    let p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
    if (p.endsWith('/')) p += 'index.html';
    const file = ROOT + 'public' + p;
    if (!file.startsWith(ROOT + 'public/') || !existsSync(file) || !statSync(file).isFile()) {
      res.writeHead(404); res.end('not here'); return;
    }
    res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
    res.end(readFileSync(file));
  });
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
  const BASE = `http://127.0.0.1:${server.address().port}/tools/canvas-ratio/`;

  // The strip geometry, written out again here rather than imported from the
  // page, so that a change to the drawing shows up as a disagreement instead of
  // as a function agreeing with itself. Mirrors strip() in index.html.
  const barsFor = (v, t, eps) => {
    const W = 300, base = 38, pad = 1;
    const pts = E.profile(v, t, eps, E.NEIGHBOUR_SPAN, 121);
    let mx = 1;
    for (const p of pts) if (p.n !== null && p.n > mx) mx = p.n;
    const bw = (W - 2 * pad) / pts.length;
    const out = [];
    for (let i = 0; i < pts.length; i++) {
      if (pts[i].n === null) continue;
      const h = pts[i].n / mx * (base - 4);
      const mid = i === (pts.length - 1) / 2;
      out.push([(pad + i * bw).toFixed(2), (base - h).toFixed(2), (bw + 0.3).toFixed(2),
        Math.max(0.6, h).toFixed(2), mid ? '#ffc94a' : '#9aa0ab', mid ? '1' : '0.42'].join(' '));
    }
    return out;
  };

  const expectedCards = (t, eps) => {
    const a = E.assess(t, eps);
    return META.catalogues.map((c) => {
      const v = VALS[c.key];
      const n = E.countIn(v, t, eps), tot = E.totalIn(v);
      const p = a.percentile.ok ? E.neighbourPercentile(v, t, eps) : null;
      return {
        name: c.short,
        count: n.toLocaleString('en-US'),
        of: (n / tot * 100).toFixed(2) + '% of the ' + tot.toLocaleString('en-US') +
          ' in this catalogue between 1:1 and 3:1',
        pc: p === null
          ? 'no neighbour percentile here: ' + E.REFUSALS[a.percentile.reason]
          : 'more crowded than ' + (p * 100).toFixed(0) + '% of the ' + a.percentile.coverage.used +
            ' shapes within 12% either side' +
            (a.percentile.oneSided ? ', all of them above yours (nothing exists below 1:1)' : ''),
        bars: barsFor(v, t, eps),
        rects: barsFor(v, t, eps).length + 1 + (t * E.NEIGHBOUR_SPAN > E.HI ? 1 : 0),
      };
    });
  };

  const readCards = (pg) => pg.$$eval('#cats .cat', (nodes) => nodes.map((n) => ({
    name: n.querySelector('.nm').textContent,
    count: n.querySelector('.n span').textContent,
    of: n.querySelector('.of').textContent,
    pc: n.querySelector('.pc').textContent,
    refused: n.querySelector('.pc').classList.contains('no'),
    rects: [...n.querySelectorAll('svg rect')].map((r) =>
      [r.getAttribute('x'), r.getAttribute('y'), r.getAttribute('width'),
        r.getAttribute('height'), r.getAttribute('fill'), r.getAttribute('opacity')].join(' ')),
  })));

  const { chromium } = await import('playwright');
  const browser = await chromium.launch({ args: ['--no-sandbox'] });
  const ctx = await browser.newContext();
  try {
    // Three shapes, chosen because they exercise the three things the cards can
    // say: a percentile in full, a percentile refused, and a one-sided one.
    const CASES = [
      ['?h=76.2&w=101.6&unit=cm&eps=0.5', 4 / 3, 0.005, 'a 30 by 40 inch canvas given in centimetres'],
      ['?r=2.9&eps=0.5', 2.9, 0.005, 'a 2.9:1 shape, where the neighbour percentile is refused'],
      ['?r=1&eps=0.5', 1, 0.005, 'a square, where the neighbourhood is one-sided'],
      ['?r=1.618034&eps=1', 1.618034, 0.01, 'the golden ratio at a one per cent window'],
    ];
    for (const [query, t, eps, what] of CASES) {
      const pg = await ctx.newPage();
      await pg.goto(BASE + query, { waitUntil: 'load' });
      await pg.waitForSelector('#cats .cat', { timeout: 20000 });
      const shown = await readCards(pg);
      const want = expectedCards(t, eps);

      ok(shown.length === 4 && shown.every((s, i) => s.name === want[i].name),
        `${what}: four catalogue cards, named and ordered as catalogues.json has them`);
      const wrongCount = shown.filter((s, i) => s.count !== want[i].count);
      ok(wrongCount.length === 0,
        `  the four counts a reader sees are the engine's: ${shown.map((s) => s.count).join(' / ')}` +
        (wrongCount.length ? ` (want ${want.map((w) => w.count).join(' / ')})` : ''));
      ok(shown.every((s, i) => s.of === want[i].of),
        '  and each share-of-catalogue line is that count over that catalogue\'s encoded total');
      const wrongPc = shown.filter((s, i) => s.pc !== want[i].pc);
      ok(wrongPc.length === 0,
        `  the four neighbour lines are what assess() and neighbourPercentile() allow: "${shown[0].pc}"` +
        (wrongPc.length ? ` (want "${want[0].pc}")` : ''));
      ok(shown.every((s, i) => s.refused === (want[i].pc.startsWith('no neighbour'))),
        '  a refused percentile is marked refused on the card rather than printed as a number');
      const wrongBars = shown.filter((s, i) =>
        s.rects.length !== want[i].rects ||
        !want[i].bars.every((b, j) => s.rects[j] === b));
      ok(wrongBars.length === 0,
        `  and the four strips are ${want[0].bars.length} bars each of that catalogue's own window counts, drawn to the geometry the page documents` +
        (wrongBars.length ? ` (${wrongBars.length} of 4 differ)` : ''));

      const big = await pg.$eval('#answerBig', (n) => n.textContent);
      ok(big === t.toFixed(4) + ' : 1', `  the headline shape reads ${big}`);
      const hidden = await pg.$eval('#refusal', (n) => n.classList.contains('hidden'));
      ok(hidden, '  and no refusal is showing at the same time as an answer');
      await pg.close();
    }

    // THE SHARE BUTTON'S OWN LINK, opened. This is the reviewer's case: the
    // answer printed for a typed ratio, and the answer the link it writes prints.
    {
      const pg = await ctx.newPage();
      await pg.goto(BASE, { waitUntil: 'load' });
      await pg.waitForSelector('#cats .cat', { timeout: 20000 });
      await pg.fill('#dims', '31/24');
      await pg.waitForFunction(() => document.getElementById('answerBig').textContent.startsWith('1.2917'));
      const first = await readCards(pg);
      const href = await pg.evaluate(() => location.href);
      const pg2 = await ctx.newPage();
      await pg2.goto(href, { waitUntil: 'load' });
      await pg2.waitForSelector('#cats .cat', { timeout: 20000 });
      const second = await readCards(pg2);
      ok(first[3].count === '24,678',
        `typing 31/24 prints ${first[3].count} Wikidata paintings`);
      ok(href.includes('r=1.2916666666666667'),
        `and the link it writes carries the ratio at full precision: ${href.slice(href.indexOf('?'))}`);
      ok(second.every((s, i) => s.count === first[i].count && s.pc === first[i].pc),
        `and reopening that link prints the same four counts, ${second.map((s) => s.count).join(' / ')}, not a neighbouring answer`);
      await pg.close(); await pg2.close();
    }

    // THE FREE-FORM BOX, which is the only part of this a stranger touches.
    // Each of these used to print a confident wrong ratio and a permalink to it.
    {
      const TYPED = [
        ['30 in x 40 cm', 'mixed-units', '1.3333'],
        ['24 x 36 in (61 x 61 cm)', 'ambiguous-multiple', '1.0000'],
        ['30 x 40 cm, 50 x 60 cm', 'ambiguous-multiple', '1.3333'],
        ['-5 x 10', 'nonpositive', '2.0000'],
      ];
      const pg = await ctx.newPage();
      await pg.goto(BASE, { waitUntil: 'load' });
      await pg.waitForSelector('#cats .cat', { timeout: 20000 });
      for (const [text, reason, usedToSay] of TYPED) {
        await pg.fill('#dims', text);
        await pg.waitForFunction(() => !document.getElementById('refusal').classList.contains('hidden'), null, { timeout: 5000 })
          .catch(() => {});
        const seen = await pg.evaluate(() => ({
          refusing: !document.getElementById('refusal').classList.contains('hidden'),
          outHidden: document.getElementById('out').classList.contains('hidden'),
          sub: document.getElementById('refusalSub').textContent,
          big: document.getElementById('answerBig').textContent,
          search: location.search,
        }));
        ok(seen.refusing && seen.outHidden && seen.sub.includes(reason) && seen.sub.includes(E.INPUT_REFUSALS[reason]),
          `"${text}" is refused on the page as ${reason}, with the sentence written for it, and no counts shown`);
        ok(seen.search === '',
          `  and the address bar is emptied rather than left pointing at the previous answer (it used to write a link to ${usedToSay} : 1)`);
      }
      await pg.close();
    }

    // ⚠ THE SECOND PATH. A refusal must survive every OTHER control, not just the
    // one that produced it. Before this, typing an unreadable string refused
    // correctly and emptied the address bar, and then one nudge of the tolerance
    // slider brought the PREVIOUS rectangle's answer back and rewrote the
    // permalink to it: a link to a shape the reader was not being shown. The
    // second case needs no paste at all, because an intermediate keystroke of
    // "30 in x 40 cm" leaves a readable "30" behind.
    for (const [good, bad, note] of [
      ['76.2 x 101.6 cm', '30 in x 40 cm', 'a mixed-unit string after a good one'],
      ['', '30 in x 40 cm', 'a mixed-unit string typed from scratch'],
    ]) {
      const pg = await ctx.newPage();
      await pg.goto(BASE, { waitUntil: 'networkidle' });
      if (good) { await pg.fill('#dims', good); await pg.waitForTimeout(250); }
      await pg.fill('#dims', bad);
      await pg.waitForTimeout(250);
      const before = await pg.evaluate(() => ({
        refusing: !document.getElementById('refusal').classList.contains('hidden'),
        search: location.search,
      }));
      await pg.evaluate(() => {
        const e = document.getElementById('eps');
        e.value = String(Number(e.value) + 50);
        e.dispatchEvent(new Event('input', { bubbles: true }));
      });
      await pg.waitForTimeout(250);
      const after = await pg.evaluate(() => ({
        refusing: !document.getElementById('refusal').classList.contains('hidden'),
        outHidden: document.getElementById('status').classList.contains('hidden'),
        search: location.search,
      }));
      ok(before.refusing && after.refusing && after.outHidden,
        `the refusal survives a tolerance change (${note})`);
      ok(after.search === '',
        `  and the address bar stays empty rather than being rewritten to the shape before it (${note})`);
      await pg.close();
    }

    // The og card the page declares has to be a picture that exists on the site.
    {
      const pg = await ctx.newPage();
      const res = await pg.goto(BASE.replace('/tools/canvas-ratio/', '/media/tool-canvas-ratio.png'));
      ok(res.status() === 200 && (res.headers()['content-type'] || '').includes('image/png'),
        'the og:image the page declares is a PNG that is actually served at that path');
      await pg.close();
    }
  } finally {
    await browser.close();
    await new Promise((r) => server.close(r));
  }
}

console.log('CANVAS RATIO: offline verification of /tools/canvas-ratio/');
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('\nVERIFICATION FAILED'); process.exit(1); }
console.log('\nALL CHECKS PASS');
