#!/usr/bin/env node
// verify.mjs: every claim the layer makes, checked against primary data.
//
// Run:  node research/no-water-in-the-machine/fetch.mjs     (once, ~19 MB from NOAA)
//       node verify-no-water-in-the-machine.mjs
//
// The ground truth is NOAA CO-OPS: their published harmonic constituents,
// their published tide predictions, and their measured water levels. Nothing
// here is fitted to make a story come out; where our reconstruction and NOAA's
// disagree, the check reports the disagreement.

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

import { CONSTITUENTS, BY_NAME } from './constituents.mjs';
import {
  astro, auxiliary, nodeFactors, constituentState, speedOf,
  RATES, MEAN_LONGITUDE_POLYNOMIALS, MEAN_OBLIQUITY, EPOCH_JD, OMEGA, INC_I, norm,
} from './schureman.mjs';
import { stationFromHarcon, series, rms, maxAbsDiff, heightAt } from './predict.mjs';
import { harmonicFit } from './analyze.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
// compact/ is what ships: the same measured values, stored as integer
// millimetres on a fixed grid instead of 34 MB of repeated JSON keys. data/ is
// the verbatim NOAA output that fetch.mjs downloads and distill.mjs reduces;
// compact/manifest.json carries the SHA-256 of every raw file, so re-running
// fetch.mjs proves where these numbers came from. If data/ is present, the
// verifier prefers it and checks the two agree exactly.
const COMPACT = path.join(HERE, 'compact');
const RAW = path.join(HERE, 'data');
const D2R = Math.PI / 180;
const GAP = -32768;

// ---------------------------------------------------------------------------
let passed = 0, failed = 0;
const FIG = {};   // figures the page is allowed to print
function check(label, ok, detail = '') {
  if (ok) { passed++; console.log(`  ok   ${label}${detail ? '  ' + detail : ''}`); }
  else { failed++; console.log(`  FAIL ${label}${detail ? '  ' + detail : ''}`); }
}
function section(t) { console.log(`\n${t}\n${'-'.repeat(t.length)}`); }
const fx = (k, v) => { FIG[k] = v; return v; };

/**
 * Local maxima of a sampled signal, with a minimum separation and a minimum
 * prominence. Written once and used by both the high-water count and the
 * spring-neap beat, because a naive "bigger than both neighbours" test finds
 * hundreds of ripples and turns a fortnight into half a day. It did, here,
 * before this function existed.
 *
 * @param values     numbers, NaN allowed
 * @param minSepIdx  samples that must separate two accepted peaks
 * @param prominence a peak must exceed the lowest point between it and the
 *                   previous accepted peak by at least this much
 */
function peaks(values, minSepIdx, prominence) {
  const cand = [];
  for (let i = 1; i < values.length - 1; i++) {
    if (!Number.isFinite(values[i])) continue;
    if (values[i] >= values[i - 1] && values[i] > values[i + 1]) cand.push(i);
  }
  // greedily keep the tallest, suppressing anything within minSepIdx of it
  const order = [...cand].sort((a, b) => values[b] - values[a]);
  const kept = [];
  for (const i of order) {
    if (kept.some(j => Math.abs(j - i) < minSepIdx)) continue;
    kept.push(i);
  }
  kept.sort((a, b) => a - b);
  if (!prominence) return kept;
  const out = [];
  for (let k = 0; k < kept.length; k++) {
    const i = kept[k];
    const from = k === 0 ? 0 : kept[k - 1];
    let valley = Infinity;
    for (let j = from; j <= i; j++) if (Number.isFinite(values[j])) valley = Math.min(valley, values[j]);
    if (values[i] - valley >= prominence) out.push(i);
  }
  return out;
}

const STATIONS = [
  ['boston', 'Boston, Massachusetts'],
  ['eastport', 'Eastport, Maine'],
  ['anchorage', 'Anchorage, Alaska'],
  ['pensacola', 'Pensacola, Florida'],
  ['galveston', 'Galveston Pier 21, Texas'],
  ['sanfrancisco', 'San Francisco, California'],
  ['seattle', 'Seattle, Washington'],
  ['keywest', 'Key West, Florida'],
  ['honolulu', 'Honolulu, Hawaii'],
  ['thebattery', 'The Battery, New York'],
];

const have = (n) => existsSync(path.join(COMPACT, n));

/** Read a distilled file and put it back in the shape NOAA's API returns. */
function load(n) {
  const j = JSON.parse(readFileSync(path.join(COMPACT, n), 'utf8'));
  if (j.kind === 'harcon') {
    return {
      units: j.units,
      HarmonicConstituents: j.c.map(([name, amplitude, phase_GMT, speed]) =>
        ({ name, amplitude, phase_GMT, speed, comments: j.comments })),
    };
  }
  if (j.kind === 'obs' || j.kind === 'pred') {
    const t0 = Date.parse(j.t0);
    const rows = j.mm.split(',').map((s, i) => {
      const mm = +s;
      return {
        t: new Date(t0 + i * j.stepMin * 60000).toISOString().slice(0, 16).replace('T', ' '),
        v: mm === GAP ? '' : (mm / 1000).toFixed(3),
      };
    });
    return j.kind === 'obs' ? { metadata: j.meta, data: rows } : { predictions: rows };
  }
  return j;
}

if (!have('harcon-boston.json')) {
  console.error('No compact/. Run: node research/no-water-in-the-machine/fetch.mjs && node research/no-water-in-the-machine/distill.mjs');
  process.exit(2);
}

const harcon = Object.fromEntries(STATIONS.map(([s]) => [s, load(`harcon-${s}.json`)]));
const parseSeries = (j) => {
  const rowsIn = j.data || j.predictions;
  return rowsIn.map(r => ({
    date: new Date(r.t.replace(' ', 'T') + ':00Z'),
    value: r.v === '' ? NaN : parseFloat(r.v),
  }));
};

