#!/usr/bin/env node
/*
 * Verifier for public/strata/on-the-border-of-carmania/.
 *
 *   node research/on-the-border-of-carmania/verify-on-the-border-of-carmania.mjs
 *   node research/on-the-border-of-carmania/verify-on-the-border-of-carmania.mjs --ledger
 *
 * It reads frozen files and writes nothing. It imports the page's own engine.js
 * and format.js, and drives the shipped page in headless Chromium.
 *
 *   census      the compact extract against the raw source CSVs, row by row
 *   anchor      named anchors, the aggregate, and the related-coordinate independence control
 *   fault       planted faults in copies of the record, rerun through the unmodified engine
 *   refuse      every refusal path, in the engine and in the page
 *   geometry    the buffered convex hull is a hull, and the base-rate grid equals a full scan
 *   choices     record.json, the page's controls and the engine agree; every option moves a declared output
 *   second      frontier, error, transfer, blank-list and circularity layers
 *   surface     static text in the shipped HTML, frontmatter and record against recomputed values
 *   render      rendered figures against the engine, after each control change, in a real browser
 *   provenance  hashes of every frozen file and of the manifest record.sha256 names
 *
 * --ledger prints the six contract cells, each computed from its assertion group.
 */

import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import {
  ALL_CONNECTION_TYPES,
  BUFFER_LIMITS,
  CHOICES,
  CIRCULARITY_ROWS,
  DEFAULT_CHOICES,
  ERROR_THRESHOLDS_KM,
  FAULT_PLANT,
  MATCH_TOLERANCE_DEGREES,
  NEIGHBOUR_CLASS_OPTIONS,
  PRECISION_CLASSES,
  RULES,
  SAME_SITE_KM2,
  SNAPSHOT_DATE,
  STAGE_DEFINITIONS,
  TYPE_PRESETS,
  anchorAudit,
  audit,
  blankDespitePrecise,
  bufferOutlineKm,
  cascadeCandidate,
  cascadeCandidates,
  choicePatch,
  circularityDemo,
  countPreciseInside,
  dataCensus,
  errorAudit,
  faultDemo,
  fromKm,
  frontier,
  graphNeighbors,
  makeDataset,
  namedAnchor,
  normaliseChoices,
  polygonAreaKm2,
  regionContains,
  regionFromNeighbors,
  relatedTargets,
  requestPlace,
  selectedRegion,
  transferSummary
} from '../../public/strata/on-the-border-of-carmania/engine.js';
import { area, choiceSummary, classPhrase, distance, integer, percent, pointText, ruleName, share } from '../../public/strata/on-the-border-of-carmania/format.js';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const SLUG = 'on-the-border-of-carmania';
const PUBLIC_ROOT = path.join(ROOT, 'public');
const PUBLIC_DIR = path.join(PUBLIC_ROOT, 'strata', SLUG);
const RESEARCH_DIR = path.join(ROOT, 'research', SLUG);
const DERIVED_DIR = path.join(RESEARCH_DIR, 'data', 'derived');
const HTML_PATH = path.join(PUBLIC_DIR, 'index.html');
const RECORD_PATH = path.join(PUBLIC_DIR, 'record.json');
const MANIFEST_PATH = path.join(PUBLIC_DIR, 'data', 'manifest.json');
const MD_PATH = path.join(ROOT, 'src', 'content', 'strata', `${SLUG}.md`);
const README_PATH = path.join(RESEARCH_DIR, 'README.md');
const LICENCE_PATH = path.join(PUBLIC_DIR, 'LICENCE.txt');
const PLACES_GZ = path.join(RESEARCH_DIR, 'data', 'pleiades-places-20260911.csv.gz');
const CONNECTIONS_CSV = path.join(RESEARCH_DIR, 'data', 'gis-connections-20260911.csv');
const TYPES_CSV = path.join(RESEARCH_DIR, 'data', 'gis-connection_types-20260911.csv');
const GIS_IDS = path.join(DERIVED_DIR, 'gis-place-ids-20260911.json');
const LEDGER_ONLY = process.argv.includes('--ledger');
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

const outcomes = [];
function check(name, value, details = '') {
  const pass = Boolean(value);
  outcomes.push({ name, pass, details: pass ? '' : details });
  return pass;
}

