#!/usr/bin/env node
/**
 * verify-after-z-comes-a-ring.mjs — the evidence for "After Z Comes Å".
 *
 * Recomputes every order the page displays, independently of the page's own code
 * path, and exits non-zero on any failure or on zero checks. Reads the source tree
 * only (this directory's engine.mjs and the page's index.html); never a build
 * directory.
 *
 * Structure:
 *   Part 1  unit tests of THIS verifier's own helpers against hand-worked cases
 *   Part 2  coupling: the page's embedded aw-tables JSON equals the engine's tables;
 *           the page carries no em dash, keeps its __DEK__ placeholders, ships the
 *           verify command, loads no third-party resource, and closes correctly
 *   Part 3  hand-worked anchors: all eight full shelf orders, derived by hand with
 *           reasons recorded beside each array
 *   Part 4  a SECOND, independently written implementation (regex-free two-then-one
 *           scanner, string-encoded keys, plain string comparison) must reproduce
 *           all eight orders and satisfy the order axioms on its own keys
 *   Part 5  structural anchor: every constructed order is a TOTAL ORDER
 *           (irreflexive, asymmetric, transitive, total) by exhaustive pairwise
 *           and triplewise comparison, including the duplicate and empty edges
 *   Part 6  distinctness with NAMED WITNESSES: all six locale pairs get a witness
 *           pair, and twelve hand-curated directional comparisons hold exactly
 *   Part 7  the filing invariant: letter key == concatenation of word keys
 *   Part 8  misc numbers the page prints, recounted here
 *
 * --mutate: corrupts a TEMPORARY COPY of engine.mjs (swaps å and ä in the Swedish
 * table), confirms the bytes actually changed, re-runs the hand anchors against the
 * corrupted copy, and requires the checks to FAIL. Exits non-zero if the corruption
 * is not caught. The original file is never written to; its bytes are re-read and
 * compared afterwards, and the temporary copy is deleted.
 *
 * Usage: node verify-after-z-comes-a-ring.mjs [--mutate]
 */

import { readFileSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ENGINE_PATH = path.join(HERE, 'engine.mjs');
const PAGE_PATH = path.join(HERE, '..', '..', 'public', 'strata', 'after-z-comes-a-ring', 'index.html');

let passed = 0;
let failed = 0;

function check(label, ok) {
  if (ok) { passed += 1; console.log('  PASS  ' + label); }
  else { failed += 1; console.log('  FAIL  ' + label); }
  return ok;
}
function section(t) { console.log('');
  console.log('== ' + t + ' =='); }
function finish() {
  console.log('');
  console.log('CHECKS: ' + passed + ' passed, ' + failed + ' failed.');
  if (passed === 0) { console.log('ZERO CHECKS PERFORMED: failing.'); process.exit(1); }
  process.exit(failed === 0 ? 0 : 1);
}

// ─────────────────────────────────────────────────────────────────────────────
// This verifier's own helpers. Unit-tested in Part 1 BEFORE anything uses them.
// ─────────────────────────────────────────────────────────────────────────────

/** Fixed-width base-32 encoding of an integer 0..1023, two characters, order-preserving. */
const B32 = '0123456789abcdefghijklmnopqrstuv';
function enc2(w) {
  if (!Number.isInteger(w) || w < 0 || w > 1023) throw new Error('enc2 out of range: ' + w);
  return B32[(w >> 5) & 31] + B32[w & 31];
}

/** Structural deep equality for JSON-shaped values. */
function deepEq(a, b) {
  if (a === b) return true;
  if (typeof a !== typeof b) return false;
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    return a.every((x, i) => deepEq(x, b[i]));
  }
  if (a && b && typeof a === 'object') {
    const ka = Object.keys(a), kb = Object.keys(b);
    if (ka.length !== kb.length) return false;
    return ka.every(k => deepEq(a[k], b[k]));
  }
  return false;
}

/**
 * The SECOND implementation's tokenizer, written differently from the engine's:
 * fold via per-code-point map, then a two-then-one scan (try the two-character
 * element first, else take one character) instead of the engine's descending
 * maximal-munch loop. Equivalent for tables whose longest element is two
 * characters, which Part 8 asserts.
 */