// ===========================================================================
section('0. The distilled data is the downloaded data');
// compact/ is what the repository carries. If the 34 MB of verbatim NOAA JSON
// is also present, prove that every value survived the reduction unchanged and
// that the raw bytes still hash to what the manifest recorded. If it is absent,
// say so plainly rather than passing a check that could not have failed.
{
  const manifest = JSON.parse(readFileSync(path.join(COMPACT, 'manifest.json'), 'utf8'));
  const names = Object.keys(manifest);
  fx('rawFiles', names.length);
  fx('rawBytes', Object.values(manifest).reduce((a, b) => a + b.bytes, 0));

  if (!existsSync(RAW) || !existsSync(path.join(RAW, 'harcon-boston.json'))) {
    console.log(`  ..   ${names.length} raw files absent (run fetch.mjs to check the reduction end to end)`);
  } else {
    const { createHash } = await import('node:crypto');
    let badHash = 0, badValue = 0, compared = 0, firstBad = '';
    for (const name of names) {
      const buf = readFileSync(path.join(RAW, name));
      if (createHash('sha256').update(buf).digest('hex') !== manifest[name].sha256) {
        badHash++; if (!firstBad) firstBad = name; continue;
      }
      const raw = JSON.parse(buf.toString('utf8'));
      const rawRows = raw.data || raw.predictions;
      if (!rawRows) continue;
      const back = load(name);
      const backRows = back.data || back.predictions;
      const byT = new Map(backRows.map(r => [r.t, r.v]));
      for (const r of rawRows) {
        compared++;
        const got = byT.get(r.t);
        const want = r.v === '' ? '' : parseFloat(r.v).toFixed(3);
        if (got !== want) { badValue++; if (!firstBad) firstBad = `${name} @ ${r.t}`; }
      }
    }
    check('every raw file hashes to its manifest entry', badHash === 0,
      `${names.length} files, ${badHash} mismatched${firstBad ? ` (first: ${firstBad})` : ''}`);
    check('every measured value survives the reduction unchanged', badValue === 0,
      `${compared.toLocaleString('en-US')} heights compared, ${badValue} differ`);
    fx('valuesCompared', compared);
  }
}

// ===========================================================================
section('1. The frequencies are astronomy, not fitting');
// Every constituent speed NOAA publishes is an integer combination of six
// rates of change of angles in the solar system. If this check passes, no
// frequency on the page was ever measured from water.

{
  const rateVec = [RATES.T, RATES.s, RATES.h, RATES.p, RATES.Np, RATES.p1];
  let worst = 0, worstName = '', n = 0;
  for (const hc of harcon.boston.HarmonicConstituents) {
    const def = BY_NAME.get(hc.name);
    const mine = (def.speedDoodson || def.doodson).reduce((a, k, i) => a + k * rateVec[i], 0);
    const d = Math.abs(mine - hc.speed);
    if (d > worst) { worst = d; worstName = hc.name; }
    n++;
  }
  fx('nConstituents', n);
  fx('speedWorstDeg', worst);
  check(`all ${n} published speeds reconstructed from six astronomical rates`,
    n === 37 && worst < 1e-5,
    `worst |diff| = ${worst.toExponential(2)} deg/hr (${worstName}); NOAA prints speeds to 6 decimals`);

  // and the six rates themselves are the derivatives of the mean-longitude
  // polynomials, not independent inputs
  const P = MEAN_LONGITUDE_POLYNOMIALS;
  check('the six rates are derived from the mean-longitude polynomials',
    Math.abs(RATES.s - P.s[1] / (36525 * 24)) < 1e-15 &&
    Math.abs(RATES.Np + P.N[1] / (36525 * 24)) < 1e-15,
    `ds/dt = ${RATES.s.toFixed(7)}, dh/dt = ${RATES.h.toFixed(7)} deg/hr`);
  fx('rateS', RATES.s); fx('rateH', RATES.h);
}

// ===========================================================================
section('2. The astronomy agrees with an independent source');
// Schureman's 1900-epoch polynomials against Meeus's J2000 ones. Two different
// books, two different epochs, the same sky.
{
  const meeus = (jd) => {
    const T = (jd - 2451545.0) / 36525;
    return {
      s: norm(218.3164477 + 481267.88123421 * T - 0.0015786 * T * T + T ** 3 / 538841),
      h: norm(280.46646 + 36000.76983 * T + 0.0003032 * T * T),
      N: norm(125.04452 - 1934.136261 * T + 0.0020708 * T * T + T ** 3 / 450000),
    };
  };
  let worst = 0, at = '';
  for (const iso of ['1950-06-15T00:00:00Z', '2000-01-01T12:00:00Z',
                     '2023-01-01T00:00:00Z', '2040-09-01T18:00:00Z']) {
    const d = new Date(iso);
    const jd = d.getTime() / 86400000 + 2440587.5;
    const a = astro(d), m = meeus(jd);
    for (const k of ['s', 'h', 'N']) {
      let e = Math.abs(((a[k] - m[k] + 540) % 360) - 180);
      if (e > worst) { worst = e; at = `${k} at ${iso.slice(0, 10)}`; }
    }
  }
  fx('meeusWorstDeg', worst);
  check('Schureman (1900 epoch) and Meeus (J2000 epoch) agree on s, h and N',
    worst < 0.03,
    `worst |diff| = ${worst.toFixed(4)} deg (${at}) over 1950-2040. ` +
    `On M2 that is ${(2 * worst * 60).toFixed(1)} arcminutes of phase, or ` +
    `${(2 * worst / 28.9841042 * 3600).toFixed(1)} seconds of tide`);

  check('Schureman\'s printed mean obliquity factors are reproduced from omega and i',
    Math.abs(MEAN_OBLIQUITY.M2 - 0.9154) < 5e-5 && Math.abs(MEAN_OBLIQUITY.O1 - 0.3800) < 5e-5 &&
    Math.abs(MEAN_OBLIQUITY.Mm - 0.5021) < 5e-5 && Math.abs(MEAN_OBLIQUITY.Mf - 0.1578) < 5e-5 &&
    Math.abs(MEAN_OBLIQUITY.J1 - 0.7214) < 5e-5 && Math.abs(MEAN_OBLIQUITY.OO1 - 0.0164) < 5e-5 &&
    Math.abs(MEAN_OBLIQUITY.M3 - 0.8758) < 5e-5,
    `M2 ${MEAN_OBLIQUITY.M2.toFixed(5)} (prints 0.9154), O1 ${MEAN_OBLIQUITY.O1.toFixed(5)} (0.3800), ` +
    `Mm ${MEAN_OBLIQUITY.Mm.toFixed(5)} (0.5021), Mf ${MEAN_OBLIQUITY.Mf.toFixed(5)} (0.1578), ` +
    `J1 ${MEAN_OBLIQUITY.J1.toFixed(5)} (0.7214), OO1 ${MEAN_OBLIQUITY.OO1.toFixed(5)} (0.0164), ` +
    `M3 ${MEAN_OBLIQUITY.M3.toFixed(5)} (0.8758)`);

  check('the polynomial epoch is Schureman\'s: Greenwich mean noon, 1899 December 31',
    EPOCH_JD === 2415020.0,
    'half a day of Moon is 6.59 deg, which is 13.2 deg on M2, and nothing errors');
}

