#!/usr/bin/env node
// Seldom Amounting to Twenty Seconds: the check.
//
// Recomputes, from the transcriptions and the modern ephemeris tables in this directory,
// every number the page prints, and fails if the page and the data disagree. Node 22+,
// no packages. Run it from anywhere:
//
//   node research/seldom-amounting-to-twenty-seconds/verify.mjs          # check
//   node research/seldom-amounting-to-twenty-seconds/verify.mjs --write  # rebuild the page's data.json
//
// What it does NOT redo: the modern positions themselves. Those come from JPL DE440 via
// Skyfield (compute_modern.py, which needs a 115 MB ephemeris), and were checked against
// a second, independent route (JPL Horizons for the Moon and Sun, ERFA for the stars:
// cross_check.py). This program checks that second route's recorded agreement, and
// everything downstream of the two tables.

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

const HERE = dirname(fileURLToPath(import.meta.url));
const SLUG = 'seldom-amounting-to-twenty-seconds';
const PAGE_DIR = join(HERE, '..', '..', 'public', 'strata', SLUG);
const WRITE = process.argv.includes('--write');
const MONTHS = ['JAN', 'APR', 'JUL', 'OCT'];
const MONTH_NAME = { JAN: 'January', APR: 'April', JUL: 'July', OCT: 'October' };

let passed = 0, failed = 0;
function ok(cond, msg) { if (cond) passed++; else { failed++; console.log('  FAIL ' + msg); } }

// ---------- tiny CSV reader (quoted fields allowed) ----------
function csv(path) {
  const text = readFileSync(path, 'utf8').replace(/\r/g, '');
  const rows = []; let row = [], field = '', q = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (q) { if (c === '"' && text[i + 1] === '"') { field += '"'; i++; } else if (c === '"') q = false; else field += c; }
    else if (c === '"') q = true;
    else if (c === ',') { row.push(field); field = ''; }
    else if (c === '\n') { row.push(field); rows.push(row); row = []; field = ''; }
    else field += c;
  }
  if (field || row.length) { row.push(field); rows.push(row); }
  const [head, ...body] = rows.filter(r => r.length > 1 || r[0] !== '');
  return body.map(r => Object.fromEntries(head.map((h, i) => [h, (r[i] ?? '').trim()])));
}
const P = f => join(HERE, f);
const T = f => join(HERE, 'transcription', f);

const rms = v => Math.sqrt(v.reduce((s, x) => s + x * x, 0) / v.length);
const mean = v => v.reduce((s, x) => s + x, 0) / v.length;
const maxAbs = v => Math.max(...v.map(Math.abs));
const r1 = x => Math.round(x * 10) / 10;
const pct = (k, n) => Math.round(1000 * k / n) / 10;

// =====================================================================================
// 1. The comparer: two independent passes, and the one reconciled table
// =====================================================================================
console.log('1. Double entry');
const resolutions = csv(P('resolutions.csv'));
const distKey = r => [r.side, r.day, r.object, r.hour].join('|');
let distCells = 0, distDisagree = 0;
const merged = [];
for (const m of MONTHS) {
  const A = new Map(csv(T(`DIST_${m}_A.csv`)).map(r => [distKey(r), r]));
  const B = new Map(csv(T(`DIST_${m}_B.csv`)).map(r => [distKey(r), r]));
  ok(A.size === B.size && [...A.keys()].every(k => B.has(k)), `${m}: both passes list the same cells`);
  for (const [k, a] of A) {
    const b = B.get(k); const v = {};
    for (const f of ['deg', 'min', 'sec']) {
      distCells++;
      if (a[f] === b[f]) { v[f] = a[f]; continue; }
      distDisagree++;
      const [side, day, object, hour] = k.split('|');
      const res = resolutions.find(r => r.table === 'distances' && r.month === m && r.side === side && r.day === day &&
        r.object === object && r.hour === hour && r.field === f && r.pass_A === a[f] && r.pass_B === b[f]);
      ok(res, `${m} ${k} ${f}: passes disagree (${a[f]} / ${b[f]}) and resolutions.csv does not settle it`);
      v[f] = res ? res.reading : a[f];
    }
    merged.push({ month: m, key: k, ...v });
  }
}
const printed = csv(P('almanac-1767-distances.csv'));
ok(printed.length === merged.length, `reconciled table has ${printed.length} rows, the merge ${merged.length}`);
const mergedMap = new Map(merged.map(r => [r.month + '|' + r.key, r]));
let mismatch = 0;
for (const r of printed) {
  const g = mergedMap.get(r.month + '|' + distKey(r));
  if (!g || g.deg !== r.deg || g.min !== r.min || g.sec !== r.sec) mismatch++;
}
ok(mismatch === 0, `reconciled table equals the merge of the two passes (${mismatch} rows differ)`);