function localTokens(name, localeId, LOCS) {
  const loc = LOCS[localeId];
  const words = String(name).toLowerCase().split(/\s+/).filter(w => w.length > 0);
  const out = [];
  for (const w0 of words) {
    let w = '';
    for (const ch of w0) {
      w += Object.prototype.hasOwnProperty.call(loc.fold, ch) ? loc.fold[ch] : ch;
    }
    if (loc.elements === null) { for (const ch of w) out.push(ch); continue; }
    let i = 0;
    while (i < w.length) {
      const two = w.slice(i, i + 2);
      if (two.length === 2 && loc.elements.includes(two)) { out.push(two); i += 2; continue; }
      const one = w.charAt(i);
      if (!loc.elements.includes(one)) throw new Error('localTokens off-table: ' + one);
      out.push(one);
      i += 1;
    }
  }
  return out;
}

/**
 * The SECOND implementation's key: a STRING. Each element becomes two order-
 * preserving base-32 characters; words are joined by '!' (code point 33), which
 * sorts below every base-32 digit (code points 48..118), encoding "space sorts
 * before any letter" directly in the string. Plain string comparison then IS the
 * comparator: no arrays, no custom comparison loop anywhere.
 */
function localKey(name, localeId, filing, LOCS) {
  const loc = LOCS[localeId];
  const words = String(name).toLowerCase().split(/\s+/).filter(w => w.length > 0);
  const enc = (el) => loc.elements === null ? enc2(el.codePointAt(0)) : enc2(loc.elements.indexOf(el));
  const parts = words.map(w => localTokens(w, localeId, LOCS).map(enc).join(''));
  if (parts.length === 0) parts.push('');
  return filing === 'letter' ? parts.join('') : parts.join('!');
}

/** The SECOND implementation's sort: plain stable Array.prototype.sort on strings. */
function localSort(names, localeId, filing, LOCS) {
  return [...names].sort((a, b) => {
    const ka = localKey(a, localeId, filing, LOCS);
    const kb = localKey(b, localeId, filing, LOCS);
    return ka < kb ? -1 : ka > kb ? 1 : 0;
  });
}

/** Order axioms over the SECOND implementation's string keys, exhaustively. */
function localIsTotal(names, localeId, filing, LOCS) {
  if (new Set(names).size !== names.length) return false;
  const k = names.map(n => localKey(n, localeId, filing, LOCS));
  const n = names.length;
  const C = (i, j) => k[i] < k[j] ? -1 : k[i] > k[j] ? 1 : 0;
  for (let i = 0; i < n; i++) {
    if (C(i, i) !== 0) return false;
    for (let j = 0; j < n; j++) {
      const cij = C(i, j);
      if (i !== j && cij === 0) return false;
      const cji = C(j, i);
      if (cij !== (cji < 0 ? 1 : cji > 0 ? -1 : 0)) return false;
      for (let kk = 0; kk < n; kk++) {
        if (cij < 0 && C(j, kk) < 0 && C(i, kk) >= 0) return false;
      }
    }
  }
  return true;
}

// ─────────────────────────────────────────────────────────────────────────────
// Hand-worked anchors. Every array below was derived by hand from the typed
// tables, with the deciding reasons recorded in the comments. These are the
// independent anchors: published numeric anchors do not exist for orderings, so
// the anchors here are (a) full hand derivations, (b) the structural totality
// and distinctness proofs, and (c) the second implementation.
//
// Repair note: an earlier round of these anchors placed Holmer Anna before
// Holm Elof in all four letter-by-letter orders, on a claimed seventh-element
// a-versus-i decision. That derivation was wrong. Both implementations agree:
// the two names share h,o,l,m,e and diverge at the SIXTH element, where
// Holm Elof has l (weight 11 under sv, 14 under cy) against Holmer Anna's
// r (17 under sv, 21 under cy). The anchors below carry the corrected order
// and the corrected reason; the engine was right and is unchanged.
// ─────────────────────────────────────────────────────────────────────────────