// ===========================================================================
section('3. The nodal geometry has the shape it must have');
// xi and nu are angles in a spherical triangle that degenerates at N = 0 and
// N = 180. Both must vanish there. This is the check that catches the
// tempting wrong assignment of the two Napier analogies.
{
  let worst = 0;
  for (const N of [0, 180, 360]) {
    const a = auxiliary(N, 100);
    worst = Math.max(worst, Math.abs(a.xi), Math.abs(a.nu));
  }
  check('xi and nu vanish at N = 0 and N = 180', worst < 1e-9,
    `max |xi|, |nu| there = ${worst.toExponential(2)} deg`);

  // I sweeps the full 18.28 to 28.60 degree range over the nodal cycle
  let Imin = 90, Imax = 0, xiMax = 0, nuMax = 0;
  for (let N = 0; N < 360; N += 0.05) {
    const a = auxiliary(N, 0);
    Imin = Math.min(Imin, a.I); Imax = Math.max(Imax, a.I);
    xiMax = Math.max(xiMax, Math.abs(a.xi)); nuMax = Math.max(nuMax, Math.abs(a.nu));
  }
  fx('Imin', Imin); fx('Imax', Imax); fx('xiMax', xiMax); fx('nuMax', nuMax);
  check('the Moon-equator inclination I sweeps omega +/- i over the nodal cycle',
    Math.abs(Imin - (OMEGA - INC_I)) < 0.001 && Math.abs(Imax - (OMEGA + INC_I)) < 0.001,
    `I from ${Imin.toFixed(3)} to ${Imax.toFixed(3)} deg (omega = ${OMEGA}, i = ${INC_I})`);

  // and the node factor of M2 therefore swings by a known amount
  let fmin = 9, fmax = 0;
  for (let N = 0; N < 360; N += 0.05) {
    const f = nodeFactors(auxiliary(N, 0)).M2;
    fmin = Math.min(fmin, f); fmax = Math.max(fmax, f);
  }
  fx('fM2min', fmin); fx('fM2max', fmax);
  check('f(M2) swings over the 18.61-year nodal cycle', fmax - fmin > 0.07,
    `${fmin.toFixed(4)} to ${fmax.toFixed(4)}, i.e. ${((fmax / fmin - 1) * 100).toFixed(1)}% peak to peak`);
  fx('nodalCycleYears', 360 / (RATES.Np * 24 * 365.2422));
}

// ===========================================================================
section('4. NOAA\'s own node factors, measured out of their published series');
// A prediction series contains f_i * A_i * cos(V0_i + u_i - kappa_i). Fit it in
// a basis of bare cos(V0), sin(V0) and the recovered coefficients hand back
// f_i * A_i and (kappa_i - u_i). NOAA publishes A_i and kappa_i, so this reads
// NOAA's f and u straight off their own arithmetic. No fitting to our answer:
// the basis contains no node factor at all.
const YEARS = [2013, 2016, 2019, 2023, 2026];
const measuredNodal = {};   // year -> name -> {f, u}
{
  for (const year of YEARS) {
    const file = `pred-boston-${year}-hourly.json`;
    if (!have(file)) { console.log(`  ..   ${year} series absent, skipping`); continue; }
    const y = load(file).predictions.map(r => parseFloat(r.v));
    const yearStart = new Date(Date.UTC(year, 0, 1));
    const s0 = constituentState(yearStart, CONSTITUENTS).state;
    const defs = harcon.boston.HarmonicConstituents.map(c => BY_NAME.get(c.name));
    const m = defs.length, n = 2 * m + 1;
    const V0 = defs.map(d => s0.get(d.name).V0), sp = defs.map(d => speedOf(d));
    const ATA = Array.from({ length: n }, () => new Float64Array(n));
    const ATb = new Float64Array(n), row = new Float64Array(n);
    for (let k = 0; k < y.length; k++) {
      row[0] = 1;
      for (let i = 0; i < m; i++) {
        const a = (V0[i] + sp[i] * k) * D2R;
        row[1 + 2 * i] = Math.cos(a); row[2 + 2 * i] = Math.sin(a);
      }
      for (let i = 0; i < n; i++) { ATb[i] += row[i] * y[k]; for (let j = 0; j <= i; j++) ATA[i][j] += row[i] * row[j]; }
    }
    for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) ATA[i][j] = ATA[j][i];
    const L = Array.from({ length: n }, () => new Float64Array(n));
    for (let i = 0; i < n; i++) for (let j = 0; j <= i; j++) {
      let s = ATA[i][j]; for (let k2 = 0; k2 < j; k2++) s -= L[i][k2] * L[j][k2];
      if (i === j) L[i][i] = Math.sqrt(s); else L[i][j] = s / L[j][j];
    }
    const yv = new Float64Array(n);
    for (let i = 0; i < n; i++) { let s = ATb[i]; for (let k = 0; k < i; k++) s -= L[i][k] * yv[k]; yv[i] = s / L[i][i]; }
    const x = new Float64Array(n);
    for (let i = n - 1; i >= 0; i--) { let s = yv[i]; for (let k = i + 1; k < n; k++) s -= L[k][i] * x[k]; x[i] = s / L[i][i]; }
    const out = {};
    harcon.boston.HarmonicConstituents.forEach((c, i) => {
      const C = x[1 + 2 * i], S = x[2 + 2 * i];
      let u = norm(c.phase_GMT - norm(Math.atan2(S, C) / D2R));
      if (u > 180) u -= 360;
      out[c.name] = { f: Math.hypot(C, S) / c.amplitude, u, A: c.amplitude };
    });
    measuredNodal[year] = out;
  }

  const mid = (year) => new Date(Date.UTC(year, 6, 2, 12));
  let worstF = 0, wfName = '', worstU = 0, wuName = '', nComp = 0;
  const m1rows = [];
  for (const year of Object.keys(measuredNodal).map(Number)) {
    const st = constituentState(mid(year), CONSTITUENTS).state;
    for (const [name, meas] of Object.entries(measuredNodal[year])) {
      if (meas.A < 0.004) continue;            // below NOAA's own printed precision
      const ours = st.get(name);
      let uOurs = norm(ours.u); if (uOurs > 180) uOurs -= 360;
      let du = meas.u - uOurs; while (du > 180) du -= 360; while (du < -180) du += 360;
      const df = Math.abs(meas.f / ours.f - 1);
      if (name === 'M1') { m1rows.push({ year, measured: meas.u, ours: uOurs, df }); continue; }
      nComp++;
      if (df > worstF) { worstF = df; wfName = `${name} ${year}`; }
      if (Math.abs(du) > worstU) { worstU = Math.abs(du); wuName = `${name} ${year}`; }
    }
  }
  fx('nodalComparisons', nComp);
  fx('nodalWorstFpct', worstF * 100);
  fx('nodalWorstUdeg', worstU);
  // the full table, for the page to print rather than summarise
  fx('nodalMeasured', Object.fromEntries(Object.entries(measuredNodal).map(([year, byName]) => {
    const st = constituentState(mid(+year), CONSTITUENTS).state;
    const rowsOut = [];
    for (const [name, meas] of Object.entries(byName)) {
      if (meas.A < 0.004) continue;
      const ours = st.get(name);
      let uOurs = norm(ours.u); if (uOurs > 180) uOurs -= 360;
      rowsOut.push({
        name, A: meas.A,
        fNoaa: +meas.f.toFixed(4), fOurs: +ours.f.toFixed(4),
        uNoaa: +meas.u.toFixed(2), uOurs: +uOurs.toFixed(2),
      });
    }
    rowsOut.sort((a, b) => b.A - a.A);
    return [year, rowsOut];
  })));
  check(`our node factors match NOAA's own, over ${YEARS.length} years spanning the nodal cycle`,
    worstF < 0.005,
    `${nComp} comparisons, worst = ${(worstF * 100).toFixed(2)}% (${wfName})`);
  check('our nodal phases match NOAA\'s own',
    worstU < 0.25,
    `worst = ${worstU.toFixed(2)} deg (${wuName})`);

  // M1 gets its own check because it is the one that had to be found rather
  // than copied: Schureman's argument for it omits p and his tabulated speed
  // includes it, so a frozen-for-the-year Q anchors the perigee at mid-year.
  const m1df = Math.max(...m1rows.map(r => r.df));
  const m1spread = Math.max(...m1rows.map(r => {
    let d = r.measured - r.ours; while (d > 180) d -= 360; while (d < -180) d += 360; return Math.abs(d);
  }));
  fx('m1Rows', m1rows.map(r => ({ year: r.year, measured: +r.measured.toFixed(2), ours: +r.ours.toFixed(2) })));
  fx('m1WorstFpct', m1df * 100);
  fx('m1WorstUdeg', m1spread);
  fx('perigeeHalfYearDeg', RATES.p * 24 * 182.6212);
  check('M1, the constituent whose frequency and whose argument disagree',
    m1df < 0.005 && m1spread < 0.5,
    `node factor within ${(m1df * 100).toFixed(2)}%, nodal phase within ${m1spread.toFixed(2)} deg, ` +
    `over all ${m1rows.length} years. Reading M1's argument as if it contained p costs ` +
    `${(RATES.p * 24 * 182.6212).toFixed(2)} deg, half a year of lunar perigee`);
}

