// verify-the-island-that-moves.mjs — every claim /strata/the-island-that-moves/ makes.
//
//   node verify-the-island-that-moves.mjs
//
// The rule this file exists to enforce: the page states nothing that is not
// re-derived here by a route that does not share the page's arithmetic. Where a
// closed form is claimed, it is checked against numerical differentiation or
// brute force. Where an astronomical quantity is claimed, it is checked against
// research/the-sky-above-you/ephem.mjs, which was written for a different page,
// by a different instance, and knows nothing about this one. Where a position is
// claimed, it is checked against the committed gazetteer responses.
//
// Several checks are deliberately CONTROLS: they assert that a wrong answer would
// have been caught. A check that cannot fail is not evidence.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as W from './research/the-island-that-moves/wayfinding.mjs';
import { COMPASS } from './research/the-island-that-moves/compass.mjs';
import { altAz, precessJ2000ToDate, julianDay } from './research/the-sky-above-you/ephem.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const R = (f) => path.join(HERE, 'research/the-island-that-moves', f);
const page = JSON.parse(fs.readFileSync(R('page.json'), 'utf8'));
const stars = JSON.parse(fs.readFileSync(R('stars.json'), 'utf8'));
const islands = JSON.parse(fs.readFileSync(R('islands.json'), 'utf8'));
const byId = new Map(stars.stars.map((s) => [s.id, s]));

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok    ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${extra ? '   ' + extra : ''}`); }
};
const near = (a, b, tol) => a !== null && b !== null && Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const section = (s) => console.log(`\n${s}`);

// ===========================================================================
section('1. The closed form for the rising azimuth, and its derivative');
// ===========================================================================

// 1.1 The equator theorem: A = 90 - dec exactly, for every star that rises.
{
  let worst = 0;
  for (let dec = -89; dec <= 89; dec += 0.37) {
    const a = W.risingAzimuth(dec, 0, 0);
    if (a === null) { fail++; console.log(`  FAIL  a star at dec ${dec} should rise on the equator`); break; }
    worst = Math.max(worst, Math.abs(a - (90 - dec)));
  }
  ok('on the equator, rising azimuth = 90 - declination, over 482 declinations',
    worst < 1e-9, `worst residual ${worst.toExponential(2)} deg`);
}

// 1.2 The same, on the actual compass, read out of page.json.
ok('page.json equator ruler: every compass point sits at 90 - dec',
  page.equatorRulerWorstResidual !== null && Math.abs(page.equatorRulerWorstResidual) < 1e-9,
  `worst residual ${page.equatorRulerWorstResidual} deg`);

// 1.3 CONTROL: the same identity must FAIL away from the equator, or check 1.1
//     was testing nothing.
{
  let anyResidual = 0;
  for (const dec of [20, 40, 60, -35]) {
    const a = W.risingAzimuth(dec, 20, 0);
    anyResidual = Math.max(anyResidual, Math.abs(a - (90 - dec)));
  }
  ok('CONTROL: at latitude 20 the same identity is measurably false',
    anyResidual > 0.5, `largest departure ${anyResidual.toFixed(3)} deg`);
}

// 1.4 dA/dphi = -cot(A) tan(phi), against symmetric finite difference.
{
  let worst = 0, worstAt = null, n = 0;
  for (let dec = -70; dec <= 70; dec += 2.3) {
    for (let lat = -60; lat <= 60; lat += 3.1) {
      const c = W.dAzimuthDLatitude(dec, lat);
      const num = W.dAzimuthDLatitudeNumeric(dec, lat);
      if (c === null || num === null) continue;
      n++;
      const e = Math.abs(c - num);
      if (e > worst) { worst = e; worstAt = `dec ${dec.toFixed(1)}, lat ${lat.toFixed(1)}`; }
    }
  }
  ok(`closed-form derivative matches finite difference at ${n} points`,
    worst < 1e-6, `worst ${worst.toExponential(2)} at ${worstAt}`);
}

// 1.5 The derivative is exactly zero on the equator, for every declination.
{
  let worst = 0;
  for (let dec = -80; dec <= 80; dec += 1.7) {
    const d = W.dAzimuthDLatitude(dec, 0);
    if (d !== null) worst = Math.max(worst, Math.abs(d));
  }
  ok('the derivative vanishes identically on the equator', worst === 0, `worst |dA/dphi| ${worst}`);
}

// 1.6 The derivative is exactly zero for a star on the celestial equator, at ANY
//     latitude: such a star rises due east everywhere.
{
  let worstAz = 0, worstD = 0;
  for (let lat = -70; lat <= 70; lat += 1.3) {
    worstAz = Math.max(worstAz, Math.abs(W.risingAzimuth(0, lat, 0) - 90));
    worstD = Math.max(worstD, Math.abs(W.dAzimuthDLatitude(0, lat)));
  }
  ok('a star on the celestial equator rises due east from every latitude',
    worstAz < 1e-12 && worstD < 1e-12, `worst |A-90| ${worstAz.toExponential(2)}`);
}

// ===========================================================================
section('2. Against an independent ephemeris (research/the-sky-above-you/ephem.mjs)');
// ===========================================================================

// 2.1 ephem.altAz() is a full alt/az routine written for another page. Sweep hour
//     angle finely, find where the star crosses altitude zero going up, and read
//     its azimuth there. That route shares no line of code with risingAzimuth().
{
  const jd0 = julianDay(2026, 1, 1) + 0.5;
  let worst = 0, worstAt = null, n = 0;
  for (const s of ['* alf Aql', '* alf Lyr', '* alf Sco', '* alf Cru', '* alf Tau', '* del Ori']) {
    const st = byId.get(s);
    for (const lat of [0, 7.382, 21.31, -17.65]) {
      // Find the rising crossing by scanning sidereal time, then BISECTING on
      // altitude to machine precision.
      //
      // Linear interpolation is not good enough here and the reason is worth
      // recording, because it is the same fact the page is about. For a star that
      // only grazes the horizon the azimuth is violently sensitive to altitude:
      // Acrux at latitude 21.3 moves 0.136 deg of azimuth per 0.1 deg of altitude,
      // against 0.00017 deg for the same star seen from the equator, a factor of
      // about 800. An interpolated crossing that is a thousandth of a degree off in
      // altitude is then a quarter of a degree off in azimuth, which is what the
      // first version of this check reported and wrongly read as a disagreement
      // between two ephemerides. Bisection removes it.
      // altAz() expects coordinates of the DATE, not J2000: planetGeo() in the same
      // file precesses before calling it. Feeding it J2000 while comparing against a
      // precessed declination was the whole of an apparent 0.24 deg disagreement on
      // Acrux, and it read exactly like two ephemerides differing. Precess once, use
      // the same numbers on both sides.
      const { ra: raD, dec: decOfDate } = precessJ2000ToDate(st.ra, st.dec, jd0);
      let prev = null, found = null;
      const SID = 0.9972695663;
      for (let k = 0; k <= 2000; k++) {
        const jd = jd0 + (k / 2000) * SID;
        const { alt, az } = altAz(raD, decOfDate, jd, lat, 0);
        if (prev && prev.alt < 0 && alt >= 0) {
          let a = jd0 + ((k - 1) / 2000) * SID, b = jd;
          for (let i = 0; i < 90; i++) {
            const m = (a + b) / 2;
            (altAz(raD, decOfDate, m, lat, 0).alt < 0) ? (a = m) : (b = m);
          }
          found = altAz(raD, decOfDate, (a + b) / 2, lat, 0).az;
          break;
        }
        prev = { alt, az };
      }
      if (found === null) continue;
      const mine = W.risingAzimuth(decOfDate, lat, 0);
      if (mine === null) continue;
      n++;
      const e = Math.abs(found - mine);
      if (e > worst) { worst = e; worstAt = `${st.name} at lat ${lat}`; }
    }
  }
  ok(`independent ephemeris agrees on the rising azimuth at ${n} star/latitude pairs`,
    n >= 20 && worst < 0.05, `worst ${worst.toFixed(4)} deg at ${worstAt}`);
}

// ===========================================================================
section('2b. The crowding near east is inherited from the stars, not made by the horizon');
// ===========================================================================

// 2b.1 At Satawal the declination-to-azimuth map is nearly the identity, so the
//      compass's uneven spacing is the stars' uneven spacing and not a projection
//      artefact. This is what lets the page say the Gladwin/Lewis disagreement is
//      about the right thing.
{
  const g = page.gapComparison;
  ok('every adjacent azimuth gap reproduces its declination gap to under a degree',
    g.worstExcessDeg < 1.0, `worst excess ${g.worstExcessDeg} deg, median ${g.medianExcessDeg} deg`);
  ok('the ring really is unevenly spaced, so there was something to explain',
    g.narrowestGapDeg < 3 && g.widestGapDeg > 20,
    `gaps run ${g.narrowestGapDeg} to ${g.widestGapDeg} deg against ${g.equalSpacingWouldBeDeg} if equal`);

  // CONTROL: the identity map is a fact about THIS latitude. Far from the equator
  // the same comparison must break badly, or the claim is vacuous.
  {
    let worst = 0;
    const east = page.compassAt.aotearoa
      .filter((c) => c.dec !== null && c.az !== null && c.az < 180)
      .sort((a, b) => a.az - b.az);
    for (let i = 1; i < east.length; i++) {
      worst = Math.max(worst, Math.abs(Math.abs(east[i].az - east[i - 1].az) - Math.abs(east[i].dec - east[i - 1].dec)));
    }
    ok('CONTROL: at Auckland the same comparison fails badly, so the agreement at Satawal is about latitude',
      worst > 5, `worst excess there ${worst.toFixed(2)} deg`);
  }
}

// 2b.2 Altair rises north of east by an amount Lewis states independently.
{
  const a = page.altairOffEast;
  ok('Altair rises north of east by close to the 8.5 degrees Lewis reports',
    Math.abs(a.northOfEastDeg - a.lewisStated) < 0.6,
    `computed ${a.northOfEastDeg} deg, Lewis 1972 states ${a.lewisStated} deg`);
}

// ===========================================================================
section('3. The compass is blind to the sign of your latitude');
// ===========================================================================

// 3.1 A(phi) = A(-phi) identically: cos(A) = sin(dec)/cos(phi) sees latitude only
//     through cos, which is even. Measured over the whole compass.
{
  let worst = 0;
  for (let lat = 0.5; lat <= 60; lat += 0.37) {
    for (const s of stars.stars) {
      const a = W.risingAzimuth(s.dec, lat, 0), b = W.risingAzimuth(s.dec, -lat, 0);
      if (a === null || b === null) continue;
      worst = Math.max(worst, Math.abs(a - b));
    }
  }
  ok('rising azimuth at +lat equals rising azimuth at -lat, over the whole catalogue',
    worst < 1e-12, `worst difference ${worst.toExponential(2)} deg`);
}

// 3.2 The same, as page.json reports it.
{
  const worst = Math.max(...page.hemisphereBlindness.map((h) => h.worstDifferenceDeg));
  ok('page.json hemisphere blindness table is identically zero', worst < 1e-12, `worst ${worst}`);
}

// 3.3 CONTROL: the ALTITUDE of a star is NOT symmetric in latitude, so the sky as
//     a whole is perfectly able to tell you the hemisphere. It is the compass
//     specifically that cannot. Without this the finding sounds like a claim about
//     the sky, which would be false.
{
  const jd = julianDay(2026, 6, 1) + 0.5;
  let biggest = 0;
  for (const s of ['* alf UMi', '* alf Cru']) {
    const st = byId.get(s);
    for (const lat of [7.382, 21.31]) {
      let hiN = -90, hiS = -90;
      for (let k = 0; k <= 720; k++) {
        const t = jd + (k / 720) * 0.9972695663;
        hiN = Math.max(hiN, altAz(st.ra, st.dec, t, lat, 0).alt);
        hiS = Math.max(hiS, altAz(st.ra, st.dec, t, -lat, 0).alt);
      }
      biggest = Math.max(biggest, Math.abs(hiN - hiS));
    }
  }
  ok('CONTROL: star ALTITUDE does distinguish the hemispheres, so the blindness is the compass’s, not the sky’s',
    biggest > 10, `largest culmination difference ${biggest.toFixed(2)} deg`);
}

// ===========================================================================
section('4. What the compass does across the voyaging ranges');
// ===========================================================================

// 4.1 At Satawal every compass point is within a degree of its equatorial seat.
{
  const w = page.worstDisplacement.satawal;
  ok('at Satawal no compass point has moved two degrees from its equatorial seat',
    Math.abs(w.worstDisplacement) < 2.0, `worst ${w.worstDisplacement} deg (${w.worstPoint})`);
  ok('and the worst-behaved point at Satawal is the one nearest the pole, as cot(A) requires',
    w.worstPoint === 'kochab-rise' || w.worstPoint === 'kochab-set', w.worstPoint);
}

// 4.2 Monotone worsening with |latitude|, on the points that survive everywhere.
//
//     The raw "worst point" figure is NOT monotone and must not be asserted to be.
//     Kochab is the worst offender at Satawal and Saipan and has stopped rising by
//     Tahiti, so the worst SURVIVOR falls as latitude rises. That is the instrument
//     failing in a second way, not the first way reversing. Restricted to the points
//     that rise at all seven places, tan(phi) governs and the growth is monotone.
{
  const order = ['equator', 'satawal', 'saipan', 'tahiti', 'honolulu', 'aotearoa'];
  const vals = order.map((k) => Math.abs(page.worstDisplacementCommon[k].worstDisplacement ?? Infinity));
  let monotone = true;
  for (let i = 1; i < vals.length; i++) if (!(vals[i] >= vals[i - 1] - 1e-9)) monotone = false;
  ok('on the points that rise everywhere, worst displacement grows monotonically with |latitude|',
    monotone, order.map((k, i) => `${k}:${vals[i].toFixed(2)}`).join('  '));

  // CONTROL: the unrestricted figure must NOT be monotone, or the distinction the
  // check above draws is imaginary.
  const raw = order.map((k) => Math.abs(page.worstDisplacement[k].worstDisplacement ?? Infinity));
  let rawMonotone = true;
  for (let i = 1; i < raw.length; i++) if (!(raw[i] >= raw[i - 1] - 1e-9)) rawMonotone = false;
  ok('CONTROL: the unrestricted figure is NOT monotone, because points drop out of the sky',
    !rawMonotone, order.map((k, i) => `${k}:${raw[i].toFixed(2)}`).join('  '));
}

// 4.3 Recompute Satawal's whole compass from scratch and compare to page.json.
{
  let worst = 0;
  for (const c of page.compassAt.satawal) {
    if (c.az === null) continue;
    const pt = COMPASS.find((p) => p.key === c.key);
    const expect = pt.fixed !== undefined ? pt.fixed
      : (pt.side === 'rising'
        ? W.risingAzimuth(byId.get(pt.star).dec, islands.byKey.Satawal.lat, 0)
        : W.settingAzimuth(byId.get(pt.star).dec, islands.byKey.Satawal.lat, 0));
    worst = Math.max(worst, Math.abs(c.az - expect));
  }
  ok('every azimuth in page.json recomputes from stars.json + islands.json',
    worst < 1e-4, `worst ${worst.toExponential(2)} deg, against the 5e-5 granularity of page.json's own rounding`);
}

