#!/usr/bin/env node
// Verifier for /strata/every-tree-wrote-the-same-bad-year/.
//
// Three layers, in order of how much they could embarrass us:
//
//   1. PROVENANCE. Re-download the three ITRDB measurement files from NOAA and
//      require each to hash to the SHA-256 recorded in the page's data.js. Also
//      re-fetch Douglass 1919 from the Internet Archive and require the two
//      sentences the page quotes to appear in it verbatim. (--no-net skips these
//      and counts them.)
//   2. TRANSPORT. Re-parse the downloaded files with this directory's own reader
//      of the Tucson decadal format and require the page's embedded copy to be
//      identical: same cores, same first years, same integers, all 45,411 of them.
//   3. ARITHMETIC. Recompute every number the page prints, twice: once with this
//      directory's implementation (crossdate.mjs) and once with the browser's
//      (public/.../dendro.js), which were written separately. Require the two to
//      agree, and require both to produce the figures the page and its prose carry.
//
// Exit 0 if every check passes, 1 with the first failure named.

import { createHash } from 'node:crypto';
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

import { parseRwl } from './rwl.mjs';
import * as OWN from './crossdate.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'every-tree-wrote-the-same-bad-year');
const CACHE = join(HERE, 'data', 'cache');
const NO_NET = process.argv.includes('--no-net');
const VERBOSE = process.argv.includes('-v');

const WEB = await import(new URL(join(PAGE, 'dendro.js'), 'file://').href);
const { PACKED, PROVENANCE } = await import(new URL(join(PAGE, 'data.js'), 'file://').href);