// ===========================================================================
section('5. Which instant NOAA freezes the nodal terms at, determined not assumed');
{
  const year = 2023;
  const file = `pred-boston-${year}-hourly.json`;
  const grid = [];
  if (have(file)) {
    const y = load(file).predictions.map(r => parseFloat(r.v));
    const rows = stationFromHarcon(harcon.boston);
    const yearStart = new Date(Date.UTC(year, 0, 1));
    const s0 = constituentState(yearStart, CONSTITUENTS).state;
    const pts = {
      'start of year': new Date(Date.UTC(year, 0, 1)),
      'middle of year': new Date(Date.UTC(year, 6, 2, 12)),
      'end of year': new Date(Date.UTC(year + 1, 0, 1)),
    };
    for (const [fn, fd] of Object.entries(pts)) {
      const sf = constituentState(fd, CONSTITUENTS).state;
      for (const [un, ud] of Object.entries(pts)) {
        const su = constituentState(ud, CONSTITUENTS).state;
        const terms = rows.map(r => ({
          f: sf.get(r.name).f, A: r.A, speed: r.speed,
          phase: norm(s0.get(r.name).V0 + su.get(r.name).u - r.kappa),
        }));
        let ss = 0;
        for (let i = 0; i < y.length; i++) {
          let h = 0;
          for (const t of terms) h += t.f * t.A * Math.cos((t.speed * i + t.phase) * D2R);
          ss += (h - y[i]) ** 2;
        }
        grid.push({ f: fn, u: un, rms: Math.sqrt(ss / y.length) });
      }
    }
    grid.sort((a, b) => a.rms - b.rms);
    fx('conventionGrid', grid.map(g => ({ f: g.f, u: g.u, rms: +g.rms.toFixed(5) })));
    check('the best fit to NOAA\'s year is f and u both at the middle of the year',
      grid[0].f === 'middle of year' && grid[0].u === 'middle of year',
      `best ${(grid[0].rms * 100).toFixed(2)} cm, worst of the nine ${(grid[grid.length - 1].rms * 100).toFixed(2)} cm`);
  } else {
    check('convention grid', false, 'year series absent');
  }
}

// ===========================================================================
section('6. Forward: our machine against NOAA\'s published predictions');
const forward = [];
{
  const start = new Date('2024-01-01T00:00:00Z');
  for (const [slug, label] of STATIONS) {
    const rows = stationFromHarcon(harcon[slug], { skipUnknown: true });
    const pred = parseSeries(load(`pred-${slug}-2024-01.json`));
    const noaa = Float64Array.from(pred.map(p => p.value));
    const ours = series(rows, start, noaa.length, 6, 'annual');
    const nonodal = series(rows, start, noaa.length, 6, 'nonodal');
    const range = Math.max(...noaa) - Math.min(...noaa);

    // isolate M1: refit the difference on M1 alone and remove it
    const diff = pred.map((p, i) => ({ date: p.date, value: p.value - ours[i] }));
    const fit = harmonicFit(diff, ['M1', 'M2', 'S2', 'N2', 'K1', 'O1'], 'annual');
    const m1A = fit.fitted.find(f => f.name === 'M1').A;

    forward.push({
      slug, label,
      published: harcon[slug].HarmonicConstituents.length,
      used: rows.length, skipped: rows.skipped.length,
      range,
      rms: rms(ours, noaa).rms,
      max: maxAbsDiff(ours, noaa).max,
      nonodalRms: rms(nonodal, noaa).rms,
      m1Line: m1A,
      afterM1: fit.residualRms,
    });
  }
  fx('forward', forward.map(f => ({
    slug: f.slug, label: f.label, published: f.published, used: f.used,
    range: +f.range.toFixed(2), rms: +f.rms.toFixed(4), max: +f.max.toFixed(4),
    nonodalRms: +f.nonodalRms.toFixed(4), m1Line: +f.m1Line.toFixed(4),
    afterM1: +f.afterM1.toFixed(5),
  })));

  const full37 = forward.filter(f => f.skipped === 0);
  const worst = Math.max(...full37.map(f => f.rms));
  fx('forwardWorstRms', worst);
  check(`${full37.length} harbours reconstructed from their published 37 numbers`,
    worst < 0.08,
    `RMS vs NOAA over January 2024: ${full37.map(f => (f.rms * 100).toFixed(1)).join(', ')} cm; ` +
    `tidal ranges ${full37.map(f => f.range.toFixed(1)).join(', ')} m`);

  const worstAfter = Math.max(...full37.map(f => f.afterM1));
  fx('forwardWorstAfterM1', worstAfter);
  check('with M1 and five majors removed, the residual falls to NOAA\'s printing precision',
    worstAfter < 0.0006,
    `worst ${(worstAfter * 1000).toFixed(2)} mm; NOAA prints heights to the millimetre, ` +
    `so a uniform rounding error alone has RMS 0.29 mm`);

  const ratio = full37.map(f => f.nonodalRms / f.rms);
  fx('nonodalRatioMin', Math.min(...ratio));
  check('negative control: ignoring the 18.61-year nodal cycle makes it worse everywhere',
    Math.min(...ratio) > 1.2,
    `f = 1, u = 0 costs ${Math.min(...ratio).toFixed(1)}x to ${Math.max(...ratio).toFixed(1)}x the error`);

  const anch = forward.find(f => f.slug === 'anchorage');
  fx('anchoragePublished', anch.published);
  fx('anchorageRms', anch.rms);
  check('Anchorage is the harbour where 37 numbers are not enough',
    anch.published > 100 && anch.rms > 5 * worst,
    `NOAA publishes ${anch.published} constituents there, not 37; with 37 our error is ` +
    `${(anch.rms * 100).toFixed(0)} cm against ${(worst * 100).toFixed(1)} cm at the worst 37-constituent harbour`);
}