const moonKey = r => r.day;
let moonCells = 0, moonDisagree = 0;
for (const m of MONTHS) {
  const A = new Map(csv(T(`MOON_${m}_A.csv`)).map(r => [moonKey(r), r]));
  const B = new Map(csv(T(`MOON_${m}_B.csv`)).map(r => [moonKey(r), r]));
  ok(A.size === B.size, `Moon ${m}: same days in both passes`);
  for (const [d, a] of A) for (const f of Object.keys(a)) {
    if (f === 'flag' || f === 'day') continue;
    moonCells++;
    if (a[f].toUpperCase() !== (B.get(d)?.[f] ?? '').toUpperCase()) {
      moonDisagree++;
      ok(resolutions.some(r => r.table === 'moon' && r.month === m && r.day === d && r.field === f), `Moon ${m} day ${d} ${f} unresolved`);
    }
  }
}
console.log(`   distances: ${distCells} cells, ${distDisagree} disagreement(s); Moon places: ${moonCells} cells, ${moonDisagree}`);

// =====================================================================================
// 2. Printed minus true, and what it cost a navigator
// =====================================================================================
console.log('2. The printed distances against DE440');
const modern = new Map(csv(P('modern-distances.csv')).map(r => [r.month + '|' + distKey(r), r]));
const rows = printed.map(r => {
  const mo = modern.get(r.month + '|' + distKey(r));
  ok(mo, `modern value exists for ${r.month} ${distKey(r)}`);
  const p = (+r.deg) * 3600 + (+r.min) * 60 + (+r.sec);
  const res = p - (+mo.modern_deg) * 3600;
  const rate = +mo.rate_arcsec_per_hour;
  return {
    month: r.month, leaf: +r.leaf, side: r.side, day: +r.day, object: r.object, star: r.star_id, hour: +r.hour, p,
    res, resNoAb: p - (+mo.modern_no_aberration_deg) * 3600, rate, dDl: +mo.dD_dlon, dDb: +mo.dD_dlat,
    // a navigator who measured the TRUE distance and read the time off the printed table would
    // be wrong by -res/rate hours; fifteen degrees of longitude to the hour, so in arcminutes:
    lonErr: 900 * res / rate,
  };
});
// Misprints: values whose printed form is wrong in a way the page itself betrays (a transposed
// pair of digits, a missing figure). They are real errors a navigator would have met, so they
// are counted and shown; but the question "how good were Mayer's tables and the computers'
// arithmetic" is asked of the other values, and every headline number below says which.
const misprints = csv(P('printing-errors.csv'));
const dms = s => { const [a, b, c] = s.split('.').map(Number); return a * 3600 + b * 60 + c; };
for (const e of misprints.filter(e => e.table === 'distances')) {
  const r = rows.find(r => r.month === e.month && r.side === e.side && r.day === +e.day && r.object === e.object && r.hour === +e.hour);
  ok(r && r.p === dms(e.printed), `misprint ${e.month} ${e.day} ${e.object} ${e.hour}h is in the table as printed`);
  if (!r) continue;
  r.misprint = true;
  const fixed = r.res - r.p + dms(e.corrected);
  ok(Math.abs(r.res) > 600 && Math.abs(fixed) < 5, `misprint ${e.object}: ${r1(r.res)}" as printed, ${r1(fixed)}" as corrected`);
  r.fixedRes = fixed;
}
const clean = rows.filter(r => !r.misprint);
const worst = rows.filter(r => r.misprint).sort((a, b) => Math.abs(b.lonErr) - Math.abs(a.lonErr))[0];
const res = clean.map(r => r.res), lon = clean.map(r => r.lonErr);
// What a navigator who measured the true distance at the entry's own instant would actually
// get, reading the time off the printed table by proportional parts between the two entries
// that bracket the measurement (arcminutes of longitude). For an ordinary entry this is the
// linear estimate above to first order; for a misprint it is the honest figure.
function proportionalParts(r) {
  const s = rows.filter(x => x.month === r.month && x.side === r.side && x.object === r.object).sort((a, b) => (a.day * 24 + a.hour) - (b.day * 24 + b.hour));
  const T0 = r.day * 24 + r.hour, reading = r.p - r.res;
  for (let i = 0; i + 1 < s.length; i++) {
    const a = s[i], b = s[i + 1], ta = a.day * 24 + a.hour, tb = b.day * 24 + b.hour;
    if (tb - ta !== 3 || reading < Math.min(a.p, b.p) || reading > Math.max(a.p, b.p)) continue;
    return (ta + (reading - a.p) / (b.p - a.p) * 3 - T0) * 900;
  }
  return NaN;
}
const S = {
  n: rows.length, nClean: clean.length, misprints: rows.length - clean.length,
  printedRms: r1(rms(rows.map(r => r.res))), printedMax: r1(maxAbs(rows.map(r => r.res))),
  misprintArcsec: worst ? Math.round(Math.abs(worst.res)) : 0, misprintLon: worst ? Math.round(Math.abs(proportionalParts(worst))) : 0,
  rms: r1(rms(res)), mean: r1(mean(res)), max: r1(maxAbs(res)),
  over20: res.filter(x => Math.abs(x) >= 20).length, over60: res.filter(x => Math.abs(x) > 60).length,
  rmsNoAb: r1(rms(clean.map(r => r.resNoAb))),
  lonMedian: r1([...lon].map(Math.abs).sort((a, b) => a - b)[Math.floor(lon.length / 2)]),
  lonOver10: lon.filter(x => Math.abs(x) > 10).length, lonOver30: lon.filter(x => Math.abs(x) > 30).length,
  lonMax: r1(maxAbs(lon)),
};
S.over20pct = pct(S.over20, S.nClean); S.lonOver10pct = pct(S.lonOver10, S.nClean);
S.byMonth = Object.fromEntries(MONTHS.map(m => {
  const v = clean.filter(r => r.month === m).map(r => r.res);
  return [m, { n: v.length, rms: r1(rms(v)), max: r1(maxAbs(v)), over60: v.filter(x => Math.abs(x) > 60).length }];
}));
console.log(`   ${S.n} printed; ${S.misprints} misprint(s) set aside (as printed: RMS ${S.printedRms}", max ${S.printedMax}")`);
console.log(`   n=${S.nClean}  RMS ${S.rms}"  max ${S.max}"  >=20": ${S.over20} (${S.over20pct}%)  >60": ${S.over60}`);
console.log(`   as longitude: median ${S.lonMedian}'  >10': ${S.lonOver10} (${S.lonOver10pct}%)  >30': ${S.lonOver30}  max ${S.lonMax}'`);
console.log(`   with the stars left unaberrated on the modern side, the RMS would be ${S.rmsNoAb}"`);