let pass = 0, skipped = 0;
const fails = [];
function check(name, cond, detail = '') {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok   ${name}${detail ? ' — ' + detail : ''}`); }
  else { fails.push(`${name}${detail ? ' — ' + detail : ''}`); console.log(`  FAIL ${name}${detail ? ' — ' + detail : ''}`); }
}
function skip(name) { skipped++; if (VERBOSE) console.log(`  skip ${name}`); }
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps * Math.max(1, Math.abs(a), Math.abs(b));
const section = (s) => console.log(`\n${s}`);

async function fetchText(url) {
  mkdirSync(CACHE, { recursive: true });
  const key = join(CACHE, url.replace(/[^a-z0-9.]/gi, '_'));
  if (NO_NET) return existsSync(key) ? readFileSync(key, 'utf8') : null;
  const res = await fetch(url);
  if (!res.ok) throw new Error(`${res.status} for ${url}`);
  const text = await res.text();
  writeFileSync(key, text);
  return text;
}

// ===========================================================================
section('1 · provenance: the archive still serves what the page carries');

const sources = {};
for (const [key, prov] of Object.entries(PROVENANCE)) {
  if (NO_NET) {
    skip(`re-download ${key}`);
    const cached = await fetchText(prov.url);
    if (cached) sources[key] = cached;
    else { skip(`parse ${key} (no cache)`); }
    continue;
  }
  const text = await fetchText(prov.url);
  const sha = createHash('sha256').update(text, 'utf8').digest('hex');
  check(`${key}: NOAA file hashes to the recorded SHA-256`, sha === prov.sha256,
    sha === prov.sha256 ? sha.slice(0, 16) + '…' : `got ${sha.slice(0, 16)}… want ${prov.sha256.slice(0, 16)}…`);
  check(`${key}: byte length matches`, Buffer.byteLength(text, 'utf8') === prov.bytes);
  sources[key] = text;
}

// The two Douglass sentences the page quotes, checked against the scan.
const DOUGLASS_QUOTES = [
  'Superficial counting of rings is subject to errors due to omission and doubling of rings',
  'the error of unchecked counting in the Arizona pines was 4 per cent',
  'The fundamental starting-point in all identification is the ring partially formed at the time of cutting the tree',
  'It was approached by the author from the standpoint of astronomy and a desire to understand the variations of the sun',
];
if (NO_NET) { for (const q of DOUGLASS_QUOTES) skip(`Douglass 1919 quote: "${q.slice(0, 40)}…"`); }
else {
  const dj = await fetchText('https://archive.org/stream/climaticcyclestr01douguoft/climaticcyclestr01douguoft_djvu.txt');
  // The scan's OCR hyphenates across line breaks; normalise whitespace and rejoin.
  const flat = dj.replace(/<[^>]+>/g, ' ').replace(/-\s*\n\s*/g, '').replace(/\s+/g, ' ');
  for (const q of DOUGLASS_QUOTES) {
    check(`Douglass 1919 carries: "${q.slice(0, 48)}…"`, flat.includes(q));
  }
}

// ===========================================================================
section('2 · transport: the page carries the file, whole and unaltered');

let totalValues = 0;
for (const [key, prov] of Object.entries(PROVENANCE)) {
  const embedded = WEB.decode(PACKED[key]);
  check(`${key}: embedded core count matches the recorded ${prov.nSeries}`, embedded.length === prov.nSeries,
    `${embedded.length}`);
  const sum = embedded.reduce((a, s) => a + s.values.length, 0);
  check(`${key}: embedded value count matches the recorded ${prov.nValues}`, sum === prov.nValues, `${sum}`);
  totalValues += sum;

  if (!sources[key]) { skip(`${key}: compare against the archive file`); continue; }
  const { series } = parseRwl(sources[key]);
  check(`${key}: our parser finds the same number of cores`, series.length === embedded.length,
    `${series.length} vs ${embedded.length}`);
  let mismatch = null;
  for (let i = 0; i < series.length && !mismatch; i++) {
    const a = series[i], b = embedded[i];
    if (a.id !== b.id) mismatch = `id ${a.id} vs ${b.id}`;
    else if (a.start !== b.start) mismatch = `${a.id} start ${a.start} vs ${b.start}`;
    else if (a.values.length !== b.values.length) mismatch = `${a.id} length ${a.values.length} vs ${b.values.length}`;
    else for (let k = 0; k < a.values.length; k++) {
      if (a.values[k] !== b.values[k]) { mismatch = `${a.id} year ${a.start + k}: ${a.values[k]} vs ${b.values[k]}`; break; }
    }
  }
  check(`${key}: every core, every year, every integer identical`, mismatch === null, mismatch || 'all match');
}
check('the page\'s stated total of 45,411 measurements', totalValues === 45411, `${totalValues}`);

// The two discrepancies the page reports in NOAA's own template metadata.
if (!NO_NET) {
  for (const [key, claimed, actual] of [['co021', 1400, 1176], ['az023', 1304, 1263]]) {
    const noaaUrl = PROVENANCE[key].url.replace(/\.rwl$/, '-noaa.rwl');
    const head = await fetchText(noaaUrl);
    const m = head.match(/^#\s*Earliest_Year:\s*(-?\d+)/m);
    check(`${key}: NOAA template header still states Earliest_Year ${claimed}`, m && Number(m[1]) === claimed,
      m ? m[1] : 'field not found');
    const embedded = WEB.decode(PACKED[key]);
    const first = Math.min(...embedded.map((s) => s.start));
    check(`${key}: the measurement file it heads actually begins in ${actual}`, first === actual, `${first}`);
  }
} else { for (let i = 0; i < 4; i++) skip('NOAA metadata discrepancy'); }

// ===========================================================================
section('3 · two implementations, written separately, must agree');

const decoded = {};
for (const key of Object.keys(PACKED)) decoded[key] = WEB.decode(PACKED[key]);
const AZ = decoded.az023, CO = decoded.co021, AK = decoded.ak001;

// 3a. The transform is the 1973 FORTRAN expression, literally.
{
  let worstT = 0, worstFortran = 0;
  for (const s of [...AZ, ...CO, ...AK]) {
    const mine = OWN.baillieTransform(s.values);
    const theirs = WEB.transform(s.values);
    for (let i = 0; i < mine.length; i++) {
      const a = mine[i], b = theirs[i];
      if (Number.isNaN(a) !== Number.isNaN(b)) { worstT = Infinity; break; }
      if (!Number.isNaN(a)) worstT = Math.max(worstT, Math.abs(a - b));
    }
    // A(I) = ALOG(500 * A(I+2) / (A(I)+A(I+1)+A(I+2)+A(I+3)+A(I+4)))
    for (let i = 2; i + 2 < s.values.length; i++) {
      const w = s.values.slice(i - 2, i + 3);
      if (w.some((v) => !(v > 0))) continue;
      const fortran = Math.log((500 * s.values[i]) / w.reduce((p, q) => p + q, 0));
      worstFortran = Math.max(worstFortran, Math.abs(fortran - mine[i]));
    }
  }
  check('the transform agrees between the two implementations', worstT < 1e-12, `max |diff| = ${worstT.toExponential(2)}`);
  check('and equals the published FORTRAN line, term for term', worstFortran < 1e-12,
    `max |diff| = ${worstFortran.toExponential(2)}`);
}

// 3b. Gleichlaeufigkeit: a series against itself must be exactly 1.
{
  const x = WEB.transform(AZ[0].values);
  const g1 = WEB.glk(x, x), g2 = OWN.glk(Array.from(x), Array.from(x));
  check('GLK of a series against itself is exactly 1 (the 2015 correction)', g1.glk === 1 && g2.glk === 1,
    `page ${g1.glk}, verifier ${g2.glk}`);
  // How much could the convention about flat intervals have mattered here? Ties do
  // occur in the transformed data, when a ring and its neighbour happen to sit at
  // the same fraction of their respective five-year means. Count them, and bound
  // the difference between the corrected convention and the old half-credit one.
  let tiesOne = 0, tiesBoth = 0, total = 0, worstGap = 0;
  const other = WEB.transform(CO[0].values);
  for (const s of AZ) {
    const a = WEB.transform(s.values);
    const n = Math.min(a.length, other.length);
    const g = WEB.glk(a.slice(0, n), other.slice(0, n));
    if (!g) continue;
    tiesOne += g.tiesOne; tiesBoth += g.tiesBoth; total += g.n;
    // The old convention gave a both-flat interval half credit instead of full,
    // so it differed by exactly tiesBoth/2 out of n.
    worstGap = Math.max(worstGap, g.tiesBoth / (2 * g.n));
  }
  check('flat intervals are rare in the transformed data',
    (tiesOne + tiesBoth) / total < 0.005, `${tiesOne + tiesBoth} in ${total} (${(100 * (tiesOne + tiesBoth) / total).toFixed(3)}%)`);
  check('so the two conventions for them could not shift any printed GLK by 0.001',
    worstGap < 0.001, `max shift ${worstGap.toExponential(2)}`);
}

// 3c. Sliding, on a real core, must agree row for row.
{
  const master = WEB.buildMaster(CO.map(WEB.prepare), 3);
  const masterOwn = OWN.buildMaster(CO.map(OWN.prepare), 3);
  check('the two master chronologies have the same span', master.start === masterOwn.start
    && master.x.length === masterOwn.x.length, `${master.start}+${master.x.length}`);
  let worst = 0;
  for (let i = 0; i < master.x.length; i++) {
    const a = master.x[i], b = masterOwn.x[i];
    if (Number.isNaN(a) !== Number.isNaN(b)) { worst = Infinity; break; }
    if (!Number.isNaN(a)) worst = Math.max(worst, Math.abs(a - b));
  }
  check('and the same values at every year', worst < 1e-12, `max |diff| = ${worst.toExponential(2)}`);

  const s = AZ[0];
  const rowsWeb = WEB.slide(WEB.transform(s.values), master, 100);
  const rowsOwn = OWN.slide(OWN.baillieTransform(s.values), masterOwn, 100);
  check('the slide produces the same number of candidate positions', rowsWeb.length === rowsOwn.length,
    `${rowsWeb.length}`);
  let worstT = 0, worstG = 0;
  for (let i = 0; i < Math.min(rowsWeb.length, rowsOwn.length); i++) {
    worstT = Math.max(worstT, Math.abs(rowsWeb[i].t - rowsOwn[i].t));
    worstG = Math.max(worstG, Math.abs(rowsWeb[i].glk - rowsOwn[i].glk));
  }
  check('and the same t at every one of them', worstT < 1e-9, `max |diff| = ${worstT.toExponential(2)}`);
  check('and the same parallel-run percentage', worstG < 1e-12, `max |diff| = ${worstG.toExponential(2)}`);
}

// ===========================================================================
section('4 · the claims the page makes, recomputed from the integers');

function experiment(targets, pool, selfExclude) {
  const prepared = pool.map(OWN.prepare);
  const rows = [];
  for (const s of targets) {
    const members = selfExclude ? prepared.filter((p) => p.id !== s.id) : prepared;
    const master = OWN.buildMaster(members, 3);
    const cands = OWN.slide(OWN.baillieTransform(s.values), master, 100);
    if (!cands.length) continue;
    const { best, second } = OWN.bestAndRunnerUp(cands, 5);
    const trueRow = cands.find((r) => r.startYear === s.start) || null;
    rows.push({ id: s.id, trueStart: s.start, called: best.startYear, correct: best.startYear === s.start,
      tBest: best.t, tSecond: second ? second.t : NaN, tTrue: trueRow ? trueRow.t : NaN,
      nCandidates: cands.length });
  }
  return rows;
}

const looAZ = experiment(AZ, AZ, true);
const looCO = experiment(CO, CO, true);
const cross = experiment(AZ, CO, false);
const ctrl = experiment(AZ, AK, false);

check('leave-one-out inside Navajo NM: 48 of 48 exact years',
  looAZ.length === 48 && looAZ.every((r) => r.correct), `${looAZ.filter((r) => r.correct).length} of ${looAZ.length}`);
check('leave-one-out inside Mesa Verde: 35 of 35 exact years',
  looCO.length === 35 && looCO.every((r) => r.correct), `${looCO.filter((r) => r.correct).length} of ${looCO.length}`);
check('Navajo NM cores against the Mesa Verde chronology: 48 of 48 exact years',
  cross.length === 48 && cross.every((r) => r.correct), `${cross.filter((r) => r.correct).length} of ${cross.length}`);
check('Navajo NM cores against the Alaskan chronology: 0 of 48',
  ctrl.length === 48 && ctrl.every((r) => !r.correct), `${ctrl.filter((r) => r.correct).length} correct`);

const ctrlOver = ctrl.filter((r) => r.tBest >= 3.5).length;
const ctrlMax = Math.max(...ctrl.map((r) => r.tBest));
const crossMin = Math.min(...cross.map((r) => r.tBest));
check('23 of the 48 impossible matches clear the conventional t >= 3.5', ctrlOver === 23, `${ctrlOver}`);
check('the strongest impossible match reaches t = 5.17', near(ctrlMax, 5.172, 1e-3), ctrlMax.toFixed(3));
check('the weakest genuine cross-site match reaches t = 7.21', near(crossMin, 7.205, 1e-3), crossMin.toFixed(3));
check('the two distributions do not overlap', ctrlMax < crossMin,
  `gap = ${(crossMin - ctrlMax).toFixed(3)}`);

// The float, and its anchor.
{
  const floatSet = AZ.filter((s) => s.end < 1940);
  const living = AZ.filter((s) => s.end >= 1940);
  check('four Navajo NM cores stop before 1940', floatSet.length === 4, floatSet.map((s) => s.end).join(', '));
  check('their last rings are 1555, 1614, 1699 and 1919',
    floatSet.map((s) => s.end).sort((a, b) => a - b).join(',') === '1555,1614,1699,1919');

  const byLen = [...floatSet].sort((a, b) => b.values.length - a.values.length);
  const placed = [{ series: byLen[0], rel: 0 }];
  const queue = byLen.slice(1);
  while (queue.length) {
    const fm = OWN.buildMaster(placed.map((p) => ({ id: p.series.id, start: p.rel, x: OWN.baillieTransform(p.series.values) })), 1);
    let pick = null;
    for (const cand of queue) {
      const rows = OWN.slide(OWN.baillieTransform(cand.values), fm, 80);
      if (!rows.length) continue;
      const { best } = OWN.bestAndRunnerUp(rows, 5);
      if (!pick || best.t > pick.best.t) pick = { cand, best };
    }
    if (!pick) break;
    placed.push({ series: pick.cand, rel: pick.best.startYear });
    queue.splice(queue.indexOf(pick.cand), 1);
  }
  const seed = placed[0].series;
  const internalOk = placed.every((p) => (p.rel - placed[0].rel) === (p.series.start - seed.start));
  check('the float assembles with its internal geometry correct in 4 of 4', internalOk && placed.length === 4);

  const fm = OWN.buildMaster(placed.map((p) => ({ id: p.series.id, start: p.rel, x: OWN.baillieTransform(p.series.values) })), 1);
  check('the float spans 657 relative years', fm.x.length === 657, `${fm.x.length}`);
  const livingMaster = OWN.buildMaster(living.map(OWN.prepare), 3);
  const rows = OWN.slide(fm.x, livingMaster, 100);
  const { best, second } = OWN.bestAndRunnerUp(rows, 5);
  check('the anchor is tried at 1,109 positions', rows.length === 1109, `${rows.length}`);
  check('the anchor scores t = 31.69', near(best.t, 31.69, 1e-3), best.t.toFixed(3));
  check('against a next best of t = 4.17 elsewhere', near(second.t, 4.17, 1e-2), second.t.toFixed(3));
  const implied = best.startYear - fm.start + placed[0].rel;
  check(`the anchor puts the first ring of ${seed.id} in its published year ${seed.start}`,
    implied === seed.start, `${implied}`);
}

// Interseries correlation and how many cores each site needs.
for (const [key, series, wantRbar, wantN] of [
  ['az023', AZ, 0.735, 3], ['co021', CO, 0.770, 2], ['ak001', AK, 0.412, 9],
]) {
  const { rbar } = OWN.rbarOf(series.map(OWN.prepare), 100);
  check(`${key}: mean interseries correlation is ${wantRbar}`, near(rbar, wantRbar, 5e-4), rbar.toFixed(4));
  let n = 1; while (n < 500 && OWN.eps(n, rbar) < 0.85) n++;
  check(`${key}: EPS reaches 0.85 at ${wantN} core${wantN === 1 ? '' : 's'}`, n === wantN, `${n}`);
  check(`${key}: the page's EPS formula agrees with ours`, near(WEB.eps(7, rbar), OWN.eps(7, rbar)));
}