function readJson(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function sha256(filePath) {
  return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
}

function number(value) {
  return Number(value).toLocaleString('en-US');
}

function same(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

/* A quote-aware CSV reader, independent of the Python extractor. */
function parseCsv(text) {
  const rows = [];
  const n = text.length;
  let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
  let row = [];
  while (i < n) {
    let value;
    if (text[i] === '"') {
      const parts = [];
      let j = i + 1;
      for (;;) {
        const q = text.indexOf('"', j);
        if (q === -1) throw new Error('unterminated quoted field');
        if (text[q + 1] === '"') {
          parts.push(text.slice(j, q + 1));
          j = q + 2;
          continue;
        }
        parts.push(text.slice(j, q));
        i = q + 1;
        break;
      }
      value = parts.join('');
    } else {
      let j = i;
      while (j < n && text[j] !== ',' && text[j] !== '\n' && text[j] !== '\r') j += 1;
      value = text.slice(i, j);
      i = j;
    }
    row.push(value);
    if (text[i] === ',') {
      i += 1;
      if (i === n) row.push('');
      continue;
    }
    if (text[i] === '\r') i += 1;
    if (text[i] === '\n' || i >= n) {
      rows.push(row);
      row = [];
      i += 1;
    }
  }
  if (row.length) rows.push(row);
  return rows;
}

function csvObjects(text) {
  const [header, ...rows] = parseCsv(text);
  return rows.filter((row) => row.length > 1 || row[0] !== '').map((row) => Object.fromEntries(header.map((key, index) => [key, row[index]])));
}

function loadRaw() {
  const places = [];
  for (let index = 0; index < 5; index += 1) places.push(...readJson(path.join(DERIVED_DIR, `places-${index}.json`)));
  const extents = [];
  for (let index = 0; index < 4; index += 1) extents.push(...readJson(path.join(DERIVED_DIR, `extents-${index}.json`)));
  return {
    places,
    extents,
    edges: readJson(path.join(DERIVED_DIR, 'edges.json')),
    types: readJson(path.join(DERIVED_DIR, 'types.json')),
    meta: readJson(path.join(DERIVED_DIR, 'meta.json')),
    anchors: readJson(path.join(DERIVED_DIR, 'anchors.json'))
  };
}

function frontmatterValue(markdown, key) {
  const match = markdown.match(new RegExp(`^${key}: "([\\s\\S]*?)"$`, 'm'));
  return match ? match[1] : null;
}

function attr(html, selector) {
  const match = html.match(selector);
  return match ? match[1] : null;
}

function stripTags(fragment) {
  return fragment.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
}

function joinAnd(list) {
  return list.length < 2 ? list.join('') : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
}

function headlineText(result) {
  return `The admitted-neighbour rule places ${integer(result.inside)} of ${integer(result.eligible)} eligible known precise places inside its reconstructed regions, or ${percent(result.coverage)}. This page audits its own region rule rather than calling it Pleiades' algorithm.`;
}

/* ---------------------------------------------------------------- census */

function verifyCensus(raw, census) {
  const placeRows = csvObjects(zlib.gunzipSync(fs.readFileSync(PLACES_GZ)).toString('utf8'));
  const counts = {};
  for (const row of placeRows) counts[row.locationPrecision] = (counts[row.locationPrecision] || 0) + 1;
  check('census:raw-place-rows-equal-engine-census', placeRows.length === census.total &&
    Object.keys(counts).length === Object.keys(census.counts).length &&
    Object.entries(counts).every(([key, value]) => census.counts[key] === value), JSON.stringify({ raw: counts, engine: census.counts }));
  const num = (value) => (value === '' || value === undefined ? null : Number(value));
  let placeDiffs = raw.places.length === placeRows.length ? 0 : Infinity;
  if (placeDiffs === 0) {
    raw.places.forEach((row, index) => {
      const source = placeRows[index];
      if (row[0] !== source.id || row[1] !== source.title || row[2] !== source.locationPrecision ||
        row[3] !== num(source.reprLat) || row[4] !== num(source.reprLong) || row[5] !== source.authors) placeDiffs += 1;
    });
  }
  check('census:compact-places-equal-raw-csv', placeDiffs === 0, `${placeDiffs} rows differ`);

  const edgeRows = csvObjects(fs.readFileSync(CONNECTIONS_CSV, 'utf8'));
  const pid = (value) => String(value || '').replace(/\/+$/, '').split('/').pop();
  let edgeDiffs = raw.edges.length === edgeRows.length ? 0 : Infinity;
  if (edgeDiffs === 0) {
    raw.edges.forEach((edge, index) => {
      const source = edgeRows[index];
      if (edge[0] !== pid(source.place_id) || edge[1] !== pid(source.connects_to) || edge[2] !== source.connection_type) edgeDiffs += 1;
    });
  }
  check('census:compact-edges-equal-raw-csv', edgeDiffs === 0, `${edgeDiffs} rows differ`);
  const legacyIds = new Set(placeRows.map((row) => row.id));
  const endpointMisses = edgeRows.filter((row) => !legacyIds.has(pid(row.place_id)) || !legacyIds.has(pid(row.connects_to))).length;
  check('census:edge-endpoint-mismatches-recounted', census.edgeRows === edgeRows.length && census.mismatchedEdges === endpointMisses, `${endpointMisses}`);

  const typeRows = csvObjects(fs.readFileSync(TYPES_CSV, 'utf8'));
  check('census:types-equal-raw-csv', raw.types.length === typeRows.length &&
    raw.types.every((row, index) => same(row, [typeRows[index].key, typeRows[index].term, typeRows[index].definition, typeRows[index].uri])));
  const present = new Set(edgeRows.map((row) => row.connection_type));
  check('census:connection-types-present', present.size === ALL_CONNECTION_TYPES.length && ALL_CONNECTION_TYPES.every((type) => present.has(type)) &&
    census.edgeTypesPresent === present.size && census.typeDefinitions === typeRows.length &&
    same(census.typesWithoutEdges, typeRows.map((row) => row.key).filter((key) => !present.has(key))), JSON.stringify(census.typesWithoutEdges));
  const preciseWithPoint = placeRows.filter((row) => row.locationPrecision === 'precise' && row.reprLat !== '' && row.reprLong !== '').length;
  check('census:extents', census.precisePoints === preciseWithPoint && census.preciseExtentPlaces === raw.extents.length &&
    raw.meta.precise_extent_places === raw.extents.length && raw.extents.every((row) => row.length === 5));

  const gis = readJson(GIS_IDS);
  const gisIds = new Set(gis.map((row) => row[0]));
  const absent = placeRows.filter((row) => !gisIds.has(row.id));
  const split = { rough: 0, precise: 0, unlocated: 0, related: 0 };
  for (const row of absent) split[row.locationPrecision] = (split[row.locationPrecision] || 0) + 1;
  const gisOnly = gis.filter((row) => !legacyIds.has(row[0])).length;
  check('census:gis-places-gap-recounted', gisIds.size === gis.length && absent.length === Object.values(split).reduce((a, b) => a + b, 0), JSON.stringify(split));
  return { gap: { gisRows: gis.length, absent: absent.length, split, gisOnly }, placeRows, edgeRows };
}

/* ---------------------------------------------------------------- anchor */

function verifyAnchors(raw, dataset, census, anchors, record) {
  const printed = (id) => raw.anchors[id].reprPoint;
  check('anchor:lebadeia-engine-equals-printed', anchors.named.lebadeia.agrees &&
    anchors.named.lebadeia.computed.stage === 'physical' && anchors.named.lebadeia.computed.ids.length === 3 &&
    Math.abs(anchors.named.lebadeia.computed.x - printed('540907')[0]) < 1e-12 && Math.abs(anchors.named.lebadeia.computed.y - printed('540907')[1]) < 1e-12);
  check('anchor:acarnanian-engine-equals-printed', anchors.named.acarnanian.agrees &&
    anchors.named.acarnanian.computed.stage === 'regional' && anchors.named.acarnanian.computed.ids.length === 3 &&
    Math.abs(anchors.named.acarnanian.computed.x - printed('231467659')[0]) < 1e-12 && Math.abs(anchors.named.acarnanian.computed.y - printed('231467659')[1]) < 1e-12);
  check('anchor:aggregate-below-half-selects-fallback-wording', anchors.relatedShare !== null && anchors.relatedShare < 0.5 &&
    anchors.relatedPublished === relatedTargets(dataset).size, String(anchors.relatedShare));
  const geo = anchors.geometry;
  check('anchor:geometry-breakdown-sums', geo.point.candidates + geo.larger.candidates + geo['no-extent'].candidates === anchors.relatedCandidates &&
    geo.point.matches + geo.larger.matches + geo['no-extent'].matches === anchors.relatedWithinOneMicrodegree &&
    Object.values(anchors.stageCounts).reduce((a, b) => a + b, 0) === anchors.relatedCandidates);
  check('anchor:record-anchor-fields', record.anchor.expected === pointText({ x: printed('540907')[0], y: printed('540907')[1] }) &&
    record.anchor.computed === pointText(anchors.named.lebadeia.computed) && record.anchor.agrees === anchors.named.lebadeia.agrees);

  /* The independence control. Every related place's published coordinates are
     blanked in a copy of the record; the published targets are kept apart. The
     candidates must not move, so those coordinates are never engine inputs. */
  const targets = relatedTargets(dataset);
  const ids = Array.from(targets.keys());
  const clean = cascadeCandidates(dataset, ids);
  const blankRaw = structuredClone(raw);
  let blanked = 0;
  for (const row of blankRaw.places) {
    if (row[2] === 'related') {
      row[3] = null;
      row[4] = null;
      blanked += 1;
    }
  }
  const blankDataset = makeDataset(blankRaw);
  check('anchor:independence-copy-has-no-related-coordinates', blanked === census.counts.related && relatedTargets(blankDataset).size === 0 && targets.size > 0);
  check('anchor:independence-candidate-ids-stages-points-unchanged', same(cascadeCandidates(blankDataset, ids), clean) && clean.some((row) => row.stage !== null));
  const blankAudit = anchorAudit(blankDataset, targets);
  check('anchor:independence-aggregate-unchanged-against-kept-targets', blankAudit.relatedCandidates === anchors.relatedCandidates &&
    blankAudit.relatedWithinOneMicrodegree === anchors.relatedWithinOneMicrodegree && same(blankAudit.geometry, anchors.geometry) && same(blankAudit.stageMatches, anchors.stageMatches));
  check('anchor:independence-named-anchors-unchanged', same(namedAnchor(blankDataset, '540907'), anchors.named.lebadeia) && same(namedAnchor(blankDataset, '231467659'), anchors.named.acarnanian));
}

/* ---------------------------------------------------------------- fault */

function verifyFaults(raw, anchors) {
  check('fault:clean-anchor-closes', anchors.named.lebadeia.agrees);
  const movedRaw = structuredClone(raw);
  const movedRow = movedRaw.places.find((row) => row[0] === FAULT_PLANT.moved);
  movedRow[4] += FAULT_PLANT.dx;
  movedRow[3] += FAULT_PLANT.dy;
  const moved = namedAnchor(makeDataset(movedRaw), FAULT_PLANT.anchor);
  check('fault:moved-neighbour-coordinate-misses-anchor', Boolean(moved.computed) && !moved.agrees);
  const droppedRaw = structuredClone(raw);
  droppedRaw.edges = droppedRaw.edges.filter((edge) => !(edge[0] === FAULT_PLANT.moved && edge[1] === FAULT_PLANT.anchor && edge[2] === 'at'));
  check('fault:dropped-at-edge-misses-anchor', droppedRaw.edges.length === raw.edges.length - 1 && !namedAnchor(makeDataset(droppedRaw), FAULT_PLANT.anchor).agrees);
  const demo = faultDemo(makeDataset(raw));
  check('fault:page-demonstration-equals-planted-copy', demo.clean.agrees && !demo.doctored.agrees && pointText(demo.doctored.computed) === pointText(moved.computed));
  return { moved };
}

/* ---------------------------------------------------------------- refuse */

function verifyRefusals(dataset, census) {
  const parsika = selectedRegion(dataset, '30256', DEFAULT_CHOICES);
  check('refuse:parsika-box-from-one-precise-neighbour', !parsika.region.ok && parsika.region.code === 'too-few' && parsika.admittedNeighbors.length === 1);
  const unknown = requestPlace(dataset, '99999999999');
  const unknownRegion = selectedRegion(dataset, '99999999999', DEFAULT_CHOICES);
  check('refuse:outside-record-domain', !unknown.ok && unknown.code === 'not-in-snapshot' && unknown.reason.includes(SNAPSHOT_DATE) &&
    !unknownRegion.region.ok && unknownRegion.region.code === 'not-in-snapshot');
  const located = requestPlace(dataset, '570685');
  check('refuse:located-id-has-own-point', !located.ok && located.code === 'has-own-point');
  check('refuse:non-id-entry', requestPlace(dataset, 'Sparta').code === 'not-an-id' && requestPlace(dataset, '').code === 'not-an-id' &&
    requestPlace(dataset, 'https://pleiades.stoa.org/places/30256').ok);
  const none = audit(dataset, { neighborClasses: [] });
  check('refuse:no-admitted-neighbour-class', none.eligible === 0 && none.reachable === 0 && none.noAdmitted === census.counts.unlocated &&
    selectedRegion(dataset, '30256', { neighborClasses: [] }).region.code === 'no-admitted');

  const hull = normaliseChoices({ ...DEFAULT_CHOICES, rule: 'hull' });
  let collinear = null;
  for (const place of dataset.places.values()) {
    if (place.precision !== 'precise') continue;
    const neighbours = graphNeighbors(dataset, place.id, hull);
    const region = regionFromNeighbors(dataset, neighbours, hull);
    if (!region.ok && region.code === 'collinear') {
      collinear = { id: place.id, neighbours };
      break;
    }
  }
  check('refuse:collinear-unbuffered-hull', Boolean(collinear) &&
    regionFromNeighbors(dataset, collinear.neighbours, { ...hull, rule: 'buffered-hull' }).ok, collinear ? collinear.id : 'no collinear case found');

  const related = normaliseChoices({ truthClasses: ['related'] });
  const mixed = audit(dataset, { truthClasses: ['precise', 'related'] });
  check('refuse:related-truths-in-audit', related.truthClasses.length === 0 && same(related.refusedTruthClasses, ['related']) &&
    audit(dataset, { truthClasses: ['related'] }).truths === 0 && mixed.truths === audit(dataset, DEFAULT_CHOICES).truths);
  check('refuse:related-truths-only-in-labelled-circular-rows', CIRCULARITY_ROWS.filter((row) => row.truthClasses.includes('related')).every((row) => row.circular && /circular|related/.test(row.label)));

  const sources = ['data.js', 'engine.js', 'render.js', 'format.js'].map((name) => [name, fs.readFileSync(path.join(PUBLIC_DIR, name), 'utf8')]);
  const bad = [];
  for (const [name, source] of sources) {
    for (const api of ['XMLHttpRequest', 'sendBeacon', 'WebSocket', 'EventSource', 'importScripts', 'import(']) if (source.includes(api)) bad.push(`${name}: ${api}`);
    if (name !== 'data.js' && /\bfetch\s*\(/.test(source)) bad.push(`${name}: fetch`);
    for (const match of source.matchAll(/['"`]([a-z][a-z0-9+.-]*:\/\/[^'"`]*)['"`]/gi)) if (match[1] !== 'http://www.w3.org/2000/svg') bad.push(`${name}: ${match[1]}`);
    for (const match of source.matchAll(/\bfrom\s+['"]([^'"]+)['"]/g)) if (!match[1].startsWith('./')) bad.push(`${name}: import ${match[1]}`);
  }
  const dataJs = sources.find(([name]) => name === 'data.js')[1];
  const fetchPaths = Array.from(dataJs.matchAll(/['"](\.\/data\/[^'"]+)['"]/g)).map((match) => match[1]);
  check('refuse:no-live-request-in-page-code', bad.length === 0 && fetchPaths.length === 13 && fetchPaths.every((p) => fs.existsSync(path.join(PUBLIC_DIR, p))), bad.join(' | '));
}

/* ---------------------------------------------------------------- geometry */

function verifyGeometry(dataset) {
  const buffered = normaliseChoices({ ...DEFAULT_CHOICES, rule: 'buffered-hull', bufferKm: 50 });
  let witness = null;
  let disc = null;
  for (const place of dataset.places.values()) {
    if (place.precision !== 'precise') continue;
    const neighbours = graphNeighbors(dataset, place.id, buffered);
    const region = regionFromNeighbors(dataset, neighbours, buffered);
    if (!region.ok) continue;
    if (!witness && region.hullKm.length >= 3) witness = region;
    if (!disc && region.hullKm.length === 1) disc = region;
    if (witness && disc) break;
  }
  check('geometry:witnesses-found', Boolean(witness && disc));
  if (!witness || !disc) return;
  const r = witness.radiusKm;
  const corner = { x: witness.bbox[0], y: witness.bbox[1] };
  const inBox = corner.x >= witness.bbox[0] && corner.y >= witness.bbox[1];
  check('geometry:buffered-hull-excludes-its-bounding-box-corner', inBox && !regionContains(witness, corner));
  const hull = witness.hullKm;
  let edgeOk = true;
  for (let index = 0; index < hull.length; index += 1) {
    const a = hull[index];
    const b = hull[(index + 1) % hull.length];
    const length = Math.hypot(b.x - a.x, b.y - a.y);
    const normal = { x: (b.y - a.y) / length, y: -(b.x - a.x) / length };
    const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
    const near = fromKm(witness.projection, { x: mid.x + normal.x * r * 0.99, y: mid.y + normal.y * r * 0.99 });
    const far = fromKm(witness.projection, { x: mid.x + normal.x * r * 1.01, y: mid.y + normal.y * r * 1.01 });
    if (!regionContains(witness, near) || regionContains(witness, far)) edgeOk = false;
  }
  check('geometry:buffered-hull-boundary-is-radius-from-every-edge', edgeOk);
  const dense = polygonAreaKm2(bufferOutlineKm(hull, r, 720));
  check('geometry:buffered-area-equals-dense-outline', Math.abs(dense - witness.areaKm2) / witness.areaKm2 < 1e-4, `${dense} vs ${witness.areaKm2}`);
  check('geometry:one-point-buffer-is-a-disc', Math.abs(disc.areaKm2 - Math.PI * disc.radiusKm ** 2) < 1e-9 * disc.areaKm2);

  let compared = 0;
  let differ = 0;
  const probes = [
    normaliseChoices(DEFAULT_CHOICES),
    normaliseChoices({ ...DEFAULT_CHOICES, rule: 'hull' }),
    buffered,
    normaliseChoices({ ...DEFAULT_CHOICES, rule: 'buffered-hull', bufferKm: 500 })
  ];
  for (const choices of probes) {
    let taken = 0;
    let index = 0;
    for (const place of dataset.places.values()) {
      if (place.precision !== 'precise' || taken >= 60) continue;
      index += 1;
      if (index % 7) continue;
      const region = regionFromNeighbors(dataset, graphNeighbors(dataset, place.id, choices), choices);
      if (!region.ok) continue;
      taken += 1;
      const brute = dataset.precisePoints.reduce((sum, point) => sum + (regionContains(region, point) ? 1 : 0), 0);
      compared += 1;
      if (brute !== countPreciseInside(dataset, region)) differ += 1;
    }
  }
  check('geometry:base-rate-grid-count-equals-full-scan', compared >= 150 && differ === 0, `${differ} of ${compared}`);
}

/* ---------------------------------------------------------------- choices */

function selectOptions(html, id) {
  const match = html.match(new RegExp(`<select[^>]*id="${id}"[^>]*>([\\s\\S]*?)</select>`));
  if (!match) return null;
  return Array.from(match[1].matchAll(/<option([^>]*)>/g)).map((option) => ({
    value: (option[1].match(/value="([^"]*)"/) || [])[1],
    selected: /\bselected\b/.test(option[1]),
    disabled: /\bdisabled\b/.test(option[1])
  }));
}

function verifyChoices(dataset, html, record, renderSource) {
  const mirror = CHOICES.map(({ id, label, options, default: fallback, affects, inert, note }) => ({ id, label, options, default: fallback, affects, inert, ...(note ? { note } : {}) }));
  check('choices:record-json-equals-engine-declaration', same(record.choices, mirror));
  check('choices:every-declared-choice-has-two-options', CHOICES.every((choice) => choice.options.length >= 2 && choice.options.includes(choice.default) && typeof choice.inert === 'boolean'));

  const problems = [];
  for (const choice of CHOICES) {
    if (choice.control === 'bufferKm') {
      const tag = (html.match(/<input[^>]*id="bufferKm"[^>]*>/) || [''])[0];
      const min = Number(attr(tag, /min="([^"]*)"/));
      const max = Number(attr(tag, /max="([^"]*)"/));
      if (min !== BUFFER_LIMITS.min || max !== BUFFER_LIMITS.max || attr(tag, /value="([^"]*)"/) !== choice.default ||
        !choice.options.every((option) => Number(option) >= min && Number(option) <= max)) problems.push('bufferKm');
    } else if (choice.control === 'neighbourClasses') {
      const fieldset = (html.match(/<fieldset[^>]*id="neighbourClasses"[^>]*>([\s\S]*?)<\/fieldset>/) || [])[1] || '';
      const boxes = Array.from(fieldset.matchAll(/<input([^>]*)data-neighbor-class([^>]*)>/g)).map((m) => ({ value: attr(m[0], /value="([^"]*)"/), checked: /\bchecked\b/.test(m[0]) }));
      if (!same(boxes.map((box) => box.value), PRECISION_CLASSES) || !same(boxes.filter((box) => box.checked).map((box) => box.value), NEIGHBOUR_CLASS_OPTIONS[choice.default]) ||
        !choice.options.every((option) => NEIGHBOUR_CLASS_OPTIONS[option] && NEIGHBOUR_CLASS_OPTIONS[option].every((value) => PRECISION_CLASSES.includes(value)))) problems.push('neighbourClasses');
      if (!renderSource.includes('input[data-neighbor-class]')) problems.push('neighbourClasses not read by render.js');
    } else {
      const options = selectOptions(html, choice.control);
      if (!options) {
        problems.push(`${choice.control} missing`);
        continue;
      }
      const enabled = options.filter((option) => !option.disabled);
      const disabled = options.filter((option) => option.disabled).map((option) => option.value);
      const selected = options.filter((option) => option.selected).map((option) => option.value);
      if (!same(enabled.map((option) => option.value), choice.options)) problems.push(`${choice.control} options`);
      if (!same(selected, [choice.default])) problems.push(`${choice.control} default`);
      if (!same(disabled, choice.control === 'typePreset' ? ['custom'] : [])) problems.push(`${choice.control} disabled`);
      if (!renderSource.includes(`$('${choice.control}')`)) problems.push(`${choice.control} not read by render.js`);
    }
  }
  check('choices:page-controls-equal-declared-options', problems.length === 0, problems.join(' | '));

  const sample = audit(dataset, DEFAULT_CHOICES);
  check('choices:affects-name-real-outputs', CHOICES.every((choice) => choice.affects.every((key) => Object.prototype.hasOwnProperty.call(sample, key))));

  const inertMoves = [];
  for (const choice of CHOICES) {
    const baseline = audit(dataset, { ...DEFAULT_CHOICES, ...choicePatch(choice.id, choice.default) });
    for (const option of choice.options) {
      if (option === choice.default) continue;
      const result = audit(dataset, { ...DEFAULT_CHOICES, ...choicePatch(choice.id, option) });
      if (!choice.affects.some((key) => !same(result[key], baseline[key]))) inertMoves.push(`${choice.id}=${option}`);
    }
  }
  check('choices:every-option-moves-a-declared-output', inertMoves.length === 0, inertMoves.join(' | '));

  const clamp = (value) => normaliseChoices({ bufferKm: value }).bufferKm;
  check('choices:clamps-and-empty-sets-are-not-silent', clamp(0) === BUFFER_LIMITS.min && clamp(-3) === BUFFER_LIMITS.min && clamp(900) === BUFFER_LIMITS.max &&
    clamp('') === BUFFER_LIMITS.fallback && clamp('abc') === BUFFER_LIMITS.fallback && clamp(12.4) === 12 &&
    same(normaliseChoices({ neighborClasses: [] }).neighborClasses, []) && same(normaliseChoices({ types: [] }).types, []) &&
    normaliseChoices({ depth: 7 }).depth === 3);
}

/* ---------------------------------------------------------------- second layer */

function verifySecond(raw, dataset, census) {
  const base = normaliseChoices(DEFAULT_CHOICES);
  const rows = frontier(dataset, base, 'base');
  check('second:frontier-rows-are-the-three-rules', same(rows.map((row) => row.rule), RULES) && rows[0].result === audit(dataset, base));
  const alternatives = [
    { direction: 'inbound' },
    { neighborClasses: ['precise', 'related'] },
    { truthClasses: ['precise', 'rough'] },
    { bufferKm: 1 },
    { types: TYPE_PRESETS['stage-1'] }
  ];
  const stale = [];
  for (const patch of alternatives) {
    const choices = normaliseChoices({ ...DEFAULT_CHOICES, ...patch });
    const moved = frontier(dataset, choices, 'base');
    const follows = moved.every((row) => row.result === audit(dataset, { ...choices, rule: row.rule }));
    const changes = moved.some((row, index) => !same(row.result.inside, rows[index].result.inside) || !same(row.result.medianAreaKm2, rows[index].result.medianAreaKm2));
    if (!follows || !changes) stale.push(JSON.stringify(patch));
  }
  check('second:frontier-follows-every-base-choice', stale.length === 0, stale.join(' | '));
  const all = frontier(dataset, { ...base, types: [] }, 'all');
  check('second:frontier-type-selector-sets-only-types', all.every((row) => row.result === audit(dataset, { ...base, types: ALL_CONNECTION_TYPES, rule: row.rule })));

  const cascade = errorAudit(dataset, 'cascade', 'all');
  check('second:error-cascade-counts-consistent', cascade.n > 0 && cascade.n === Object.values(cascade.stageCounts).reduce((a, b) => a + b, 0) &&
    cascade.within1Km <= cascade.within10Km && cascade.within10Km <= cascade.within100Km && cascade.within100Km <= cascade.n && cascade.n <= census.precisePoints && Number.isFinite(cascade.medianKm));
  check('second:error-stage-modes-contain-first-firing-rows', STAGE_DEFINITIONS.every((stage) => errorAudit(dataset, 'cascade', stage.id).n >= (cascade.stageCounts[stage.id] || 0)));
  const mentioned = errorAudit(dataset, 'type', 'mentioned');
  check('second:error-zero-case-is-not-a-number', mentioned.n === 0 && mentioned.medianKm === null && share(mentioned.within1Km, mentioned.n) === 'not available');

  /* Held out means held out: plant a self-loop on sampled precise places and
     move their own points in a copy. Their candidates and regions must not move. */
  const sampleIds = [];
  const taken = new Set();
  for (const row of [...errorAudit(dataset, 'cascade', 'all').worst, ...Array.from(dataset.places.values()).filter((place) => place.precision === 'precise')]) {
    if (sampleIds.length >= 60) break;
    const candidate = cascadeCandidate(dataset, row.id);
    if (!candidate || taken.has(row.id) || candidate.ids.some((id) => taken.has(id))) continue;
    if (sampleIds.some((id) => (cascadeCandidate(dataset, id) || { ids: [] }).ids.includes(row.id))) continue;
    sampleIds.push(row.id);
    taken.add(row.id);
  }
  const heldRaw = structuredClone(raw);
  const sampleSet = new Set(sampleIds);
  for (const row of heldRaw.places) if (sampleSet.has(row[0])) { row[3] += 3; row[4] += 3; }
  for (const id of sampleIds) heldRaw.edges.push([id, id, 'at']);
  const heldDataset = makeDataset(heldRaw);
  const candidateMoves = sampleIds.filter((id) => !same(cascadeCandidate(heldDataset, id), cascadeCandidate(dataset, id)));
  const regionMoves = sampleIds.filter((id) => {
    const a = selectedRegion(heldDataset, id, base).region;
    const b = selectedRegion(dataset, id, base).region;
    return a.ok !== b.ok || (a.ok && !same(a.bbox, b.bbox));
  });
  check('second:held-out-place-never-feeds-its-own-candidate-or-region', sampleIds.length >= 50 && candidateMoves.length === 0 && regionMoves.length === 0,
    `${candidateMoves.length} candidates and ${regionMoves.length} regions moved`);

  const pid = (value) => value;
  const places = new Map(raw.places.map((row) => [row[0], row]));
  const located = (row) => row && row[2] !== 'unlocated' && row[3] !== null && row[4] !== null;
  const recountTransfer = (type) => {
    const hits = new Set();
    for (const edge of raw.edges) {
      if (type !== 'all' && edge[2] !== type) continue;
      const [a, b] = [pid(edge[0]), pid(edge[1])];
      if (a === b || !places.has(a) || !places.has(b)) continue;
      if (places.get(a)[2] === 'unlocated' && located(places.get(b))) hits.add(a);
      if (places.get(b)[2] === 'unlocated' && located(places.get(a))) hits.add(b);
    }
    return hits.size;
  };
  check('second:transfer-reach-recounted-from-raw-edges', ['all', 'at', 'part_of_regional', 'near'].every((type) => {
    const summary = transferSummary(dataset, type);
    return summary.reachableUnlocated === recountTransfer(type) && summary.heldOutN === errorAudit(dataset, 'type', type).n;
  }));
  const blankIds = new Set();
  for (const edge of raw.edges) {
    const [a, b] = edge;
    if (a === b || !places.has(a) || !places.has(b)) continue;
    const preciseRow = (row) => row[2] === 'precise' && row[3] !== null && row[4] !== null;
    if (places.get(a)[2] === 'unlocated' && preciseRow(places.get(b))) blankIds.add(a);
    if (places.get(b)[2] === 'unlocated' && preciseRow(places.get(a))) blankIds.add(b);
  }
  const blanks = blankDespitePrecise(dataset);
  check('second:blank-list-recounted-from-raw-edges', blanks.length === blankIds.size && blanks.every((place) => blankIds.has(place.id)) &&
    blankIds.has('303418080') && blankIds.has('613004963'));

  const demo = circularityDemo(dataset);
  const byId = Object.fromEntries(demo.map((row) => [row.id, row.result]));
  const withPoint = (classes) => raw.places.filter((row) => classes.includes(row[2]) && row[3] !== null && row[4] !== null).length;
  check('second:circularity-rows-count-their-truths', byId['related-truths'].truths === withPoint(['related']) &&
    byId['every-located'].truths === withPoint(['precise', 'rough', 'related']) && byId.headline === audit(dataset, DEFAULT_CHOICES));
  check('second:circularity-related-truths-inflate-coverage', byId['related-truths'].coverage > byId.headline.coverage);
}

/* ---------------------------------------------------------------- surface */

function visibleText(html) {
  const body = html.slice(html.indexOf('<body'));
  return body
    .replace(/<!--[\s\S]*?-->/g, ' ')
    .replace(/<script\b[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style\b[\s\S]*?<\/style>/gi, ' ')
    .replace(/<[^>]*\b(?:aria-label|placeholder|title|alt)="([^"]*)"[^>]*>/gi, ' $1 ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/\s+/g, ' ');
}

function verifySurface(ctx) {
  const { raw, dataset, census, anchors, gap, html, record, markdown, readme, licence, manifest } = ctx;
  const dek = frontmatterValue(markdown, 'dek');
  const plain = frontmatterValue(markdown, 'plain');
  const seoTitle = frontmatterValue(markdown, 'seoTitle');
  const poeticTitle = frontmatterValue(markdown, 'title');
  let ld = null;
  const ldMatch = html.match(/<script\s+type="application\/ld\+json">([\s\S]*?)<\/script>/i);
  try { ld = ldMatch ? JSON.parse(ldMatch[1]) : null; } catch { ld = null; }
  check('surface:json-ld-parses', Boolean(ld));
  check('surface:title', attr(html, /<title>([\s\S]*?)<\/title>/i) === seoTitle);
  check('surface:description', attr(html, /<meta\s+name="description"\s+content="([^"]*)"/i) === dek);
  check('surface:og-description', attr(html, /<meta\s+property="og:description"\s+content="([^"]*)"/i) === dek);
  check('surface:twitter-description', attr(html, /<meta\s+name="twitter:description"\s+content="([^"]*)"/i) === dek);
  check('surface:canonical', attr(html, /<link\s+rel="canonical"\s+href="([^"]*)"/i) === `https://artwaste.land/strata/${SLUG}/`);
  check('surface:og-and-twitter-image', attr(html, /<meta\s+property="og:image"\s+content="([^"]*)"/i) === `https://artwaste.land/og/${SLUG}.png` &&
    attr(html, /<meta\s+name="twitter:image"\s+content="([^"]*)"/i) === `https://artwaste.land/og/${SLUG}.png`);
  check('surface:plain-frontmatter-in-head', Boolean(plain) && html.includes(`<meta name="aw-plain" content="${plain}" />`));
  check('surface:json-ld-fields', Boolean(ld) && ld.name === seoTitle && ld.headline === poeticTitle && ld.description === dek &&
    ld.url === `https://artwaste.land/strata/${SLUG}/` && ld.image === `https://artwaste.land/og/${SLUG}.png`);
  check('surface:dek-body', html.includes(`<p class="dek">${dek}</p>`));
  check('surface:record-title-and-href', record.title === poeticTitle && record.href === `/strata/${SLUG}/` && record.slug === SLUG);
  check('surface:frontmatter-plain-length', typeof plain === 'string' && plain.length >= 90 && plain.length <= 420 && !plain.includes('—'));

  const [year, month, day] = raw.meta.source_snapshot.split('-');
  check('surface:static-census', raw.meta.source_snapshot === SNAPSHOT_DATE && dek.includes(`${Number(day)} ${MONTHS[Number(month) - 1]} ${year}`) &&
    dek.includes(`${number(census.total)} place records`) && dek.includes(`${number(census.counts.unlocated)} marked unlocated`) &&
    html.includes(`of ${number(census.counts.precise)} precise rows`) && html.includes(`share of all ${number(census.counts.precise)} precise published points`));
  const n = ALL_CONNECTION_TYPES.length;
  check('surface:static-type-counts', html.includes(`all ${n} types in the edge file`) && html.includes(`${n} of ${n} connection types admitted`) &&
    html.includes(`admit all ${n} types`) && html.includes(`These are the ${n} connection types that occur in the paired edge file`) &&
    html.includes(`The type vocabulary file defines ${census.typeDefinitions}; <span class="mono">${census.typesWithoutEdges[0]}</span> has no edge in this snapshot.`) &&
    html.includes(`(all ${n} types, both directions, one hop, axis-aligned box)`) && census.typesWithoutEdges.length === 1);
  const s = gap.split;
  check('surface:static-source-gap', html.includes(`${gap.absent} of the ${number(census.total)} legacy place ids are absent from the GIS package's own ${number(gap.gisRows)}-row places table (${s.rough} rough, ${s.precise} precise, ${s.unlocated} unlocated, ${s.related} related)`) &&
    html.includes(`${census.mismatchedEdges} of the ${number(census.edgeRows)} GIS edges have an endpoint absent from the legacy place table`) &&
    html.includes(`The legacy table's ${gap.absent} ids missing from the GIS places table`) && gap.gisOnly === 0);
  const cascadeText = stripTags((html.match(/<p id="cascadeDescription">([\s\S]*?)<\/p>/) || ['', ''])[1]);
  check('surface:static-cascade-stages-in-engine-order', STAGE_DEFINITIONS.every((stage, index) => {
    const phrase = stage.direction === 'both'
      ? `stage ${index + 1}, ${joinAnd(stage.types)} in both directions`
      : `stage ${index + 1}, ${stage.direction} ${joinAnd(stage.types)}`;
    return cascadeText.includes(phrase) && html.includes(`>stage ${index + 1}: ${stage.id}</option>`);
  }) && cascadeText.includes(`tries ${['one', 'two', 'three', 'four'][STAGE_DEFINITIONS.length - 1]} typed stages`) &&
    same(TYPE_PRESETS['location-bearing'], STAGE_DEFINITIONS.slice(0, 3).flatMap((stage) => stage.types)) && html.includes('>stages 1 to 3</option>'), cascadeText.slice(0, 200));
  const printed = (id) => `[${raw.anchors[id].reprPoint[0]}, ${raw.anchors[id].reprPoint[1]}]`;
  check('surface:static-anchor-lebadeia', html.includes(`Lebadeia</span> (540907) prints <span class="mono">${printed('540907')}</span>. Its three inbound <span class="mono">at</span> neighbours`) &&
    anchors.named.lebadeia.computed.ids.length === 3);
  check('surface:static-anchor-acarnanian', html.includes(`Acarnanian League</span> (231467659) prints <span class="mono">${printed('231467659')}</span>. Its three inbound <span class="mono">part_of_admin</span> members`) &&
    anchors.named.acarnanian.computed.ids.length === 3);
  const headlineResult = audit(dataset, DEFAULT_CHOICES);
  check('surface:headline', record.headline === headlineText(headlineResult) && html.includes(`<span id="headline">${record.headline}</span>`));

  const tomb = dataset.places.get('303418080');
  const sparta = dataset.places.get('570685');
  check('surface:static-blank-worked-case', html.includes('The Tomb of Castor (303418080) is one worked case: it links <span class="mono">at</span> to Sparta') &&
    tomb && tomb.precision === 'unlocated' && sparta && sparta.title === 'Sparta' && sparta.precision === 'precise' &&
    raw.edges.some((edge) => edge[0] === '303418080' && edge[1] === '570685' && edge[2] === 'at') &&
    blankDespitePrecise(dataset).some((place) => place.id === '303418080'));
  const parsikaEdges = raw.edges.filter((edge) => edge[0] === '30256' || edge[1] === '30256');
  const withRelated = selectedRegion(dataset, '30256', { neighborClasses: ['precise', 'related'] });
  check('surface:static-parsika-lede-and-try-this', dataset.places.get('30256').title.startsWith('Parsika') &&
    parsikaEdges.length === 2 && parsikaEdges.every((edge) => edge[0] === '30256' && edge[2] === 'bounds') &&
    dataset.places.get('29573').title === 'Gedrosia' && dataset.places.get('29573').precision === 'precise' &&
    dataset.places.get('29517').title === 'Carmania' && dataset.places.get('29517').precision === 'related' &&
    withRelated.region.ok && withRelated.region.kind === 'box' && withRelated.admittedNeighbors.length === 2 &&
    html.includes('only one of its two neighbours, Gedrosia, is precise') && html.includes('Carmania joins, a box appears'));

  /* Enumerate, do not match: every number in the page's visible text must be a
     value this verifier recomputes or a declared constant of the engine. */
  const text = visibleText(html);
  const dates = text.match(/\d{4}-\d{2}-\d{2}/g) || [];
  const allowedDates = new Set([raw.meta.source_snapshot, record.record.retrieved, manifest.retrieved]);
  check('surface:static-dates-are-snapshot-or-retrieval', dates.length > 0 && dates.every((date) => allowedDates.has(date)) && dates.includes(SNAPSHOT_DATE), dates.join(' '));
  const registry = new Map();
  const add = (token, why) => registry.set(String(token), [...(registry.get(String(token)) || []), why]);
  add(number(census.total), 'place rows');
  add(number(census.counts.unlocated), 'unlocated rows');
  add(number(census.counts.precise), 'precise rows');
  add(Number(day), 'snapshot day');
  add(year, 'snapshot year');
  add(n, 'connection types present');
  add(census.typeDefinitions, 'type definitions');
  add(gap.absent, 'legacy ids absent from GIS places');
  add(number(gap.gisRows), 'GIS places rows');
  for (const key of ['rough', 'precise', 'unlocated', 'related']) add(gap.split[key], `gap ${key}`);
  add(census.mismatchedEdges, 'edge endpoint mismatches');
  add(number(census.edgeRows), 'edge rows');
  for (const id of Object.keys(raw.anchors)) {
    add(id, 'anchor id');
    for (const value of raw.anchors[id].reprPoint) add(String(value), 'printed anchor coordinate');
  }
  add(number(headlineResult.inside), 'headline eligible-region matches');
  add(number(headlineResult.eligible), 'headline eligible precise places');
  add(Number(percent(headlineResult.coverage).replace('%', '')), 'headline coverage percent');
  add(BUFFER_LIMITS.min, 'buffer minimum');
  add(BUFFER_LIMITS.max, 'buffer maximum');
  STAGE_DEFINITIONS.forEach((_, index) => add(index + 1, 'stage number'));
  ERROR_THRESHOLDS_KM.forEach((value) => add(value, 'error threshold'));
  add(SAME_SITE_KM2, 'same-site threshold');
  add('303418080', 'blank-list worked case');
  add((record.record.licence.match(/\d+\.\d+/) || [''])[0], 'licence version');
  add((readme.match(/Ryan Horne, [^\n]*?(\d{4})-\d{2}-\d{2}/) || [])[1], 'Horne survey year');
  const locations = manifest.sources.find((source) => source.name.startsWith('pleiades-locations'));
  add((locations.bytes / 1e6).toFixed(1), 'locations export megabytes');
  const tokens = (text.replace(/\d{4}-\d{2}-\d{2}/g, ' ').match(/\d+(?:[.,]\d+)*/g)) || [];
  const unregistered = Array.from(new Set(tokens.filter((token) => !registry.has(token))));
  const unused = Array.from(registry.keys()).filter((token) => !tokens.includes(token));
  check('surface:static-numbers-enumerated', unregistered.length === 0 && unused.length === 0, `unregistered: ${unregistered.join(' ')}; registered but absent: ${unused.join(' ')}`);

  check('surface:closing-tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/i.test(html));
  const scripts = Array.from(html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi));
  check('surface:only-inline-script-is-json-ld', scripts.every((match) => /type="application\/ld\+json"/i.test(match[1]) || match[2].trim() === ''));
  const dashFiles = [...fs.readdirSync(PUBLIC_DIR).filter((name) => /\.(html|js|txt|json)$/.test(name)).map((name) => path.join(PUBLIC_DIR, name)), MD_PATH, README_PATH];
  check('surface:no-em-dash', dashFiles.every((file) => !fs.readFileSync(file, 'utf8').includes('—')));
  const josis = 'Hao Chen, Stephan Winter, and Maria Vasardani';
  check('surface:josis-author-order', readme.includes(josis) && licence.includes('Hao Chen, Stephan Winter, and Maria Vasardani') &&
    !readme.includes('Maria Vasardani, and Stephan Winter') && !licence.includes('Maria Vasardani, and Stephan Winter'));
}

/* ---------------------------------------------------------------- render */

const CONTENT_TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain' };

function serve() {
  const server = http.createServer((request, response) => {
    let requested = decodeURIComponent(request.url.split('?')[0]);
    if (requested.endsWith('/')) requested += 'index.html';
    const file = path.join(PUBLIC_ROOT, requested);
    if (!file.startsWith(PUBLIC_ROOT) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
      response.writeHead(404);
      response.end('not found');
      return;
    }
    response.writeHead(200, { 'Content-Type': CONTENT_TYPES[path.extname(file)] || 'application/octet-stream' });
    fs.createReadStream(file).pipe(response);
  });
  return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
}

async function ready(page) {
  await page.waitForFunction(() => ['ready', 'failed'].includes(document.documentElement.dataset.engineState), null, { timeout: 600000, polling: 100 });
  return page.evaluate(() => document.documentElement.dataset.engineState);
}

function texts(page, ids) {
  return page.evaluate((list) => Object.fromEntries(list.map((id) => {
    const element = document.getElementById(id);
    return [id, element ? element.textContent : null];
  })), ids);
}

function frontierRows(page) {
  return page.evaluate(() => Array.from(document.querySelectorAll('#frontier .frontier-row')).map((row) => ({ rule: row.dataset.rule, values: row.querySelector('.frontier-values').textContent })));
}

function expectedFrontier(rows) {
  return rows.map((row) => ({
    rule: row.rule,
    values: `${percent(row.result.coverage)} coverage of ${integer(row.result.eligible)} eligible · median ${area(row.result.medianAreaKm2)} · base rate ${percent(row.result.meanBaseRate)} · ${integer(row.result.sameSiteHits)} hits under 1 km²`
  }));
}

async function assertPanels(page, dataset, name, choices, frontierType) {
  const result = audit(dataset, choices);
  const t = await texts(page, ['baseCoverage', 'baseArea', 'baseRate', 'baseSameSite', 'baseCoverageDetail', 'reach', 'choiceReadout', 'heldOutStatus']);
  const detail = `${integer(result.inside)} inside of ${integer(result.eligible)} eligible ${classPhrase(result.truthClasses)} truths; ${integer(result.refused)} refused`;
  const reach = [`${integer(result.reachable)} of ${integer(result.unlocated)} unlocated records`, `${integer(result.noAdmitted)} have none`, `${integer(result.withRegion)} have a usable region`];
  check(`render:${name}:held-out-figures-equal-engine`, t.baseCoverage === percent(result.coverage) && t.baseArea === area(result.medianAreaKm2) &&
    t.baseRate === percent(result.meanBaseRate) && t.baseSameSite === integer(result.sameSiteHits) && t.baseCoverageDetail.includes(detail) &&
    reach.every((part) => t.reach.includes(part)) && t.heldOutStatus.includes(`${percent(result.coverage)} coverage of ${integer(result.eligible)} eligible`), JSON.stringify(t));
  const rows = await frontierRows(page);
  const want = expectedFrontier(frontier(dataset, choices, frontierType));
  check(`render:${name}:frontier-equals-engine-for-current-controls`, same(rows, want), JSON.stringify({ rows, want }));
  check(`render:${name}:choice-readout`, t.choiceReadout === choiceSummary(choices, choices.types.length), t.choiceReadout);
  return rows;
}

async function assertSelected(page, dataset, name, id, choices) {
  const selected = selectedRegion(dataset, id, choices);
  const t = await texts(page, ['graphCount', 'graphDrawn', 'admittedCount', 'regionShape', 'regionArea', 'baseStatus']);
  const value = await page.inputValue('#placeSelect');
  check(`render:${name}:selected-record-equals-engine`, value === id && t.graphCount === integer(selected.graphNeighbors.length) &&
    t.graphDrawn.startsWith(`${integer(selected.drawableNeighbors.length)} with coordinates`) && t.admittedCount === integer(selected.admittedNeighbors.length) &&
    t.regionShape === (selected.region.ok ? ruleName(selected.region.kind) : 'refused') &&
    t.regionArea === (selected.region.ok ? area(selected.region.areaKm2) : 'no region') &&
    t.baseStatus.includes(selected.region.ok ? area(selected.region.areaKm2) : selected.region.reason), JSON.stringify({ value, t }));
  return selected;
}

async function driveDesktop(browser, origin, ctx) {
  const { dataset, census, anchors, faults, dek } = ctx;
  const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
  const page = await context.newPage();
  const errors = [];
  const requests = [];
  page.on('pageerror', (error) => errors.push(`pageerror ${error.message}`));
  page.on('console', (message) => { if (message.type() === 'error') errors.push(`console ${message.text()}`); });
  page.on('request', (request) => requests.push(request.url()));
  await page.goto(`${origin}/strata/${SLUG}/`, { waitUntil: 'load', timeout: 120000 });
  check('render:initial:engine-ready', (await ready(page)) === 'ready');
  const visibleDek = await page.locator('p.dek').textContent();
  check('render:initial:visible-dek-equals-frontmatter', await page.locator('p.dek').isVisible() && visibleDek === dek, JSON.stringify({ visibleDek, dek }));

  const defaults = normaliseChoices(DEFAULT_CHOICES);
  const initialRows = await assertPanels(page, dataset, 'initial', defaults, 'base');
  await assertSelected(page, dataset, 'initial', '30256', defaults);
  const t = await texts(page, ['sourceRows', 'sourceUnlocated', 'sourceEdges', 'censusReadout', 'snapshotStatus', 'anchorEngine', 'aggregateMatch', 'stageMatches', 'headline', 'anchorReadout', 'faultNote', 'blankCount', 'errorN', 'errorMedian', 'error1', 'error10', 'error100', 'transferReach', 'transferMedian', 'typeSummary', 'placeCount']);
  const geo = anchors.geometry;
  const cascade = errorAudit(dataset, 'cascade', 'all');
  const transfer = transferSummary(dataset, 'all');
  const demo = faultDemo(dataset);
  check('render:initial:census-and-check-panel', t.sourceRows === integer(census.total) && t.sourceUnlocated === integer(census.counts.unlocated) && t.sourceEdges === integer(census.edgeRows) &&
    t.censusReadout.includes(`${integer(census.counts.precise)} precise, ${integer(census.counts.rough)} rough, ${integer(census.counts.related)} related, ${integer(census.counts.unlocated)} unlocated`) &&
    t.snapshotStatus.includes(`${integer(census.edgeRows)} GIS edges in ${integer(census.edgeTypesPresent)} connection types (the type file defines ${integer(census.typeDefinitions)}; ${census.typesWithoutEdges.join(', ')} without an edge), ${integer(census.preciseExtentPlaces)} precise place extents, and ${integer(census.mismatchedEdges)} of ${integer(census.edgeRows)} edges`) &&
    t.placeCount.startsWith(`${integer(census.counts.unlocated)} unlocated records`) && t.typeSummary === `${ALL_CONNECTION_TYPES.length} of ${ALL_CONNECTION_TYPES.length} connection types admitted`, JSON.stringify(t));
  check('render:initial:anchor-panel-equals-engine', t.anchorEngine === `Engine: Lebadeia ${pointText(anchors.named.lebadeia.computed)}; Acarnanian League ${pointText(anchors.named.acarnanian.computed)}.` &&
    t.aggregateMatch.startsWith(`${integer(anchors.relatedWithinOneMicrodegree)} of ${integer(anchors.relatedCandidates)} related records`) &&
    t.aggregateMatch.includes(`(${percent(anchors.relatedShare)}); ${integer(anchors.relatedNoCandidate)} of ${integer(anchors.relatedPublished)} get no candidate`) &&
    t.aggregateMatch.includes(`single-point extent, ${integer(geo.point.matches)} of ${integer(geo.point.candidates)} match; where any has a larger extent, ${integer(geo.larger.matches)} of ${integer(geo.larger.candidates)} match`) &&
    ['physical', 'regional', 'network', 'membership', 'fallback'].every((stage) => t.stageMatches.includes(`${stage} ${integer(anchors.stageMatches[stage] || 0)} of ${integer(anchors.stageCounts[stage] || 0)}`)) &&
    t.headline === headlineText(audit(dataset, defaults)) && t.anchorReadout === 'Lebadeia agrees with the printed point; Acarnanian League agrees.', JSON.stringify(t));
  check('fault:page-shows-doctored-copy-missing', t.faultNote.includes(`Doctored copy: ${pointText(faults.moved.computed)}, which does not agree`) &&
    t.faultNote.includes(`Clean record: ${pointText(demo.clean.computed)}, which agrees`), t.faultNote);
  check('render:initial:second-layer-panels-equal-engine', t.blankCount === integer(blankDespitePrecise(dataset).length) &&
    t.errorN === integer(cascade.n) && t.errorMedian === distance(cascade.medianKm) && t.error1 === share(cascade.within1Km, cascade.n) &&
    t.error10 === share(cascade.within10Km, cascade.n) && t.error100 === share(cascade.within100Km, cascade.n) &&
    t.transferReach === integer(transfer.reachableUnlocated) && t.transferMedian === distance(transfer.heldOutMedianKm), JSON.stringify(t));

  await page.check('input[data-neighbor-class][value="related"]');
  await ready(page);
  const withRelated = normaliseChoices({ ...DEFAULT_CHOICES, neighborClasses: ['precise', 'related'] });
  await assertPanels(page, dataset, 'related-neighbours', withRelated, 'base');
  const tryThis = await assertSelected(page, dataset, 'related-neighbours', '30256', withRelated);
  check('render:try-this-first-box-appears-with-warning', tryThis.region.ok && await page.evaluate(() => !document.getElementById('circularWarning').hidden));

  await page.uncheck('input[data-neighbor-class][value="precise"]');
  await ready(page);
  await page.uncheck('input[data-neighbor-class][value="related"]');
  await ready(page);
  const noClass = normaliseChoices({ ...DEFAULT_CHOICES, neighborClasses: [] });
  const emptyRows = await assertPanels(page, dataset, 'no-neighbour-class', noClass, 'base');
  const emptySelected = await assertSelected(page, dataset, 'no-neighbour-class', '30256', noClass);
  const emptyTexts = await texts(page, ['neighbourNote', 'baseCoverage']);
  const checked = await page.evaluate(() => document.querySelectorAll('input[data-neighbor-class]:checked').length);
  check('choices:ui-no-neighbour-class-is-not-silently-precise', checked === 0 && emptySelected.region.code === 'no-admitted' &&
    emptyTexts.neighbourNote.includes('No neighbour class is admitted') && emptyTexts.baseCoverage === 'not available', JSON.stringify(emptyTexts));
  check('render:frontier-is-not-stale-after-a-base-change', !same(emptyRows, initialRows) && emptyRows.length === 3);

  await page.check('input[data-neighbor-class][value="precise"]');
  await ready(page);
  await page.selectOption('#regionRule', 'buffered-hull');
  await ready(page);
  await page.fill('#bufferKm', '0');
  await page.press('#bufferKm', 'Tab');
  await ready(page);
  const oneKm = normaliseChoices({ ...DEFAULT_CHOICES, rule: 'buffered-hull', bufferKm: 1 });
  check('choices:ui-buffer-zero-clamps-to-declared-minimum', (await page.inputValue('#bufferKm')) === String(BUFFER_LIMITS.min) &&
    (await texts(page, ['choiceReadout'])).choiceReadout.includes(`buffered convex hull of ${BUFFER_LIMITS.min} km`));
  await assertPanels(page, dataset, 'buffer-1-km', oneKm, 'base');
  await assertSelected(page, dataset, 'buffer-1-km', '30256', oneKm);
  const polygonPoints = await page.evaluate(() => (document.querySelector('#graph polygon') || { getAttribute: () => '' }).getAttribute('points').trim().split(/\s+/).length);
  check('render:buffered-outline-is-drawn-as-a-hull-not-a-box', polygonPoints > 4, String(polygonPoints));

  await page.selectOption('#direction', 'inbound');
  await ready(page);
  const inbound = normaliseChoices({ ...oneKm, direction: 'inbound' });
  await assertPanels(page, dataset, 'inbound', inbound, 'base');

  await page.click('details > summary');
  await page.click('#clearTypes');
  await ready(page);
  const noTypes = normaliseChoices({ ...inbound, types: [] });
  const noTypeRows = await assertPanels(page, dataset, 'no-types', noTypes, 'base');
  const summary = await texts(page, ['typeSummary']);
  check('render:clear-types-empties-base-and-frontier', (await page.inputValue('#typePreset')) === 'custom' &&
    summary.typeSummary === `0 of ${ALL_CONNECTION_TYPES.length} connection types admitted, a custom subset` &&
    noTypeRows.every((row) => row.values.includes('coverage of 0 eligible')), JSON.stringify(summary));

  await page.selectOption('#frontierType', 'all');
  await ready(page);
  await assertPanels(page, dataset, 'frontier-all-types', noTypes, 'all');

  await page.selectOption('#typePreset', 'stage-1');
  await ready(page);
  const stageOne = normaliseChoices({ ...inbound, types: TYPE_PRESETS['stage-1'] });
  await assertPanels(page, dataset, 'stage-1-preset', stageOne, 'all');

  const lookUp = async (value) => {
    await page.fill('#placeId', value);
    await page.click('#placeIdForm button[type="submit"]');
    await ready(page);
    return (await texts(page, ['placeIdStatus'])).placeIdStatus;
  };
  const unknownText = await lookUp('99999999999');
  check('refuse:ui-id-outside-snapshot', unknownText === `Refused: ${requestPlace(dataset, '99999999999').reason} The selection is unchanged.` && (await page.inputValue('#placeSelect')) === '30256', unknownText);
  const locatedText = await lookUp('570685');
  check('refuse:ui-located-id', locatedText === `Refused: ${requestPlace(dataset, '570685').reason} The selection is unchanged.`, locatedText);
  const tombText = await lookUp('303418080');
  check('render:ui-lookup-selects-unlocated-id', tombText.startsWith('Selected ') && tombText.includes('303418080'), tombText);
  await assertSelected(page, dataset, 'lookup-tomb-of-castor', '303418080', stageOne);

  await page.click('#runCircular');
  await ready(page);
  const circular = await page.evaluate(() => Array.from(document.querySelectorAll('#circularRows tr')).map((row) => Array.from(row.children).map((cell) => cell.textContent)));
  const wantCircular = circularityDemo(dataset).map((row) => [row.label, integer(row.result.truths), integer(row.result.eligible), percent(row.result.coverage), area(row.result.medianAreaKm2)]);
  check('render:circularity-rows-equal-engine', same(circular, wantCircular), JSON.stringify(circular));

  await page.selectOption('#errorMode', 'type');
  await page.selectOption('#errorType', 'mentioned');
  const zero = await texts(page, ['errorN', 'errorMedian', 'error1']);
  check('render:error-zero-case-prints-not-available', zero.errorN === '0' && zero.errorMedian === 'not available' && zero.error1 === 'not available', JSON.stringify(zero));
  await page.selectOption('#errorType', 'at');
  const atError = errorAudit(dataset, 'type', 'at');
  const atTexts = await texts(page, ['errorN', 'errorMedian', 'error100']);
  check('render:error-type-at-equals-engine', atTexts.errorN === integer(atError.n) && atTexts.errorMedian === distance(atError.medianKm) && atTexts.error100 === share(atError.within100Km, atError.n), JSON.stringify(atTexts));
  await page.selectOption('#transferType', 'at');
  const atTransfer = transferSummary(dataset, 'at');
  const transferTexts = await texts(page, ['transferReach', 'transferMedian']);
  check('render:transfer-type-at-equals-engine', transferTexts.transferReach === integer(atTransfer.reachableUnlocated) && transferTexts.transferMedian === distance(atTransfer.heldOutMedianKm), JSON.stringify(transferTexts));

  check('render:no-page-or-console-errors', errors.length === 0, errors.join(' | '));
  check('refuse:ui-browser-requests-stay-local', requests.length > 0 && requests.every((url) => url.startsWith(origin) || url.startsWith('data:')), requests.filter((url) => !url.startsWith(origin)).join(' '));
  await context.close();
}

async function measureNarrow(browser, origin) {
  const context = await browser.newContext({ viewport: { width: 390, height: 900 } });
  const page = await context.newPage();
  await page.goto(`${origin}/strata/${SLUG}/`, { waitUntil: 'load', timeout: 120000 });
  await ready(page);
  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
  check('render:no-horizontal-overflow-at-390px', overflow <= 2, String(overflow));
  await context.close();
}

async function verifyRendered(ctx) {
  let chromium;
  try {
    ({ chromium } = createRequire(path.join(ROOT, 'package.json'))('playwright'));
  } catch (error) {
    check('render:browser-available', false, `playwright could not load: ${error.message}`);
    return;
  }
  const server = await serve();
  const origin = `http://127.0.0.1:${server.address().port}`;
  let browser = null;
  try {
    browser = await chromium.launch();
    check('render:browser-available', true);
    await driveDesktop(browser, origin, ctx);
    await measureNarrow(browser, origin);
  } catch (error) {
    check('render:browser-run-completed', false, error.stack || error.message);
  } finally {
    if (browser) await browser.close();
    server.close();
  }
}

/* ---------------------------------------------------------------- provenance */

function verifyProvenance(record, readme, manifest) {
  for (const file of record.files) {
    const filePath = path.join(ROOT, file.path);
    check(`provenance:${file.path}`, fs.existsSync(filePath) && sha256(filePath) === file.sha256 && readme.includes(file.sha256));
  }
  check('provenance:record-sha256-is-the-shipped-manifest', sha256(MANIFEST_PATH) === record.record.sha256);
  const shipped = fs.readdirSync(path.join(PUBLIC_DIR, 'data')).filter((name) => name !== 'manifest.json').sort();
  check('provenance:manifest-pins-every-shipped-data-file', same(manifest.files.map((file) => file.path), shipped.map((name) => `data/${name}`)) &&
    manifest.files.every((file) => {
      const filePath = path.join(PUBLIC_DIR, file.path);
      return fs.statSync(filePath).size === file.bytes && sha256(filePath) === file.sha256;
    }));
  check('provenance:public-data-byte-identical-to-research-copies', shipped.every((name) => sha256(path.join(PUBLIC_DIR, 'data', name)) === sha256(path.join(DERIVED_DIR, name))));
  const held = manifest.sources.filter((source) => source.held_at && !source.held_at.includes(' '));
  check('provenance:held-source-files-hash', held.length === 3 && held.every((source) => {
    const filePath = path.join(ROOT, source.held_at);
    return fs.statSync(filePath).size === source.bytes && sha256(filePath) === source.sha256 && readme.includes(source.sha256);
  }));
  check('provenance:primary-source-hash', sha256(PLACES_GZ) === held[0].sha256 && record.record.url === held[0].url);
  const unshipped = manifest.sources.filter((source) => !source.held_at || source.held_at.includes(' '));
  check('provenance:unshipped-source-hashes-stated', unshipped.length === 2 && unshipped.every((source) => /^[0-9a-f]{64}$/.test(source.sha256) && readme.includes(source.sha256) && readme.includes(String(source.bytes).replace(/\B(?=(\d{3})+(?!\d))/g, ','))) &&
    readme.includes('not redistributed'));
}

/* ---------------------------------------------------------------- run */

async function run() {
  const raw = loadRaw();
  const dataset = makeDataset(raw);
  const census = dataCensus(dataset);
  const anchors = anchorAudit(dataset);
  const html = fs.readFileSync(HTML_PATH, 'utf8');
  const record = readJson(RECORD_PATH);
  const manifest = readJson(MANIFEST_PATH);
  const markdown = fs.readFileSync(MD_PATH, 'utf8');
  const readme = fs.readFileSync(README_PATH, 'utf8');
  const licence = fs.readFileSync(LICENCE_PATH, 'utf8');
  const renderSource = fs.readFileSync(path.join(PUBLIC_DIR, 'render.js'), 'utf8');

  const { gap } = verifyCensus(raw, census);
  verifyAnchors(raw, dataset, census, anchors, record);
  const faults = verifyFaults(raw, anchors);
  verifyRefusals(dataset, census);
  verifyGeometry(dataset);
  verifyChoices(dataset, html, record, renderSource);
  verifySecond(raw, dataset, census);
  verifySurface({ raw, dataset, census, anchors, gap, html, record, markdown, readme, licence, manifest });
  await verifyRendered({ dataset, census, anchors, faults, dek: frontmatterValue(markdown, 'dek') });
  verifyProvenance(record, readme, manifest);

  const group = (pattern) => {
    const items = outcomes.filter((item) => pattern.test(item.name));
    return items.length > 0 && items.every((item) => item.pass);
  };
  const ledger = {
    anchor_reproduced_by_engine: group(/^(anchor:|fault:clean-anchor-closes$)/),
    rendered_figures_asserted: group(/^(surface|render):/),
    choices_are_live: group(/^choices:/),
    planted_fault_caught: group(/^fault:/),
    refusal_asserted: group(/^refuse:/),
    provenance_pinned: group(/^provenance:/)
  };
  const allPass = Object.values(ledger).every(Boolean) && outcomes.every((item) => item.pass);
  if (LEDGER_ONLY) {
    for (const [key, value] of Object.entries(ledger)) console.log(`${key}=${value}`);
  } else {
    for (const item of outcomes) console.log(`${item.pass ? 'PASS' : 'FAIL'} ${item.name}${item.details ? ` ${item.details.slice(0, 1500)}` : ''}`);
    console.log(`${outcomes.filter((item) => item.pass).length} of ${outcomes.length} assertions pass`);
    console.log(`ledger ${JSON.stringify(ledger)}`);
  }
  if (!allPass) process.exitCode = 1;
}

run().catch((error) => {
  console.error(error.stack || error.message);
  process.exitCode = 1;
});