// =====================================================================================
// 3. Whose error? Mayer's Moon, as the almanac printed it, against DE440
// =====================================================================================
console.log("3. Mayer's Moon against DE440");
const moonPrinted = csv(P('almanac-1767-moon.csv'));
const moonModern = new Map(csv(P('modern-moon.csv')).map(r => [`${r.month}|${r.day}|${r.when}`, r]));
const wrap = x => ((x + 180) % 360 + 360) % 360 - 180;
const moonErr = moonPrinted.map(r => {
  const mo = moonModern.get(`${r.month}|${r.day}|${r.when}`);
  ok(mo, `modern Moon for ${r.month} ${r.day} ${r.when}`);
  const typo = misprints.find(e => e.table === 'moon' && e.month === r.month && e.day === r.day && e.hour === r.when);
  let [sg, dg, mn, sc] = [r.lon_signs, r.lon_deg, r.lon_min, r.lon_sec].map(Number);
  if (typo) {
    ok(typo.printed === [sg, dg, mn, sc].join('.'), `Moon misprint ${r.month} ${r.day} ${r.when} is in the table as printed`);
    [sg, dg, mn, sc] = typo.corrected.split('.').map(Number);
  }
  const L = sg * 30 + dg + mn / 60 + sc / 3600;
  const B = ((+r.lat_deg) + (+r.lat_min) / 60 + (+r.lat_sec) / 3600) * (r.lat_ns === 'N' ? 1 : -1);
  return { month: r.month, day: +r.day, hour: r.when === 'noon' ? 0 : 12,
           dL: wrap(L - (+mo.lon_deg)) * 3600, dB: (B - (+mo.lat_deg)) * 3600, dpsi: +mo.nutation_in_longitude_arcsec };
});
const dL = moonErr.map(e => e.dL), dB = moonErr.map(e => e.dB);
const M = {
  n: moonErr.length, lonRms: r1(rms(dL)), lonMean: r1(mean(dL)), lonMax: r1(maxAbs(dL)),
  lonOver20: dL.filter(x => Math.abs(x) >= 20).length, lonOver60: dL.filter(x => Math.abs(x) > 60).length,
  latRms: r1(rms(dB)), latMax: r1(maxAbs(dB)),
};
M.lonOver20pct = pct(M.lonOver20, M.n);
M.byMonthMean = Object.fromEntries(MONTHS.map(m => [m, r1(mean(moonErr.filter(e => e.month === m).map(e => e.dL)))]));
console.log(`   longitude: n=${M.n} RMS ${M.lonRms}" mean ${M.lonMean}" max ${M.lonMax}"  >=20": ${M.lonOver20} (${M.lonOver20pct}%)  >60": ${M.lonOver60}`);
console.log(`   latitude:  RMS ${M.latRms}" max ${M.latMax}"`);