// ===========================================================================
section('5. Etak: the cotangent, and a real passage');
// ===========================================================================

// 5.1 s = -d cot(theta) inverts bearingFromAlongTrack exactly.
{
  let worst = 0;
  for (const d of [10, 75.6, 200]) {
    for (let s = -500; s <= 500; s += 3.7) {
      const th = W.bearingFromAlongTrack(s, d);
      worst = Math.max(worst, Math.abs(W.alongTrackFromBearing(th, d) - s));
    }
  }
  ok('the cotangent law round-trips: bearing -> along-track -> bearing', worst < 1e-9,
    `worst ${worst.toExponential(2)} km`);
}

// 5.2 ds/dtheta = d csc^2(theta), against finite difference, and its minimum is
//     exactly at abeam.
{
  const d = 75.6;
  let worst = 0;
  for (let th = 5; th <= 175; th += 0.9) {
    const eps = 1e-6;
    const num = (W.alongTrackFromBearing(th + eps, d) - W.alongTrackFromBearing(th - eps, d)) / (2 * eps * Math.PI / 180);
    worst = Math.max(worst, Math.abs(num - W.dAlongTrackDBearing(th, d)) / Math.abs(num));
  }
  ok('ds/dtheta = d csc^2(theta), against finite difference', worst < 1e-6,
    `worst relative error ${worst.toExponential(2)}`);
  const atAbeam = W.dAlongTrackDBearing(90, d);
  let minAway = Infinity;
  for (const th of [10, 30, 60, 89, 91, 120, 150, 170]) minAway = Math.min(minAway, W.dAlongTrackDBearing(th, d));
  ok('the segment rate is minimal exactly abeam, where it equals the offset itself',
    near(atAbeam, d, 1e-9) && minAway > atAbeam, `abeam ${atAbeam.toFixed(4)} km/rad, offset ${d}`);
}