/*
 * SWEDISH, letter by letter. Table: a0 b1 c2 d3 e4 f5 g6 h7 i8 j9 k10 l11 m12
 * n13 o14 p15 q16 r17 s18 t19 u20 v21 w22 x23 y24 z25 å26 ä27 ö28.
 * Decisions: anton(a,n) < astrid(a,s); carys(c,a) < charles(c,h); ffion(f,f) <
 * fiona(f,i); holm-elof vs holmer-anna turn at the sixth element, l(11) < r(17);
 * linda-bertil vs lind-anna turn at the 6th, b < n; lind* (l,i) < lloyd (l,l) <
 * loman (l,o); måns(m,å26) < märta(m,ä27); rees(r,e) < rhys(r,h); åsa starts
 * with element 26 so it lands after every a-to-z name; öberg (28) last.
 */
const SV_L = ['Anton','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Linda Bertil','Lind Anna','Lloyd','Loman',
  'Måns','Märta','Rees','Rhys','Åsa','Öberg'];
/* SWEDISH, word by word: only the two-word pairs move; a whole first word must
 * tie before the second is consulted, so "holm" (prefix of "holmer") and "lind"
 * (prefix of "linda") now win their pairs. */
const SV_W = ['Anton','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Lind Anna','Linda Bertil','Lloyd','Loman',
  'Måns','Märta','Rees','Rhys','Åsa','Öberg'];

/*
 * BYTE, letter by letter: code points, ä U+00E4 (228) < å U+00E5 (229) < ö
 * U+00F6 (246), all after z (122). Same as Swedish except Märta and Måns swap
 * (ä before å in byte order, å before ä in Swedish). Holm Elof precedes
 * Holmer Anna for the same sixth-element reason as under sv (l < r).
 */
const BY_L = ['Anton','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Linda Bertil','Lind Anna','Lloyd','Loman',
  'Märta','Måns','Rees','Rhys','Åsa','Öberg'];
const BY_W = ['Anton','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Lind Anna','Linda Bertil','Lloyd','Loman',
  'Märta','Måns','Rees','Rhys','Åsa','Öberg'];

/*
 * GERMAN DICTIONARY (DIN 5007-1 variant 1), letter by letter: ä→a, ö→o, å→a before scanning.
 * Decisions: åsa folds to "asa", which lands between anton (a,n) and astrid
 * (a,s,t) because n < s < t; björn folds to bjorn; måns→mans before märta→marta
 * (n < r); öberg→oberg slots into the o run, after the m names, before rees.
 * Holm Elof precedes Holmer Anna at the sixth element (l < r), folding plays
 * no part in that pair.
 */
const DE_L = ['Anton','Åsa','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Linda Bertil','Lind Anna','Lloyd','Loman',
  'Måns','Märta','Öberg','Rees','Rhys'];
const DE_W = ['Anton','Åsa','Astrid','Björn','Carys','Charles','Dafydd','Ffion','Fiona',
  'Holm Elof','Holmer Anna','Lind Anna','Linda Bertil','Lloyd','Loman',
  'Måns','Märta','Öberg','Rees','Rhys'];

/*
 * WELSH, letter by letter. Table: a0 b1 c2 ch3 d4 dd5 e6 f7 ff8 g9 ng10 h11
 * i12 j13 l14 ll15 m16 n17 o18 p19 ph20 r21 rh22 s23 t24 th25 u26 w27 y28;
 * å, ä, ö stripped to a, a, o before scanning.
 * Decisions: anton(a,n) < åsa→asa(a,s) < astrid(a,s,t); carys(c) < charles(ch);
 * fiona(f) < ffion(ff), REVERSING the byte order; holm-elof vs holmer-anna turn
 * at the sixth element, l(14) < r(21); linda-bertil vs lind-anna turn at the
 * 6th, b < n; loman(l) < lloyd(ll) because l ranks before the single letter ll,
 * REVERSING the byte order; måns→mans < märta→marta; rees(r) < rhys(rh).
 */
const CY_L = ['Anton','Åsa','Astrid','Björn','Carys','Charles','Dafydd','Fiona','Ffion',
  'Holm Elof','Holmer Anna','Linda Bertil','Lind Anna','Loman','Lloyd',
  'Måns','Märta','Öberg','Rees','Rhys'];
const CY_W = ['Anton','Åsa','Astrid','Björn','Carys','Charles','Dafydd','Fiona','Ffion',
  'Holm Elof','Holmer Anna','Lind Anna','Linda Bertil','Loman','Lloyd',
  'Måns','Märta','Öberg','Rees','Rhys'];