// ===========================================================================
section('7. Backward: the analyser recovers the table from the water');
const backward = [];
{
  for (const [slug, label] of STATIONS) {
    const hourly = parseSeries(load(`hourly-${slug}-2023.json`)).filter(s => Number.isFinite(s.value));
    const names = harcon[slug].HarmonicConstituents.filter(c => BY_NAME.has(c.name)).map(c => c.name);
    const fit = harmonicFit(hourly, names, 'annual');
    const pub = new Map(harcon[slug].HarmonicConstituents.map(c => [c.name, c]));
    const rowsOut = fit.fitted.map(f => {
      const p = pub.get(f.name);
      let dk = f.kappa - p.phase_GMT; while (dk > 180) dk -= 360; while (dk < -180) dk += 360;
      return { name: f.name, pubA: p.amplitude, A: f.A, dA: f.A - p.amplitude, pubK: p.phase_GMT, kappa: f.kappa, dK: dk };
    });
    const majors = rowsOut.filter(r => r.pubA >= 0.05);
    backward.push({
      slug, label, n: hourly.length,
      residualRms: fit.residualRms,
      worstMajorDA: Math.max(...majors.map(r => Math.abs(r.dA))),
      worstMajorDK: Math.max(...majors.map(r => Math.abs(r.dK))),
      majors: rowsOut.filter(r => r.pubA >= 0.05).map(r => ({
        name: r.name, pubA: r.pubA, A: +r.A.toFixed(4), pubK: r.pubK, kappa: +r.kappa.toFixed(1), dK: +r.dK.toFixed(2),
      })),
    });
  }
  fx('backward', backward.map(b => ({
    slug: b.slug, label: b.label, n: b.n,
    residualRms: +b.residualRms.toFixed(4),
    worstMajorDA: +b.worstMajorDA.toFixed(4),
    worstMajorDK: +b.worstMajorDK.toFixed(2),
    majors: b.majors,
  })));
  // First, the analyser against a signal whose answer is known exactly: NOAA's
  // own synthetic prediction series for the same year. If this does not close,
  // nothing said about real water means anything.
  {
    const pr = parseSeries(load('pred-boston-2023-hourly.json'));
    const names = harcon.boston.HarmonicConstituents.map(c => c.name);
    const fit = harmonicFit(pr, names, 'annual');
    const pub = new Map(harcon.boston.HarmonicConstituents.map(c => [c.name, c]));
    let wa = 0, wk = 0, wkn = '';
    for (const f of fit.fitted) {
      const p = pub.get(f.name);
      wa = Math.max(wa, Math.abs(f.A - p.amplitude));
      if (p.amplitude >= 0.01) {
        let dk = f.kappa - p.phase_GMT; while (dk > 180) dk -= 360; while (dk < -180) dk += 360;
        if (Math.abs(dk) > wk) { wk = Math.abs(dk); wkn = f.name; }
      }
    }
    fx('roundTripWorstDAmm', wa * 1000); fx('roundTripWorstDK', wk);
    check('round trip: synthesise NOAA\'s table, then analyse it back',
      wa < 0.0002 && wk < 0.3,
      `every one of the 37 recovered to within ${(wa * 1000).toFixed(2)} mm and ` +
      `${wk.toFixed(2)} deg (worst ${wkn}); series residual ${(fit.residualRms * 1000).toFixed(2)} mm`);
  }

  // Now real water. The meteorological long-period terms are held out on
  // purpose: Sa and Ssa are the annual and semiannual WEATHER cycle, which NOAA
  // derives from a twenty-year analysis, and one year is not twenty.
  const METEOROLOGICAL = new Set(['SA', 'SSA', 'MSF', 'MM', 'MF']);
  const full37 = backward.filter(b => b.slug !== 'anchorage');
  let wa = 0, wan = '', wk = 0, wkn = '';
  let waTop = 0, waTopN = '', wkTop = 0, wkTopN = '';
  for (const b of full37) {
    const top = b.majors.filter(m => !METEOROLOGICAL.has(m.name))
      .sort((x, y) => y.pubA - x.pubA).slice(0, 5).map(m => m.name);
    for (const m of b.majors) {
      if (METEOROLOGICAL.has(m.name)) continue;
      const rel = Math.abs(m.A - m.pubA) / m.pubA;
      if (rel > wa) { wa = rel; wan = `${m.name} at ${b.label}`; }
      if (Math.abs(m.dK) > wk) { wk = Math.abs(m.dK); wkn = `${m.name} at ${b.label}`; }
      if (top.includes(m.name)) {
        if (rel > waTop) { waTop = rel; waTopN = `${m.name} at ${b.label}`; }
        if (Math.abs(m.dK) > wkTop) { wkTop = Math.abs(m.dK); wkTopN = `${m.name} at ${b.label}`; }
      }
    }
  }
  fx('backwardWorstRelPct', wa * 100); fx('backwardWorstDK', wk);
  fx('backwardTopRelPct', waTop * 100); fx('backwardTopDK', wkTop);
  fx('backwardWorstName', wan);
  check('one year of real water re-derives the constituents that carry the tide',
    waTop < 0.35 && wkTop < 15,
    `at the nine 37-constituent harbours, the five largest astronomical constituents each ` +
    `came back within ${(waTop * 100).toFixed(1)}% (${waTopN}) and ${wkTop.toFixed(1)} deg (${wkTopN}) ` +
    `of NOAA's published table, which is itself a five-year vector average, not a one-year fit`);

  const bos = backward.find(b => b.slug === 'boston');
  const m2 = bos.majors.find(m => m.name === 'M2');
  fx('bostonM2', m2);
  check('Boston M2, from the water alone, with no tide table consulted',
    Math.abs(m2.A - m2.pubA) < 0.02,
    `we get ${m2.A.toFixed(3)} m at ${m2.kappa.toFixed(1)} deg; NOAA publishes ${m2.pubA.toFixed(3)} m at ${m2.pubK.toFixed(1)} deg`);

  fx('backwardResidualBoston', bos.residualRms);
  check('what the harmonic method cannot explain is the weather',
    bos.residualRms > 0.05 && bos.residualRms < 0.5,
    `at Boston the unexplained part of 2023 has RMS ${(bos.residualRms * 100).toFixed(1)} cm, ` +
    `against a ${forward.find(f => f.slug === 'boston').range.toFixed(1)} m tidal range`);
}