// Interpolate the Moon's printed error to each distance's time and ask how much of the
// distance's error it accounts for. `nutation` flips the question of which equinox the
// printed longitudes were referred to: if to the MEAN equinox, their error against a true-
// equinox Moon is larger by the nutation in longitude.
function moonErrAt(month, day, hour, meanEquinox) {
  const T0 = day * 24 + hour;
  const pts = moonErr.filter(e => e.month === month).map(e => ({ t: e.day * 24 + e.hour, ...e })).sort((a, b) => a.t - b.t);
  let lo = null, hi = null;
  for (const p of pts) { if (p.t <= T0) lo = p; if (p.t >= T0 && !hi) hi = p; }
  if (!lo || !hi) return null;
  const f = hi.t === lo.t ? 0 : (T0 - lo.t) / (hi.t - lo.t);
  const L = x => meanEquinox ? x.dL + x.dpsi : x.dL;
  return { dL: L(lo) * (1 - f) + L(hi) * f, dB: lo.dB * (1 - f) + hi.dB * f };
}
function decompose(meanEquinox) {
  const out = [];
  for (const r of clean) {
    const e = moonErrAt(r.month, r.day, r.hour, meanEquinox);
    if (!e) continue;
    const pred = r.dDl * e.dL + r.dDb * e.dB;
    out.push({ r, pred, left: r.res - pred });
  }
  return out;
}
const dec = decompose(false), decMean = decompose(true);
// the aberration question again, now that the Moon theory's error no longer swamps it
const leftNoAb = dec.map(d => d.r.resNoAb - d.pred);
const D = {
  n: dec.length, before: r1(rms(dec.map(d => d.r.res))), after: r1(rms(dec.map(d => d.left))),
  afterMeanEquinox: r1(rms(decMean.map(d => d.left))),
};
D.afterNoAb = r1(rms(leftNoAb));
D.share = Math.round(100 * (1 - (D.after * D.after) / (D.before * D.before)));
console.log(`   distances with a Moon place on both sides: ${D.n}; RMS ${D.before}" -> ${D.after}" once the printed Moon's own error is removed (${D.share}% of the variance)`);
console.log(`   if the printed longitudes were mean-equinox instead, the residual would be ${D.afterMeanEquinox}"`);
ok(D.after < D.afterMeanEquinox, 'the distances say the printed Moon longitudes are referred to the TRUE equinox (nutation applied)');
console.log(`   with the stars left unaberrated on the modern side, that residual would be ${D.afterNoAb}"`);
ok(D.after < D.afterNoAb, 'once the Moon is accounted for, the distances plainly include the aberration of the stars');
ok(D.after < D.before / 2, 'most of the distance error is the lunar theory, not the arithmetic');