// 5.3 The real passage. The quantity the cotangent predicts is the RATE, km of
//     track per degree of bearing, not the raw segment length: raw length also
//     carries the width of whichever house is being crossed, and the houses are
//     uneven. So the rate must bottom out in the segment holding the abeam point,
//     and the raw lengths must NOT, or the two effects were never separated.
{
  const p = page.passages[0];
  const holdsAbeam = (s) => (s.midKm - s.lengthKm / 2) <= p.abeamAtKm && p.abeamAtKm <= (s.midKm + s.lengthKm / 2);
  const abeamSeg = p.segments.find(holdsAbeam);
  ok('the abeam point falls inside one of the etak segments', !!abeamSeg,
    abeamSeg ? `${abeamSeg.from} -> ${abeamSeg.to}` : 'none');
  ok('the fastest bearing rate (fewest km per degree) is the segment holding the abeam point',
    abeamSeg && Math.abs(abeamSeg.kmPerDegree - p.fastestKmPerDegree) < 1e-9,
    `abeam ${abeamSeg && abeamSeg.kmPerDegree} km/deg, minimum ${p.fastestKmPerDegree} km/deg`);

  // The separation is real only if raw length would have given a DIFFERENT answer.
  const shortestRaw = p.segments.reduce((a, b) => (a.lengthKm <= b.lengthKm ? a : b));
  ok('CONTROL: the shortest RAW segment is not the abeam one, so the two effects are genuinely distinct',
    !holdsAbeam(shortestRaw),
    `shortest raw ${shortestRaw.from} -> ${shortestRaw.to} at ${shortestRaw.lengthKm} km, abeam at ${p.abeamAtKm} km`);

  // Cross-check the rate against the closed form d*csc^2 evaluated at that segment's
  // own mid-bearing, converted from km per radian to km per degree.
  {
    const mid = p.segments.find(holdsAbeam);
    const theta = W.bearingFromAlongTrack(mid.midKm - p.abeamAtKm, Math.abs(p.crossTrackKm));
    const predicted = W.dAlongTrackDBearing(theta, Math.abs(p.crossTrackKm)) * Math.PI / 180;
    ok('the measured rate matches d*csc^2(theta) from the closed form',
      Math.abs(predicted - mid.kmPerDegree) / mid.kmPerDegree < 0.05,
      `closed form ${predicted.toFixed(4)} vs measured ${mid.kmPerDegree} km/deg`);
  }
}