// ===========================================================================
section('7b. The constant that is not constant: L2, one year at a time');
// The one place a single year of water and NOAA's published table genuinely
// part company. We show the decade rather than average it away, and we do not
// claim to have settled why.
{
  const decade = {};
  for (const slug of ['boston', 'eastport']) {
    const names = harcon[slug].HarmonicConstituents.map(c => c.name);
    const rowsOut = [];
    for (let year = 2015; year <= 2024; year++) {
      const file = `hourly-${slug}-${year}.json`;
      if (!have(file)) continue;
      const smp = parseSeries(load(file)).filter(s => Number.isFinite(s.value));
      const fit = harmonicFit(smp, names, 'annual');
      const nodal = constituentState(new Date(Date.UTC(year, 6, 2, 12)), CONSTITUENTS).state;
      const pick = (n) => fit.fitted.find(f => f.name === n);
      rowsOut.push({
        year, n: smp.length,
        M2: +pick('M2').A.toFixed(4), S2: +pick('S2').A.toFixed(4),
        N2: +pick('N2').A.toFixed(4), K1: +pick('K1').A.toFixed(4),
        L2: +pick('L2').A.toFixed(4), L2phase: +pick('L2').kappa.toFixed(1),
        fL2: +nodal.get('L2').f.toFixed(3),
      });
    }
    decade[slug] = rowsOut;
  }
  fx('decade', decade);

  const pubOf = (slug, n) => harcon[slug].HarmonicConstituents.find(c => c.name === n).amplitude;
  for (const name of ['M2', 'S2', 'K1']) {
    const spread = Math.max(...['boston', 'eastport'].map(slug => {
      const v = decade[slug].map(r => r[name]);
      return (Math.max(...v) - Math.min(...v)) / pubOf(slug, name);
    }));
    check(`${name} is the same every year, to within ${(spread * 100).toFixed(1)}%`,
      spread < 0.05,
      `ten separate one-year analyses at two harbours`);
    fx(`decadeSpread${name}`, spread * 100);
  }

  const l2 = ['boston', 'eastport'].map(slug => {
    const v = decade[slug].map(r => r.L2);
    return { slug, min: Math.min(...v), max: Math.max(...v), pub: pubOf(slug, 'L2') };
  });
  fx('decadeL2', l2);
  const l2Ratio = Math.min(...l2.map(x => x.max / x.min));
  fx('decadeL2Ratio', l2Ratio);
  check('L2 is not, and the two harbours swing together',
    l2Ratio > 1.8,
    l2.map(x => `${x.slug} ${x.min.toFixed(3)} to ${x.max.toFixed(3)} m (published ${x.pub})`).join('; '));

  // The swing anticorrelates with the node factor we divided out. That is the
  // clue we can state; it is not a resolution, and we do not pretend otherwise.
  const corr = (() => {
    const xs = [], ys = [];
    for (const slug of ['boston', 'eastport'])
      for (const r of decade[slug]) { xs.push(r.fL2); ys.push(r.L2 / pubOf(slug, 'L2')); }
    const mx = xs.reduce((a, b) => a + b) / xs.length, my = ys.reduce((a, b) => a + b) / ys.length;
    let sxy = 0, sx = 0, sy = 0;
    for (let i = 0; i < xs.length; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sx += (xs[i] - mx) ** 2; sy += (ys[i] - my) ** 2; }
    return sxy / Math.sqrt(sx * sy);
  })();
  fx('decadeL2Corr', corr);
  fx('perigeeHalfCycleYears', 180 / (RATES.p * 24 * 365.2422));
  check('and it moves against the node factor Schureman tells us to divide out',
    corr < -0.5,
    `Pearson r = ${corr.toFixed(2)} between f(L2) and the recovered L2, over 20 harbour-years. ` +
    `f(L2) turns on 2P, which repeats every ${(180 / (RATES.p * 24 * 365.2422)).toFixed(2)} years. ` +
    `We have not established whether the fault is the harbour or the correction`);
}

// ===========================================================================
section('8. How long a record you need: the Rayleigh criterion, made to bite');
{
  const names = harcon.boston.HarmonicConstituents.map(c => c.name);
  const hourly = parseSeries(load('hourly-boston-2023.json')).filter(s => Number.isFinite(s.value));
  const pub = new Map(harcon.boston.HarmonicConstituents.map(c => [c.name, c]));
  const sepHours = 360 / Math.abs(speedOf(BY_NAME.get('M2')) - speedOf(BY_NAME.get('N2')));
  fx('m2n2SeparationDays', sepHours / 24);
  const runs = [];
  for (const days of [7, 15, 29, 90, 365]) {
    const sub = hourly.slice(0, days * 24);
    let out;
    try {
      const fit = harmonicFit(sub, names, 'annual');
      const f = fit.fitted.find(x => x.name === 'M2');
      out = { days, A: f.A, dA: f.A - pub.get('M2').amplitude, ok: true };
    } catch (e) { out = { days, ok: false, err: e.message }; }
    runs.push(out);
  }
  fx('rayleighRuns', runs.map(r => ({ days: r.days, ok: r.ok, A: r.ok ? +r.A.toFixed(4) : null, dA: r.ok ? +r.dA.toFixed(4) : null })));
  const long = runs.find(r => r.days === 365);
  const singular = runs.filter(r => !r.ok).map(r => r.days);
  const solvable = runs.filter(r => r.ok);
  check('M2 and N2 need 27.55 days of record to be told apart',
    Math.abs(sepHours / 24 - 27.55) < 0.05,
    `360 / (speed difference) = ${(sepHours / 24).toFixed(2)} days, the anomalistic month, ` +
    `which is how long it takes the Moon to return to perigee`);
  check('below that, the problem is not inaccurate; it has no solution',
    singular.length > 0,
    `asking 37 constituents of ${singular.join(' and ')} days of water leaves the normal ` +
    `equations singular, and the solver refuses rather than returning a plausible number`);
  const shortest = solvable[0];
  check('and just above it, a short record gives the wrong M2',
    Math.abs(shortest.dA) > 3 * Math.abs(long.dA),
    solvable.map(r => `${r.days} d: ${r.A.toFixed(3)} m (${r.dA >= 0 ? '+' : ''}${(r.dA * 100).toFixed(1)} cm)`).join('; ') +
    `; NOAA publishes ${pub.get('M2').amplitude.toFixed(3)} m`);
}