// The drought, and what each filter does with it.
{
  const WIN = [1276, 1299], LEN = 24;
  const indexed = CO.map((s) => ({ start: s.start, x: OWN.standardise(s.values, 200, new Map()) }));
  const slow = WEB.stack(indexed, 4);
  const fast = WEB.stack(CO.map(OWN.prepare).map((p) => ({ start: p.start, x: p.x })), 4);
  // The browser's standardiser must agree with ours.
  const webIdx = CO.map((s) => ({ start: s.start, x: WEB.standardise(s.values, 200) }));
  let worst = 0;
  for (let i = 0; i < indexed.length; i++) {
    for (let k = 0; k < indexed[i].x.length; k++) {
      const a = indexed[i].x[k], b = webIdx[i].x[k];
      if (Number.isNaN(a) !== Number.isNaN(b)) { worst = Infinity; break; }
      if (!Number.isNaN(a)) worst = Math.max(worst, Math.abs(a - b));
    }
  }
  check('the two standardisers agree on every core', worst < 1e-8, `max |diff| = ${worst.toExponential(2)}`);
  // And the smoother really has the property its name claims.
  const lam = OWN.lambdaFor50pcAt(200);
  check('the 200-year smoother passes half the amplitude at 200 years, measured',
    near(OWN.responseAt(lam, 200), 0.5, 1e-3), OWN.responseAt(lam, 200).toFixed(5));
  check('and much less at 20 years', OWN.responseAt(lam, 20) < 0.01, OWN.responseAt(lam, 20).toExponential(2));

  const rank = (rows) => {
    const runs = [];
    for (let i = 0; i + LEN <= rows.length; i++) {
      const seg = rows.slice(i, i + LEN);
      if (seg[LEN - 1].year - seg[0].year !== LEN - 1) continue;
      runs.push({ from: seg[0].year, mean: seg.reduce((a, b) => a + b.value, 0) / LEN });
    }
    runs.sort((a, b) => a.mean - b.mean);
    return { rank: runs.findIndex((r) => r.from === WIN[0]) + 1, n: runs.length, worst: runs[0] };
  };
  const rSlow = rank(slow), rFast = rank(fast);
  check('standardised, AD 1276-1299 is the 4th lowest of 666 windows', rSlow.rank === 4 && rSlow.n === 666,
    `${rSlow.rank} of ${rSlow.n}`);
  check('and the very lowest window is 1273-1296', rSlow.worst.from === 1273, `${rSlow.worst.from}`);
  check('through the crossdating filter the same window ranks 495 of 652',
    rFast.rank === 495 && rFast.n === 652, `${rFast.rank} of ${rFast.n}`);
  const inWin = slow.filter((r) => r.year >= WIN[0] && r.year <= WIN[1]);
  const outWin = slow.filter((r) => r.year < WIN[0] || r.year > WIN[1]);
  const mean = (xs) => xs.reduce((a, b) => a + b.value, 0) / xs.length;
  check('the standardised drop across the window is 28 per cent',
    Math.round(100 * (1 - mean(inWin) / mean(outWin))) === 28,
    `${(100 * (1 - mean(inWin) / mean(outWin))).toFixed(1)}%`);
  check('and at least 13 cores are present in every year of it',
    Math.min(...inWin.map((r) => r.depth)) >= 13, `min depth ${Math.min(...inWin.map((r) => r.depth))}`);
}