// 5.4 THE COUNT IS ROSTER-DEPENDENT AND THE ENDPOINT IS NOT. This is the check that
//     keeps section three of the page honest.
//
//     How many star points a sweep crosses depends on which points are on the ring,
//     and this ring is assembled from the points named in secondary accounts, so it
//     is very likely short of one or two that Gladwin had. So the page must NOT
//     claim to adjudicate the count. What it does claim is about the ARRIVAL
//     BEARING, which is computed from three island positions and one star's
//     declination and touches no other point of the compass at all. These two checks
//     assert exactly that division.
{
  const p = page.passages[0];
  // Deleting any single non-Acrux point from the ring can change the count...
  const counts = new Set();
  for (const drop of COMPASS.filter((c) => c.star !== '* alf Cru')) {
    counts.add(p.boundaries.filter((b) => b.key !== drop.key).length);
  }
  ok('CONTROL: the number of points passed does change if the roster changes, so the page must not adjudicate a count',
    counts.size > 1, `dropping one point at a time gives counts ${[...counts].sort().join(', ')}`);

  // ...but the arrival bearing cannot, because no compass point enters it.
  const from = islands.byKey[p.from], to = islands.byKey[p.to], ref = islands.byKey[p.ref];
  const arrival = W.initialBearing(to.lat, to.lon, ref.lat, ref.lon);
  ok('the arrival bearing depends only on island positions, and recomputes from them alone',
    near(arrival, p.arrivalBearing, 1e-3), `${arrival.toFixed(4)} vs ${p.arrivalBearing}`);

  const crossSet = W.settingAzimuth(byId.get('* alf Cru').dec, from.lat, 0);
  ok('the setting Southern Cross is not reached, on the positions of record',
    arrival > crossSet, `arrival ${arrival.toFixed(2)} deg vs setting Southern Cross ${crossSet.toFixed(2)} deg`);
}