// ===========================================================================
section('9. What kind of tide: the form factor, and what it predicts');
{
  const rowsOut = [];
  for (const [slug, label] of STATIONS) {
    const c = Object.fromEntries(harcon[slug].HarmonicConstituents.map(h => [h.name, h.amplitude]));
    const F = (c.K1 + c.O1) / (c.M2 + c.S2);

    // Count high waters in NOAA's PUBLISHED January prediction series. A
    // semidiurnal harbour gets two a lunar day, 1.93; a purely diurnal one gets
    // one. Peaks must be four hours apart and stand a tenth of the month's
    // range above the water between them.
    //
    // Deliberately the prediction and not the measured record: at Key West the
    // month's whole range is 0.81 m, and wind puts turning points into the real
    // water that a peak counter cannot tell from tides. Counted off the
    // measured record instead, Key West reads 2.35 high waters a day and
    // Honolulu 2.32, which is weather being counted as tide. That is the same
    // residual section 11 finds at The Battery, only quieter.
    const pred = parseSeries(load(`pred-${slug}-2024-01.json`));
    const v = pred.map(o => o.value);
    const range = Math.max(...v) - Math.min(...v);
    const hw = peaks(v, 40, 0.10 * range);       // 40 samples of 6 min = 4 hours
    const spanDays = (pred[pred.length - 1].date - pred[0].date) / 86400e3;
    const highsPerDay = hw.length / spanDays;

    // and the same count off the raw water, reported so the gap is visible
    const obs = parseSeries(load(`obs-${slug}-2024-01.json`));
    const ov = obs.map(o => o.value);
    const ofin = ov.filter(Number.isFinite);
    const orange = Math.max(...ofin) - Math.min(...ofin);
    const ohw = peaks(ov, 40, 0.10 * orange);
    const obsHighsPerDay = ohw.length / (ofin.length * 6 / 1440);

    rowsOut.push({
      slug, label, F, kind: F < 0.25 ? 'semidiurnal' : F < 1.5 ? 'mixed' : 'diurnal',
      highsPerDay, obsHighsPerDay, range,
    });
  }
  rowsOut.sort((a, b) => a.F - b.F);
  fx('formFactors', rowsOut.map(r => ({
    slug: r.slug, label: r.label, F: +r.F.toFixed(3), kind: r.kind,
    highsPerDay: +r.highsPerDay.toFixed(2), obsHighsPerDay: +r.obsHighsPerDay.toFixed(2),
    range: +r.range.toFixed(2),
  })));
  const notDiurnal = rowsOut.filter(r => r.kind !== 'diurnal');
  const diur = rowsOut.filter(r => r.kind === 'diurnal');
  check('the form factor sorts the harbours, and the tide table agrees',
    diur.length > 0 &&
    Math.min(...notDiurnal.map(r => r.highsPerDay)) > Math.max(...diur.map(r => r.highsPerDay)) + 0.3,
    `${notDiurnal.length} harbours with F below 1.5 had ${Math.min(...notDiurnal.map(r => r.highsPerDay)).toFixed(2)}-` +
    `${Math.max(...notDiurnal.map(r => r.highsPerDay)).toFixed(2)} high waters a day in January 2024; ` +
    `the ${diur.length} with F above 1.5 had ${Math.min(...diur.map(r => r.highsPerDay)).toFixed(2)}-` +
    `${Math.max(...diur.map(r => r.highsPerDay)).toFixed(2)}. Nobody told the counter what F said`);

  const corr = (() => {
    const xs = rowsOut.map(r => Math.log(r.F)), ys = rowsOut.map(r => r.highsPerDay);
    const mx = xs.reduce((a, b) => a + b) / xs.length, my = ys.reduce((a, b) => a + b) / ys.length;
    let sxy = 0, sx = 0, sy = 0;
    for (let i = 0; i < xs.length; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sx += (xs[i] - mx) ** 2; sy += (ys[i] - my) ** 2; }
    return sxy / Math.sqrt(sx * sy);
  })();
  fx('formFactorCorr', corr);
  check('and the two move together across the whole range', corr < -0.7,
    `Pearson r = ${corr.toFixed(3)} between log F, computed from four published amplitudes, ` +
    `and high waters a day, counted off a published tide table. The two numbers share no arithmetic`);

  const weatherGap = Math.max(...rowsOut.map(r => r.obsHighsPerDay - r.highsPerDay));
  const wgAt = rowsOut.find(r => r.obsHighsPerDay - r.highsPerDay === weatherGap);
  fx('weatherCountGap', weatherGap);
  check('counting high waters off raw water counts the weather too',
    weatherGap > 0.3,
    `at ${wgAt.label}, whose January range was ${wgAt.range.toFixed(2)} m, the same counter finds ` +
    `${wgAt.obsHighsPerDay.toFixed(2)} high waters a day in the measured record against ` +
    `${wgAt.highsPerDay.toFixed(2)} in the tide table`);
}

// ===========================================================================
section('10. Spring and neap are a beat, and the beat can be measured');
{
  const M2 = BY_NAME.get('M2'), S2 = BY_NAME.get('S2');
  const beatDays = 360 / Math.abs(speedOf(M2) - speedOf(S2)) / 24;
  fx('springNeapDays', beatDays);
  // measure it off a synthesised two-constituent tide
  const rows = [
    { name: 'M2', def: M2, A: 1.371, kappa: 109.2, speed: speedOf(M2) },
    { name: 'S2', def: S2, A: 0.208, kappa: 146.2, speed: speedOf(S2) },
  ];
  const N = 200 * 24 * 2; // 200 days at 30-minute steps
  const y = series(rows, new Date('2024-01-01T00:00:00Z'), N, 30, 'annual');
  // The envelope: the range of the water over a rolling 25-hour window. Its
  // maxima are the spring tides. Peaks must be at least 5 days apart, which is
  // well inside a fortnight and well outside the daily ripple.
  const win = 25 * 2;
  const env = [];
  for (let i = 0; i + win < N; i++) {
    let hi = -9, lo = 9;
    for (let j = i; j < i + win; j++) { hi = Math.max(hi, y[j]); lo = Math.min(lo, y[j]); }
    env.push(hi - lo);
  }
  const envRange = Math.max(...env) - Math.min(...env);
  const springs = peaks(env, 5 * 48, 0.3 * envRange);
  const gaps = [];
  for (let i = 1; i < springs.length; i++) gaps.push((springs[i] - springs[i - 1]) / 48);
  const meanGap = gaps.reduce((a, b) => a + b, 0) / gaps.length;
  fx('springNeapMeasured', meanGap);
  check('the spring-neap interval measured off our own curve is the synodic fortnight',
    Math.abs(meanGap - beatDays) < 0.1,
    `measured ${meanGap.toFixed(2)} days from ${gaps.length} intervals; ` +
    `360 / (M2 - S2 speed difference) = ${beatDays.toFixed(3)} days, half a synodic month`);
}