// One ring deleted: does the diagnostic point at the gap?
{
  const s = AZ.find((v) => v.values.length >= 400);
  const master = OWN.buildMaster(AZ.filter((v) => v.id !== s.id).map(OWN.prepare), 3);
  let split = 0, localised = 0, trials = 0, wildlyWrong = 0;
  for (const frac of [0.3, 0.5, 0.7]) {
    const k = Math.floor(s.values.length * frac);
    const cut = s.values.slice(0, k).concat(s.values.slice(k + 1));
    const x = OWN.baillieTransform(cut);
    const rows = OWN.slide(x, master, 100);
    const { best } = OWN.bestAndRunnerUp(rows, 5);
    trials++;
    if (best.startYear !== s.start && best.startYear !== s.start + 1) wildlyWrong++;
    const segs = OWN.segmentDiagnostic(x, best.startYear, master, 50, 25, 5);
    const shifts = new Set(segs.map((g) => g.bestShift).filter(Number.isFinite));
    if (shifts.size > 1) split++;
    let boundary = null;
    for (let i = 0; i + 1 < segs.length; i++) {
      if (segs[i].bestShift !== segs[i + 1].bestShift) { boundary = [segs[i + 1].firstYear, segs[i].lastYear]; break; }
    }
    const removedYear = s.start + k;
    if (boundary && Math.min(Math.abs(boundary[0] - removedYear), Math.abs(boundary[1] - removedYear)) <= 25) localised++;
  }
  check('deleting one ring always splits the segmented diagnostic', split === trials, `${split} of ${trials}`);
  check('and the split lands within one segment step of the deleted ring', localised === trials, `${localised} of ${trials}`);
  check('the whole-core date never goes wildly wrong, only one year either way',
    wildlyWrong === 0, `${wildlyWrong} wild misses`);
}