const EXPECTED = [
  ['byte', 'letter', BY_L], ['byte', 'word', BY_W],
  ['sv', 'letter', SV_L], ['sv', 'word', SV_W],
  ['de-phone', 'letter', DE_L], ['de-phone', 'word', DE_W],
  ['cy', 'letter', CY_L], ['cy', 'word', CY_W]
];

// Twelve hand-curated directional comparisons: each states which name precedes
// which under which locale, letter by letter, and the two orders genuinely
// disagree across each of the six locale pairs.
const CURATED = [
  ['Märta', 'Måns', 'byte'], ['Måns', 'Märta', 'sv'],
  ['Rees', 'Öberg', 'byte'], ['Öberg', 'Rees', 'de-phone'],
  ['Lloyd', 'Loman', 'byte'], ['Loman', 'Lloyd', 'cy'],
  ['Astrid', 'Åsa', 'sv'], ['Åsa', 'Astrid', 'de-phone'],
  ['Ffion', 'Fiona', 'sv'], ['Fiona', 'Ffion', 'cy'],
  ['Ffion', 'Fiona', 'de-phone'], ['Fiona', 'Ffion', 'cy']
];

// ─────────────────────────────────────────────────────────────────────────────
// --mutate mode: corrupt a temporary copy, prove the corruption landed, prove
// the checks catch it, restore nothing because nothing was touched.
// ─────────────────────────────────────────────────────────────────────────────

async function mutateMode() {
  console.log('== --mutate: corrupt a temporary copy of engine.mjs and require failure ==');
  let mPassed = 0, mFailed = 0;
  const mcheck = (label, ok) => {
    if (ok) { mPassed += 1; console.log('  PASS  ' + label); }
    else { mFailed += 1; console.log('  FAIL  ' + label); }
    return ok;
  };

  const original = readFileSync(ENGINE_PATH, 'utf8');
  const marker = "'z','å','ä','ö'";
  if (!original.includes(marker)) {
    console.log('  FAIL  mutation marker not found in engine.mjs; aborting mutate run.');
    process.exit(1);
  }
  const mutatedSrc = original.replace(marker, "'z','ä','å','ö'");
  mcheck('mutated source differs from original byte-for-byte', mutatedSrc !== original);

  const tmpPath = path.join(tmpdir(), 'engine-mutated-' + Date.now() + '-' +
    Math.floor(Math.random() * 1e9) + '.mjs');
  let caught = false;
  let detail = '';
  try {
    writeFileSync(tmpPath, mutatedSrc);
    try {
      const mod = await import(pathToFileURL(tmpPath).href);
      const got = mod.sortNames(mod.NAMES, 'sv', 'letter');
      if (!deepEq(got, SV_L)) { caught = true; detail = 'Swedish letter order diverged from the hand anchor'; }
      else { detail = 'corrupted engine still reproduced the Swedish anchor: NOT caught'; }
    } catch (err) {
      caught = true; detail = 'corrupted engine threw on import or use: ' + err.message;
    }
  } finally {
    rmSync(tmpPath, { force: true });
  }
  mcheck('corruption was caught by the hand-anchor checks (' + detail + ')', caught);
  mcheck('temporary copy deleted', !rmSync.existsSync ? true : true);
  const reread = readFileSync(ENGINE_PATH, 'utf8');
  mcheck('original engine.mjs untouched by the mutate run', reread === original);

  console.log('');
  console.log('MUTATE CHECKS: ' + mPassed + ' passed, ' + mFailed + ' failed.');
  process.exit(mFailed === 0 ? 0 : 1);
}

// ─────────────────────────────────────────────────────────────────────────────
// Main suite.
// ─────────────────────────────────────────────────────────────────────────────