// Could part of the Moon's printed error be a shared frame offset (an equinox placed
// differently in 1767) that cancels against the stars? Fit res = k*pred + c*dD/dlon + b.
// A pure frame offset would need k well below 1 or a large c; the page says neither.
{
  const X = dec.map(d => [d.pred, d.r.dDl, 1]), y = dec.map(d => d.r.res);
  const N = [[0, 0, 0], [0, 0, 0], [0, 0, 0]], v = [0, 0, 0];
  X.forEach((x, i) => { for (let a = 0; a < 3; a++) { v[a] += x[a] * y[i]; for (let b = 0; b < 3; b++) N[a][b] += x[a] * x[b]; } });
  for (let c = 0; c < 3; c++) for (let r = 0; r < 3; r++) if (r !== c) {   // Gauss-Jordan, 3x3
    const f = N[r][c] / N[c][c]; for (let k = 0; k < 3; k++) N[r][k] -= f * N[c][k]; v[r] -= f * v[c];
  }
  const [k, c] = [v[0] / N[0][0], v[1] / N[1][1]];
  D.slope = Math.round(k * 100) / 100; D.frame = r1(c);
  console.log(`   fit: printed error = ${D.slope} x (Moon-place prediction) + ${D.frame}" of extra longitude offset`);
  ok(Math.abs(k - 1) < 0.1 && Math.abs(c) < 6, "the Moon's printed error is real against the stars, not a shared frame offset");
}
// what is left, by distance: the close approaches
const near = dec.filter(d => Math.abs(d.r.p) / 3600 < 30), far = dec.filter(d => Math.abs(d.r.p) / 3600 >= 30);
D.leftNear = r1(rms(near.map(d => d.left))); D.leftFar = r1(rms(far.map(d => d.left))); D.nNear = near.length;
console.log(`   what is left: RMS ${D.leftFar}" at distances of 30 degrees and more, ${D.leftNear}" below 30 degrees (${D.nNear} values)`);

// =====================================================================================
// 4. The examiners' own tool: differences. A slip in one cell shows in the fourth differences
// =====================================================================================
console.log('4. Fourth differences');
const series = new Map();
for (const r of rows) {
  const k = `${r.month}|${r.side}|${r.object}`;
  if (!series.has(k)) series.set(k, new Map());
  series.get(k).set(r.day * 24 + r.hour, r.p);
}
function roughSpots(ser, threshold) {
  const spots = [];
  for (const [k, s] of ser) {
    const ts = [...s.keys()].sort((a, b) => a - b);
    for (let i = 0; i + 4 < ts.length; i++) {
      if (ts[i + 4] - ts[i] !== 12) continue;
      const v = ts.slice(i, i + 5).map(t => s.get(t));
      const d4 = v[0] - 4 * v[1] + 6 * v[2] - 4 * v[3] + v[4];
      if (Math.abs(d4) > threshold) spots.push({ k, t: ts[i + 2], d4 });
    }
  }
  return spots;
}
const THRESH = 12;   // arcsec; rounding alone to the whole second reaches 8 at worst
const spots = roughSpots(series, THRESH);
const rough = csv(P('rough-spots.csv'));
const centres = new Set(spots.map(s => { const [m, side, obj] = s.k.split('|'); return `${m}|${side}|${obj}|${Math.floor(s.t / 24)}`; }));
for (const c of centres) {
  const [m, side, obj, day] = c.split('|');
  ok(rough.some(r => r.month === m && r.side === side && r.object === obj && Math.abs(+r.day - +day) <= 1),
     `rough spot ${c} has not been looked at on the scan (add it to rough-spots.csv)`);
}
console.log(`   windows over ${THRESH}": ${spots.length}, around ${centres.size} places, every one checked against the scan in rough-spots.csv`);
// hostile fixture: move every single cell by 5" in turn; how often does the gate notice?
let caught = 0, tried = 0;
for (const [k, s] of series) for (const t of s.keys()) {
  const base = roughSpots(new Map([[k, s]]), THRESH).length;
  const copy = new Map(s); copy.set(t, s.get(t) + 5);
  const inside = [...copy.keys()].filter(u => Math.abs(u - t) <= 12).length >= 5;
  if (!inside) continue;
  tried++;
  if (roughSpots(new Map([[k, copy]]), THRESH).length > base) caught++;
}
const F = { tried, caught, pct: pct(caught, tried) };
console.log(`   hostile fixture: a 5" slip planted in each of ${tried} cells is caught ${caught} times (${F.pct}%)`);
ok(F.pct > 50, 'the difference gate can see a 5" slip more often than not');

// =====================================================================================
// 5. The modern side, checked by a second route
// =====================================================================================
console.log('5. Second route to the modern values');
const X = JSON.parse(readFileSync(P('cross-check.json'), 'utf8'));
const xmax = Math.max(...X.samples.map(s => Math.abs(s.distance_diff_arcsec)));
const tmax = Math.max(...X.samples.map(s => Math.abs(s.apparent_time_diff_s)));
ok(X.samples.length >= 40, 'at least forty sampled rows were recomputed by the second route');
ok(xmax < 1, `Horizons + ERFA agree with Skyfield + DE440 to under 1" (worst ${xmax.toFixed(2)}")`);
console.log(`   ${X.samples.length} rows: worst distance difference ${xmax.toFixed(2)}", worst apparent-time difference ${tmax.toFixed(2)} s`);