// ===========================================================================
section('5 · the prose says what the arithmetic says');
{
  const raw = readFileSync(join(PAGE, 'index.html'), 'utf8');
  // The page wraps its lines, so compare against a whitespace-flattened copy:
  // a quotation broken across two source lines is still the same quotation.
  const html = raw.replace(/\s+/g, ' ');
  const carries = (needle) => html.includes(needle.replace(/\s+/g, ' '));
  check('the page states the 187 km separation', carries('187 km'));
  check('the page states the 3,718 km control distance', carries('3,718 km'));
  check('the page states 45,411 measurements', carries('45,411'));
  check('the page carries the 1973 "arbitrary preset value" quotation',
    carries('an arbitrary preset value of 3.5'));
  check('the page carries the FORTRAN line it implements', carries('ALOG(500 * A(I+2)'));
  check('the page carries Douglass on the four per cent', carries('was 4 per cent'));
  check('the page carries Douglass on the anchor',
    carries('the ring partially formed at the time of cutting the tree'));
  check('the page carries the Tille Höyük finding', carries('false, but highly positive'));
  check('the page does not quote the paywalled calibration it could not read',
    !carries('one in 600'));
  // Distances, recomputed.
  const hav = (a, b) => {
    const R = 6371.0088, rad = Math.PI / 180;
    const dLat = (b.lat - a.lat) * rad, dLon = (b.lon - a.lon) * rad;
    const s = Math.sin(dLat / 2) ** 2 + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
    return 2 * R * Math.asin(Math.sqrt(s));
  };
  const d1 = hav(PROVENANCE.az023, PROVENANCE.co021), d2 = hav(PROVENANCE.az023, PROVENANCE.ak001);
  check('Navajo NM to Mesa Verde really is 187 km', Math.round(d1) === 187, `${d1.toFixed(1)} km`);
  check('Navajo NM to Herring Alpine really is 3,718 km', Math.round(d2) === 3718, `${d2.toFixed(1)} km`);
}

// ===========================================================================
console.log(`\n${'='.repeat(64)}`);
if (fails.length) {
  console.log(`FAILED: ${fails.length} check(s) failed, ${pass} passed${skipped ? `, ${skipped} skipped` : ''}.`);
  for (const f of fails) console.log(`  · ${f}`);
  process.exit(1);
}
console.log(`PASS: ${pass} checks${skipped ? `, ${skipped} skipped (--no-net)` : ''}, 0 failures.`);
process.exit(0);