// 5.4b Gladwin's OTHER example, where the reconstruction agrees with him exactly:
//      four points, from the setting Little Bear to the rising Cassiopeia.
{
  const g = page.passages[1];
  const seq = g.boundaries.map((b) => b.key);
  // Gladwin: the reference island moves "from the setting Little Bear to the rising
  // Cassiopeia, so dividing the voyage into four segments". Five named points with
  // four gaps between them, which also fixes his counting convention: a segment is
  // an INTERVAL between crossings, not a crossing.
  ok('Satawal to Lamotrek via West Fayu crosses five star points, leaving Gladwin\'s four segments between them',
    seq.length === 5 && g.segments.length === 4, `${seq.length} points, ${g.segments.length} intervals: ${seq.join(' -> ')}`);
  ok('and the first is the setting Little Bear and the last the rising Cassiopeia, exactly as Gladwin names them',
    seq[0] === 'kochab-set' && seq[seq.length - 1] === 'cassiopeia-rise', seq.join(' -> '));
}

// 5.5 The reference island really is below the horizon on all three passages,
//     which is what makes it a computed position rather than a sighting.
for (const p of page.passages) {
  ok(`${p.from} to ${p.to}: the reference island (${p.ref}) is beyond the sighting range throughout`,
    p.referenceIslandVisible === false,
    `closest approach ${p.minimumRangeToRefKm} km vs sighting range ${page.horizon.sightingRangeKm} km`);
}