// =====================================================================================
// 6. The page
// =====================================================================================
const claims = {
  'n': S.n.toLocaleString('en-GB'), 'n-clean': S.nClean.toLocaleString('en-GB'), 'misprint-arcsec': `${S.misprintArcsec}`,
  'misprint-lon': `${S.misprintLon}`, 'misprint-deg': `${Math.round(S.misprintLon / 6) / 10}`, 'rms': `${S.rms}`, 'max': `${S.max}`, 'over20pct': `${S.over20pct}`, 'over60': `${S.over60}`,
  'lon-median': `${S.lonMedian}`, 'lon-over10pct': `${S.lonOver10pct}`, 'lon-over30': `${S.lonOver30}`, 'lon-max': `${Math.round(S.lonMax)}`,
  'rms-noab': `${S.rmsNoAb}`, 'moon-n': `${M.n}`, 'moon-rms': `${M.lonRms}`, 'moon-max': `${M.lonMax}`, 'moon-over20pct': `${M.lonOver20pct}`,
  'moon-over60': `${M.lonOver60}`, 'lat-rms': `${M.latRms}`, 'dec-before': `${D.before}`, 'dec-after': `${D.after}`, 'dec-share': `${D.share}`, 'dec-slope': `${D.slope}`, 'dec-frame': `${Math.abs(D.frame)}`,
  'dec-after-mean': `${D.afterMeanEquinox}`, 'dec-after-noab': `${D.afterNoAb}`, 'misprints': `${misprints.length}`, 'left-far': `${D.leftFar}`, 'left-near': `${D.leftNear}`,
  'cells': (distCells + moonCells).toLocaleString('en-GB'), 'disagree': `${distDisagree + moonDisagree}`,
  'fixture-pct': `${Math.round(F.pct)}`, 'xcheck-n': `${X.samples.length}`, 'xcheck-max': xmax.toFixed(1),
};
for (const m of MONTHS) { claims[`rms-${m}`] = `${S.byMonth[m].rms}`; claims[`moon-mean-${m}`] = `${M.byMonthMean[m]}`; }

const data = {
  about: 'Every lunar distance printed in the Nautical Almanac for January, April, July and October 1767, against JPL DE440. Generated by research/' + SLUG + '/verify.mjs --write.',
  months: MONTHS,
  scan: 'https://archive.org/details/bim_eighteenth-century_the-nautical-almanac-and_great-britain-commissio_1766',
  // compact rows: [monthIndex, day, hour, sideEast?1:0, objectIndex, printed arcsec, residual*100, rate*10, moonPart*100|null, leaf, misprint?1:0]
  objects: [...new Set(rows.map(r => r.object))],
  rows: rows.map(r => {
    const d = dec.find(x => x.r === r);
    return [MONTHS.indexOf(r.month), r.day, r.hour, r.side === 'east' ? 1 : 0, null, r.p, Math.round(r.res * 100), Math.round(r.rate * 10), d ? Math.round(d.pred * 100) : null, r.leaf, r.misprint ? 1 : 0];
  }),
  moon: moonErr.map(e => [MONTHS.indexOf(e.month), e.day, e.hour, Math.round(e.dL * 10), Math.round(e.dB * 10)]),
  claims,
};
const objIdx = new Map(data.objects.map((o, i) => [o, i]));
rows.forEach((r, i) => { data.rows[i][4] = objIdx.get(r.object); });

const dataPath = join(PAGE_DIR, 'data.json');
if (WRITE) {
  writeFileSync(dataPath, JSON.stringify(data));
  console.log('wrote ' + dataPath);
} else if (existsSync(dataPath)) {
  const shipped = readFileSync(dataPath, 'utf8');
  ok(shipped === JSON.stringify(data), "the page's data.json is exactly what this program computes (rerun with --write)");
}
const htmlPath = join(PAGE_DIR, 'index.html');
if (existsSync(htmlPath)) {
  const html = readFileSync(htmlPath, 'utf8');
  const seen = [...html.matchAll(/data-claim="([A-Za-z0-9-]+)"[^>]*>([^<]*)</g)];
  ok(seen.length >= 10, `the page carries its numbers as data-claim spans (${seen.length} found)`);
  for (const [, k, v] of seen) {
    ok(k in claims, `page claims an unknown quantity "${k}"`);
    if (k in claims) ok(v.trim() === claims[k], `page says ${k} = "${v.trim()}", the data say "${claims[k]}"`);
  }
}

console.log(`\n${passed} checks passed, ${failed} failed`);
if (failed) process.exit(1);