// ===========================================================================
section('11. The residual is weather: Sandy at The Battery');
{
  const obs = parseSeries(load('obs-battery-sandy-2012.json'));
  const pred = parseSeries(load('pred-battery-sandy-2012.json'));
  const byT = new Map(pred.map(p => [p.date.getTime(), p.value]));
  let peak = -9, peakAt = null;
  const resid = [];
  for (const o of obs) {
    if (!Number.isFinite(o.value) || !byT.has(o.date.getTime())) continue;
    const r = o.value - byT.get(o.date.getTime());
    resid.push({ date: o.date, r });
    if (r > peak) { peak = r; peakAt = o.date; }
  }
  const quiet = resid.filter(x => x.date < new Date('2012-10-28T00:00:00Z'));
  const quietRms = Math.sqrt(quiet.reduce((a, b) => a + b.r * b.r, 0) / quiet.length);
  fx('sandyPeakSurge', peak);
  fx('sandyPeakAt', peakAt.toISOString());
  fx('sandyQuietRms', quietRms);
  // and the observed water level itself
  let hi = -9, hiAt = null;
  for (const o of obs) if (Number.isFinite(o.value) && o.value > hi) { hi = o.value; hiAt = o.date; }
  fx('sandyPeakLevel', hi);
  check('the machine is not wrong during a hurricane; it is silent about wind',
    peak > 2.5 && quietRms < 0.2,
    `residual peaks at ${peak.toFixed(2)} m above prediction at ${peakAt.toISOString().replace('T', ' ').slice(0, 16)} UTC, ` +
    `against ${(quietRms * 100).toFixed(0)} cm RMS in the calm days before`);
  check('the surge, not the tide, made the record',
    hi > 2.5,
    `observed water level reached ${hi.toFixed(2)} m above MSL; the predicted tide that night ` +
    `never exceeded ${Math.max(...pred.filter(p => Number.isFinite(p.value)).map(p => p.value)).toFixed(2)} m`);
}

// ===========================================================================
section('12. Positive control: the instrument can return a positive');
// Every "no discrepancy" above is only evidence if the same test would have
// caught one. Inject a known error and confirm each check fires.
{
  const rows = stationFromHarcon(harcon.boston);
  const pred = parseSeries(load('pred-boston-2024-01.json'));
  const noaa = Float64Array.from(pred.map(p => p.value));
  const start = new Date('2024-01-01T00:00:00Z');
  const clean = rms(series(rows, start, noaa.length, 6, 'annual'), noaa).rms;

  const bent = rows.map(r => r.name === 'M2' ? { ...r, kappa: r.kappa + 1 } : r);
  const bentRms = rms(series(bent, start, noaa.length, 6, 'annual'), noaa).rms;
  check('a 1 degree error in one phase is visible to the comparison',
    bentRms > 1.3 * clean,
    `M2 phase + 1 deg takes the RMS from ${(clean * 100).toFixed(2)} cm to ${(bentRms * 100).toFixed(2)} cm`);

  const scaled = rows.map(r => r.name === 'M2' ? { ...r, A: r.A * 1.01 } : r);
  const scaledRms = rms(series(scaled, start, noaa.length, 6, 'annual'), noaa).rms;
  check('a 1 per cent error in one amplitude is visible too',
    scaledRms > 1.3 * clean,
    `M2 amplitude + 1% takes the RMS to ${(scaledRms * 100).toFixed(2)} cm`);

  // and the backward analyser recovers an amplitude we planted
  const synth = [];
  const t0 = new Date('2023-01-01T00:00:00Z');
  const plant = [{ name: 'M2', def: BY_NAME.get('M2'), A: 0.777, kappa: 42, speed: speedOf(BY_NAME.get('M2')) }];
  for (let i = 0; i < 8760; i++) {
    const d = new Date(t0.getTime() + i * 3600e3);
    synth.push({ date: d, value: heightAt(plant, d) });
  }
  const back = harmonicFit(synth, ['M2', 'S2', 'N2', 'K1', 'O1'], 'continuous');
  const got = back.fitted.find(f => f.name === 'M2');
  check('the analyser returns a planted amplitude and phase',
    Math.abs(got.A - 0.777) < 0.001 && Math.abs(norm(got.kappa - 42)) < 0.1,
    `planted 0.777 m at 42.0 deg, recovered ${got.A.toFixed(4)} m at ${got.kappa.toFixed(2)} deg`);
}

// ===========================================================================
section('13. The page runs this code, not a re-implementation of it');
{
  const PAGE = path.join(HERE, '..', '..', 'public', 'strata', 'no-water-in-the-machine');
  if (!existsSync(path.join(PAGE, 'machine'))) {
    check('the page carries the engine', false, 'run build-page.mjs');
  } else {
    const { ENGINE, forBrowser } = await import('./build-page.mjs').catch(() => ({}));
    const names = ENGINE || ['schureman', 'constituents', 'predict', 'analyze'];
    const rewrite = forBrowser || ((s) => s.replace(/(from '\.\/[a-zA-Z]+)\.mjs'/g, "$1.js'"));
    let bad = [];
    for (const n of names) {
      const mine = rewrite(readFileSync(path.join(HERE, `${n}.mjs`), 'utf8'));
      const theirs = readFileSync(path.join(PAGE, 'machine', `${n}.js`), 'utf8');
      if (mine !== theirs) bad.push(n);
    }
    fx('engineModules', names.length);
    check('the four engine modules the page serves are byte for byte these',
      bad.length === 0,
      `${names.length} modules; the only permitted edit is the extension in their own import lines` +
      (bad.length ? `; differ: ${bad.join(', ')}` : ''));

    // and the figures the page prints are the ones this apparatus computed
    const dataFile = path.join(PAGE, 'data.js');
    const figFile = path.join(HERE, 'figures.json');
    let fresh = false, why = 'data.js missing; run build-page.mjs';
    if (existsSync(dataFile) && existsSync(figFile)) {
      const embedded = JSON.stringify(JSON.parse(readFileSync(figFile, 'utf8')));
      fresh = readFileSync(dataFile, 'utf8').includes(embedded);
      why = fresh
        ? 'every figure the page prints is verbatim from figures.json'
        : 'data.js is stale: rerun `node verify.mjs --json` then `node build-page.mjs`';
    }
    check('the page prints this apparatus\'s figures and no others', fresh, why);
  }
}

// ===========================================================================
section('Result');
console.log(`\n  ${passed}/${passed + failed} checks passed\n`);

if (process.argv.includes('--json')) {
  const out = path.join(HERE, 'figures.json');
  const { writeFileSync } = await import('node:fs');
  writeFileSync(out, JSON.stringify({ generated: 'see git', passed, failed, FIG }, null, 1) + '\n');
  console.log(`  figures written to ${path.relative(process.cwd(), out)}`);
}

process.exit(failed === 0 ? 0 : 1);