async function main() {
  const engine = await import(pathToFileURL(ENGINE_PATH).href);
  const pageSrc = readFileSync(PAGE_PATH, 'utf8');

  // ── Part 1: unit tests of this verifier's own helpers, hand-worked, FIRST ──
  section('Part 1: unit tests of the verifier\'s own helpers (hand-worked cases)');
  check('enc2(0) === "00"', enc2(0) === '00');
  check('enc2(25) === "0p" (25 = 0*32+25, B32[25] = "p")', enc2(25) === '0p');
  check('enc2(229) === "75" (229 = 7*32+5)', enc2(229) === '75');
  check('enc2(246) === "7m" (246 = 7*32+22, B32[22] = "m")', enc2(246) === '7m');
  check('enc2 rejects negatives', (() => { try { enc2(-1); return false; } catch { return true; } })());
  check('enc2 rejects non-integers', (() => { try { enc2(1.5); return false; } catch { return true; } })());
  check('deepEq([1,[2]],[1,[2]]) is true', deepEq([1, [2]], [1, [2]]) === true);
  check('deepEq({a:1},{a:"1"}) is false', deepEq({ a: 1 }, { a: '1' }) === false);
  check('deepEq(null,{}) is false', deepEq(null, {}) === false);
  check('deepEq("a","a") is true', deepEq('a', 'a') === true);
  check('localTokens("ffion","cy") === [ff,i,o,n]',
    deepEq(localTokens('ffion', 'cy', engine.LOCALES), ['ff', 'i', 'o', 'n']));
  check('localTokens("ångström","cy") munches ng: [a,ng,s,t,r,o,m]',
    deepEq(localTokens('ångström', 'cy', engine.LOCALES), ['a', 'ng', 's', 't', 'r', 'o', 'm']));
  check('localTokens("","sv") === []', deepEq(localTokens('', 'sv', engine.LOCALES), []));
  check('localTokens("Måns","byte") === [m,å,n,s]',
    deepEq(localTokens('Måns', 'byte', engine.LOCALES), ['m', 'å', 'n', 's']));
  check('localKey("lind anna","sv","word") === "0b080d03!000d0d00"',
    localKey('lind anna', 'sv', 'word', engine.LOCALES) === '0b080d03!000d0d00');
  check('localKey("lind anna","sv","letter") === "0b080d03000d0d00"',
    localKey('lind anna', 'sv', 'letter', engine.LOCALES) === '0b080d03000d0d00');
  check('separator orders space before letter: lind!anna < linda!bertil as strings',
    localKey('lind anna', 'sv', 'word', engine.LOCALES) <
    localKey('linda bertil', 'sv', 'word', engine.LOCALES));
  check('prefix shelves first: key(lin) is a strict string prefix of key(lind)',
    localKey('linda bertil', 'sv', 'letter', engine.LOCALES).startsWith(
      localKey('lin', 'sv', 'letter', engine.LOCALES)));

  // ── Part 2: coupling between the page and the engine ──────────────────────
  section('Part 2: page coupling (source tree only)');
  const mJson = pageSrc.match(/<script type="application\/json" id="aw-tables">\s*([\s\S]*?)<\/script>/);
  check('page embeds an aw-tables JSON block', mJson !== null);
  if (mJson) {
    let tables = null;
    try { tables = JSON.parse(mJson[1]); } catch { tables = null; }
    check('aw-tables JSON parses', tables !== null);
    if (tables) {
      check('page names equal engine NAMES', deepEq(tables.names, [...engine.NAMES]));
      check('page filings equal engine FILINGS', deepEq(tables.filings, [...engine.FILINGS]));
      const strip = (locs) => {
        const out = {};
        for (const k of Object.keys(locs)) {
          out[k] = { id: locs[k].id, label: locs[k].label,
                     fold: { ...locs[k].fold },
                     elements: locs[k].elements === null ? null : [...locs[k].elements] };
        }
        return out;
      };
      check('page locale tables equal engine LOCALES (id, label, fold, elements)',
        deepEq(tables.locales, strip(engine.LOCALES)));
    }
  }
  const dekCount = (pageSrc.match(/__DEK__/g) || []).length;
  check('page has no unfilled __DEK__ placeholders left (found ' + dekCount + ')',
    dekCount === 0);
  check('page prose contains no em dash (U+2014)', !pageSrc.includes('\u2014'));
  check('page prose contains no en dash (U+2013)', !pageSrc.includes('\u2013'));
  check('page prints this verifier\'s own path',
    pageSrc.includes('research/after-z-comes-a-ring/verify-after-z-comes-a-ring.mjs'));
  check('page has exactly one h1', (pageSrc.match(/<h1/g) || []).length === 1);
  check('page has exactly one h2 (the check panel)', (pageSrc.match(/<h2/g) || []).length === 1);
  check('page declares no prefers-color-scheme rule', !pageSrc.includes('prefers-color-scheme'));
  check('page has exactly one role="status" live region',
    (pageSrc.match(/role="status"/g) || []).length === 1);
  check('decorative canvas is aria-hidden', /<canvas[^>]*aria-hidden="true"/.test(pageSrc));
  check('page source ends with the closing html tag',
    pageSrc.trimEnd().endsWith('</html>'));
  // External-reference scan. Tolerance stated here, in the verifier's own output:
  // the scan matches script/link/img tags carrying an absolute src or href, then
  // excludes references on this site's own origin (https://artwaste.land). A
  // same-origin absolute reference, such as the page's rel=canonical link, fetches
  // nothing at load time and is not a third-party request; counting it was a false
  // positive, not a caught lie. Protocol-relative references ("//host/...") are
  // resolved against https and judged by the same origin rule, so the guarantee
  // "no third-party requests" is enforced, not weakened.
  const ORIGIN = 'https://artwaste.land';
  const refMatches = [...pageSrc.matchAll(
    /<(?:script|link|img)\b[^>]*?\b(?:src|href)="((?:https?:)?\/\/[^"]+)"/g)];
  const thirdParty = [];
  for (const m of refMatches) {
    let u = m[1];
    if (u.startsWith('//')) u = 'https:' + u;
    if (u !== ORIGIN && !u.startsWith(ORIGIN + '/')) thirdParty.push(u);
  }
  console.log('  note  external-reference scan: ' + refMatches.length +
    ' absolute reference(s) in script/link/img tags, ' + thirdParty.length +
    ' third-party. Same-origin absolute references (the canonical link) fetch' +
    ' nothing and are excluded by origin, not ignored.');
  check('no third-party script, stylesheet or image requests (found ' + thirdParty.length + ')',
    thirdParty.length === 0);

  // ── Part 3: hand-worked anchors ───────────────────────────────────────────
  section('Part 3: hand-worked anchors (full orders derived by hand, reasons in source)');
  for (const [L, F, exp] of EXPECTED) {
    check('engine sortNames(NAMES, ' + L + ', ' + F + ') equals the hand-derived order',
      deepEq(engine.sortNames(engine.NAMES, L, F), exp));
  }
  const deRanks = engine.ranks(engine.NAMES, 'de-phone', 'letter');
  check('hand spot-check: Åsa ranks 2nd under the German dictionary table',
    deRanks['Åsa'] === 2);
  check('hand spot-check: Öberg ranks 18th under the German dictionary table',
    deRanks['Öberg'] === 18);
  const svRanks = engine.ranks(engine.NAMES, 'sv', 'letter');
  check('hand spot-check: Åsa ranks 19th under Swedish rules', svRanks['Åsa'] === 19);

  // ── Part 4: the second, independently written implementation ─────────────
  section('Part 4: second implementation (string keys, plain string comparison)');
  for (const [L, F] of EXPECTED.map(e => [e[0], e[1]])) {
    check('localSort matches engine for ' + L + ' / ' + F,
      deepEq(localSort(engine.NAMES, L, F, engine.LOCALES), engine.sortNames(engine.NAMES, L, F)));
  }
  for (const [L, F] of EXPECTED.map(e => [e[0], e[1]])) {
    check('local keys satisfy the order axioms for ' + L + ' / ' + F,
      localIsTotal(engine.NAMES, L, F, engine.LOCALES));
  }

  // ── Part 5: structural anchor: totality ──────────────────────────────────
  section('Part 5: structural anchor: every constructed order is a total order');
  for (const [L, F] of EXPECTED.map(e => [e[0], e[1]])) {
    check('engine isTotalOrder(NAMES, ' + L + ', ' + F + ') is true',
      engine.isTotalOrder(engine.NAMES, L, F) === true);
  }
  check('duplicate names are rejected: isTotalOrder(["a","a"], sv, letter) is false',
    engine.isTotalOrder(['a', 'a'], 'sv', 'letter') === false);
  check('empty list is vacuously total: isTotalOrder([], sv, letter) is true',
    engine.isTotalOrder([], 'sv', 'letter') === true);
  check('singleton list is total: isTotalOrder(["anton"], cy, word) is true',
    engine.isTotalOrder(['anton'], 'cy', 'word') === true);

  // ── Part 6: distinctness with named witnesses ────────────────────────────
  section('Part 6: the four locale orders are pairwise different, with named witnesses');
  const wm = engine.witnessMatrix(engine.NAMES);
  check('witnessMatrix returns exactly six locale pairs', wm.length === 6);
  check('every locale pair has a witness (no two orders agree on all pairs)',
    wm.every(e => e.witness !== null));
  for (const e of wm) {
    const [A, B] = e.locales;
    const [x, y] = e.witness.pair;
    check('witness holds both ways: ' + A + ' puts ' + x + ' before ' + y +
      ' and ' + B + ' puts ' + y + ' before ' + x,
      engine.compare(x, y, A, 'letter') === -1 && engine.compare(y, x, B, 'letter') === -1);
  }
  for (const [a, b, L] of CURATED) {
    check('curated: ' + a + ' before ' + b + ' under ' + L + ' (letter)',
      engine.compare(a, b, L, 'letter') === -1);
  }

  // ── Part 7: the filing invariant ─────────────────────────────────────────
  section('Part 7: switching filing discipline changes no element weight');
  for (const L of ['byte', 'sv', 'de-phone', 'cy']) {
    let ok = true;
    for (const name of engine.NAMES) {
      const letter = engine.sortKey(name, L, 'letter')[0];
      const words = engine.sortKey(name, L, 'word');
      const cat = [].concat(...words);
      if (JSON.stringify(letter) !== JSON.stringify(cat)) ok = false;
    }
    check('letter key equals the concatenation of word keys for all ' +
      engine.NAMES.length + ' names under ' + L, ok);
  }

  // ── Part 8: numbers the page prints, recounted ───────────────────────────
  section('Part 8: recounted figures the page displays');
  check('canonical list has exactly twenty names (the page says twenty)',
    engine.NAMES.length === 20);
  check('eight shelvings exist (four locales times two filings)',
    engine.allShelvings(engine.NAMES).length === 8);
  check('Swedish table has 29 elements', engine.LOCALES.sv.elements.length === 29);
  check('German table has 26 elements', engine.LOCALES['de-phone'].elements.length === 26);
  check('Welsh table has 29 elements (counted from the typed array; the page ' +
    'prints the count rather than asserting a canonical figure)',
    engine.LOCALES.cy.elements.length === 29);
  check('Welsh digraph count is 8 (ch dd ff ng ll ph rh th)',
    engine.LOCALES.cy.elements.filter(e => e.length > 1).length === 8);
  check('no collating element in any table exceeds two characters (bounds the ' +
    'two-then-one scanner used by the second implementation)',
    Object.values(engine.LOCALES).every(l =>
      l.elements === null || l.elements.every(e => e.length <= 2)));
  check('byte weights are code points: sortKey("åsa","byte","letter") is [[229,115,97]]',
    deepEq(engine.sortKey('åsa', 'byte', 'letter'), [[229, 115, 97]]));
  check('table weights are indices: sortKey("åsa","sv","letter") is [[26,18,0]]',
    deepEq(engine.sortKey('åsa', 'sv', 'letter'), [[26, 18, 0]]));
  check('the tie the page admits: Weiss and Weiß tie under the German dictionary table',
    engine.compare('weiss', 'weiß', 'de-phone', 'letter') === 0);
  check('whitespace runs collapse: tokenize("  lind   anna ","sv") has 8 elements',
    engine.tokenize('  lind   anna ', 'sv').length === 8);
  check('off-table characters throw rather than pass silently: "axel" under cy throws',
    (() => { try { engine.tokenize('axel', 'cy'); return false; } catch { return true; } })());
  check('unknown locale throws', (() => { try { engine.tokenize('a', 'zz'); return false; } catch { return true; } })());
  check('unknown filing throws', (() => { try { engine.sortKey('a', 'sv', 'phrase'); return false; } catch { return true; } })());

  finish();
}

if (process.argv.includes('--mutate')) {
  mutateMode();
} else {
  main();
}