// 5.6 The planar cotangent departs from the sphere by a stated, small amount, and
//     the page carries that number rather than pretending the Earth is flat.
for (const c of page.cotangentCheck) {
  ok(`planar-vs-spherical error is stated and under 2 deg (${c.passage})`,
    Math.abs(c.worstPlanarErrorDeg) < 2, `worst ${c.worstPlanarErrorDeg} deg at ${c.atKm} km`);
}

// ===========================================================================
section('6. Positions, and how well we know them');
// ===========================================================================

// 6.1 Every island the page uses came out of the committed gazetteer responses.
{
  const wd = fs.readFileSync(R('data/wikidata-islands.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
  let allMatch = true;
  for (const [k, v] of Object.entries(islands.byKey)) {
    const row = wd.find((r) => r.slug === k);
    if (!row || row.lat !== v.lat || row.lon !== v.lon) allMatch = false;
  }
  ok('every island position matches the committed Wikidata response byte for byte', allMatch);
}

// 6.2 The Satawal disagreement is real, large, and reported.
{
  const d = islands.disagreement.find((x) => x.key === 'Satawal');
  ok('the Satawal gazetteer disagreement is caught and measured',
    d && d.differenceKm > 50, `${d ? d.differenceKm : 'missing'} km between Wikidata and OSM`);
  const others = islands.disagreement.filter((x) => x.key !== 'Satawal').map((x) => x.differenceKm);
  ok('every other island agrees between the two sources to under 2 km',
    Math.max(...others) < 2, `worst of the rest ${Math.max(...others)} km`);
}

// 6.3 Great-circle distance against an independent implementation (the spherical
//     law of cosines, which is a different formula from the haversine used above).
{
  let worst = 0;
  const keys = Object.keys(islands.byKey);
  for (const a of keys) for (const b of keys) {
    if (a === b) continue;
    const A = islands.byKey[a], B = islands.byKey[b];
    const p1 = A.lat * Math.PI / 180, p2 = B.lat * Math.PI / 180, dl = (B.lon - A.lon) * Math.PI / 180;
    const c = Math.acos(Math.min(1, Math.sin(p1) * Math.sin(p2) + Math.cos(p1) * Math.cos(p2) * Math.cos(dl)));
    worst = Math.max(worst, Math.abs(c * W.EARTH_RADIUS_KM - W.greatCircleKm(A.lat, A.lon, B.lat, B.lon)));
  }
  ok('haversine agrees with the spherical law of cosines on every island pair',
    worst < 1e-6, `worst ${worst.toExponential(2)} km`);
}

// 6.4 Cross-track and along-track are consistent: stepping along the track by the
//     along-track distance really does put you at the closest point.
for (const p of page.passages) {
  const from = islands.byKey[p.from], to = islands.byKey[p.to], ref = islands.byKey[p.ref];
  let best = Infinity, bestAt = 0;
  for (let i = 0; i <= 4000; i++) {
    const s = p.totalKm * 1.4 * (i / 4000) - 0.2 * p.totalKm;
    const q = W.destinationPoint(from.lat, from.lon, W.initialBearing(from.lat, from.lon, to.lat, to.lon), s);
    const dist = W.greatCircleKm(q.lat, q.lon, ref.lat, ref.lon);
    if (dist < best) { best = dist; bestAt = s; }
  }
  ok(`${p.from} to ${p.to}: brute-forced closest approach matches the analytic one`,
    near(best, Math.abs(p.crossTrackKm), 0.05) && near(bestAt, p.abeamAtKm, 0.6),
    `brute ${best.toFixed(3)} km at ${bestAt.toFixed(2)} km; analytic ${Math.abs(p.crossTrackKm).toFixed(3)} at ${p.abeamAtKm}`);
}

// ===========================================================================
section('7. The page says only what was computed');
// ===========================================================================
{
  const html = fs.readFileSync(path.join(HERE, 'public/strata/the-island-that-moves/index.html'), 'utf8');
  const need = [
    String(page.passages[0].totalKm.toFixed(0)),
    String(page.compassPointCount),
  ];
  ok('the page carries the computed passage length and compass size',
    need.every((n) => html.includes(n)), need.join(' / '));
  ok('the page carries the SIMBAD acknowledgement required by CDS',
    html.includes('SIMBAD') && html.includes('CDS'));
  ok('the page links its own verifier', html.includes('verify-the-island-that-moves'));
  ok('the page carries the canonical way out', html.includes('aw-wayout'));
}

// ===========================================================================
console.log(`\n${pass}/${pass + fail} checks passed`);
if (fail) { console.log(`${fail} FAILED`); process.exit(1); }
