// verify-the-line-drawn-with-a-ruler.mjs
//
// Everything "The Line Drawn With a Ruler" claims, checked from the transcribed award
// outward. In four parts:
//
//   A. the geodesy engine, checked against things that are true independently of it
//      (closed-form spherical formulae, round trips, an ODE integration of the rhumb)
//   B. the award's own numbers, recomputed and compared with what the page publishes
//   C. mutation tests: break each input on purpose and confirm the checks catch it
//   D. the page itself, driven in a real headless browser, so that the figures a reader
//      sees are the figures checked above and not a stale hand-typed copy
//
//   bash research/the-line-drawn-with-a-ruler/build.sh
//   node verify-the-line-drawn-with-a-ruler.mjs
//
// Every path is found from this file's own location, so the check measures the checkout it
// sits in and not whichever machine it was first written on. Parts A to C need nothing but
// Node and the files in research/the-line-drawn-with-a-ruler/ and public/strata/.
//
// Part D serves the page to a real browser. The page is a static file that the site build
// copies from public/ into dist/ unchanged, so Part D serves public/ directly and needs no
// build. It deliberately never serves dist/: whether a dist/ happens to exist, and how old
// it is, is a fact about the machine and not about the page, and it used to decide this
// check's exit code (postbuild strips film.mp4 from dist/, and the 404 read as a console
// error). If Playwright is absent Part D is SKIPPED, and the last line says so.

import { readFileSync, existsSync } from 'node:fs';
import { createServer } from 'node:http';
import { extname, join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as G from './research/the-line-drawn-with-a-ruler/geodesy.mjs';

const ROOT = dirname(fileURLToPath(import.meta.url));
const RES = `${ROOT}/research/the-line-drawn-with-a-ruler`;
const { ellipsoid, dms, toDMS, NM, D2R } = G;

let fails = 0, checks = 0;
const skipped = [];
const ok = (name, cond, extra = '') => {
  checks++; if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (name, got, want, tol, unit = '') =>
  ok(name, Math.abs(got - want) <= tol, `got ${got}${unit}, want ${want}${unit} +/- ${tol}${unit}`);

const AWARD = JSON.parse(readFileSync(`${RES}/award.json`, 'utf8'));
const DATA = JSON.parse(readFileSync(`${RES}/data.json`, 'utf8'));
const S = ellipsoid('sphere'), EI = ellipsoid('international1924'), EW = ellipsoid('wgs84');
const P = (o) => ({ lat: dms(o.lat), lon: dms(o.lon) });
const LE_CROM = P(AWARD.basepoints['Le Crom (Ushant)']);
const WINGLETANG = P(AWARD.basepoints['Wingletang (Scilly Isles)']);
const M = P(AWARD.atlantic.M), N = P(AWARD.atlantic.N);
const RUNNEL = { lat: DATA.runnelstone.lat, lon: DATA.runnelstone.lon };
const AZ_A = dms(AWARD.atlantic.lineA.bearing.replace('"', '"N'));
const AZ_B = dms(AWARD.atlantic.lineB.bearing.replace('"', '"N'));
const AZ_BIS = dms(AWARD.atlantic.bisector.replace('"', '"N'));

console.log('A. THE GEODESY ENGINE, against facts that do not depend on it');

// On a sphere the geodesic distance has a closed form. Vincenty must reproduce it, and the
// agreement is a real check because the two computations share no code path.
{
  const R = ellipsoid('sphere').a;
  const hav = (la1, lo1, la2, lo2) => {
    const dp = (la2 - la1) * D2R, dl = (lo2 - lo1) * D2R;
    const a = Math.sin(dp / 2) ** 2 + Math.cos(la1 * D2R) * Math.cos(la2 * D2R) * Math.sin(dl / 2) ** 2;
    return 2 * R * Math.asin(Math.sqrt(a));
  };
  let worst = 0;
  for (const [a, b] of [[LE_CROM, WINGLETANG], [M, N], [LE_CROM, RUNNEL], [WINGLETANG, N]]) {
    worst = Math.max(worst, Math.abs(G.distance(S, a.lat, a.lon, b.lat, b.lon) - hav(a.lat, a.lon, b.lat, b.lon)));
  }
  ok('Vincenty on a sphere matches the haversine closed form to under 1 mm', worst < 1e-3, `worst ${(worst * 1000).toFixed(4)} mm`);
}

// Spherical trigonometry gives the great-circle azimuth in closed form too.
{
  const az = (la1, lo1, la2, lo2) => {
    const p1 = la1 * D2R, p2 = la2 * D2R, dl = (lo2 - lo1) * D2R;
    return (Math.atan2(Math.sin(dl) * Math.cos(p2),
      Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl)) / D2R + 360) % 360;
  };
  let worst = 0;
  for (const [a, b] of [[LE_CROM, WINGLETANG], [M, N], [LE_CROM, RUNNEL]]) {
    worst = Math.max(worst, Math.abs(G.inverse(S, a.lat, a.lon, b.lat, b.lon).az1 - az(a.lat, a.lon, b.lat, b.lon)));
  }
  ok('spherical azimuth matches the closed form to under 1e-9 deg', worst < 1e-9, `worst ${worst.toExponential(2)} deg`);
}

// Direct and inverse must undo each other on the ellipsoid.
{
  let worstS = 0, worstAz = 0;
  for (const [a, b] of [[LE_CROM, WINGLETANG], [M, N], [LE_CROM, RUNNEL], [WINGLETANG, RUNNEL]]) {
    const inv = G.inverse(EI, a.lat, a.lon, b.lat, b.lon);
    const fwd = G.direct(EI, a.lat, a.lon, inv.az1, inv.s);
    worstS = Math.max(worstS, G.distance(EI, fwd.lat, fwd.lon, b.lat, b.lon));
    worstAz = Math.max(worstAz, Math.abs(fwd.az2 - inv.az2));
  }
  ok('Vincenty direct undoes inverse to under 1 mm', worstS < 1e-3, `worst ${(worstS * 1000).toFixed(4)} mm`);
  ok('and returns the same terminal azimuth', worstAz < 1e-9, `worst ${worstAz.toExponential(2)} deg`);
}

// Mercator forward and inverse must round-trip, including the ellipsoidal correction.
{
  let worst = 0;
  for (let lat = 40; lat <= 60; lat += 0.37) {
    const back = G.latitudeFromIsometric(EI, G.isometricLatitude(EI, lat));
    worst = Math.max(worst, Math.abs(back - lat));
  }
  ok('isometric latitude inverts to under 1e-11 deg', worst < 1e-11, `worst ${worst.toExponential(2)} deg`);
}

// A rhumb line is the solution of dlat/ds = cos(az)/Meridional and dlon/ds =
// sin(az)/(cos(lat) * Transverse). Integrating that ODE independently must land where the
// closed-form isometric-latitude formula says it lands.
{
  const az = AZ_BIS, target = N.lon;
  const stepM = 25;
  let lat = M.lat, lon = M.lon, s = 0;
  const Mrad = (la) => EI.a * (1 - EI.e2) / Math.pow(1 - EI.e2 * Math.sin(la * D2R) ** 2, 1.5);
  const Nrad = (la) => EI.a / Math.sqrt(1 - EI.e2 * Math.sin(la * D2R) ** 2);
  while (lon > target && s < 600 * NM) {
    // midpoint (RK2) step, which makes the truncation error second order in stepM
    const dlat1 = Math.cos(az * D2R) / Mrad(lat) / D2R;
    const dlon1 = Math.sin(az * D2R) / (Nrad(lat) * Math.cos(lat * D2R)) / D2R;
    const latm = lat + dlat1 * stepM / 2, lonm = lon + dlon1 * stepM / 2;
    const dlat2 = Math.cos(az * D2R) / Mrad(latm) / D2R;
    const dlon2 = Math.sin(az * D2R) / (Nrad(latm) * Math.cos(latm * D2R)) / D2R;
    lat += dlat2 * stepM; lon += dlon2 * stepM; s += stepM;
  }
  const closed = G.rhumbToLongitude(EI, M.lat, M.lon, az, lon);
  const gap = G.distance(EI, lat, lon, closed.lat, lon);
  ok('the rhumb formula matches an independent ODE integration to under 2 m', gap < 2, `gap ${gap.toFixed(3)} m over ${(s / NM).toFixed(1)} nm`);
  // and a rhumb really does hold a constant bearing: sample its own azimuth along the way
  let worstAz = 0, prev = null;
  for (let l = M.lon; l > N.lon; l -= 0.2) {
    const p1 = G.rhumbToLongitude(EI, M.lat, M.lon, az, l);
    const p2 = G.rhumbToLongitude(EI, M.lat, M.lon, az, l - 0.02);
    const a = G.inverse(EI, p1.lat, p1.lon, p2.lat, p2.lon).az1;
    if (prev != null) worstAz = Math.max(worstAz, Math.abs(a - prev));
    prev = a;
  }
  ok('a rhumb holds its bearing along its length (spread under 0.01 deg)', worstAz < 0.01, `spread ${worstAz.toExponential(2)} deg`);
  // a geodesic on the same bearing does NOT: that difference is the whole subject
  const g1 = G.direct(EI, M.lat, M.lon, az, 10 * NM), g2 = G.direct(EI, M.lat, M.lon, az, 160 * NM);
  const swing = Math.abs(g1.az2 - g2.az2);
  ok('a geodesic on the same bearing swings by more than 2 deg over the run', swing > 2, `swing ${swing.toFixed(3)} deg`);
}

// Equidistance really is equidistance: sample the solved locus and check both distances.
{
  let worst = 0;
  for (let lon = M.lon; lon > N.lon; lon -= 0.25) {
    const lat = G.trueEquidistantLatitude(S, LE_CROM, WINGLETANG, lon);
    if (lat == null) continue;
    const d1 = G.distance(S, lat, lon, LE_CROM.lat, LE_CROM.lon);
    const d2 = G.distance(S, lat, lon, WINGLETANG.lat, WINGLETANG.lon);
    worst = Math.max(worst, Math.abs(d1 - d2));
  }
  ok('every solved point of line (a) is equidistant to under 1 mm', worst < 1e-3, `worst ${(worst * 1000).toFixed(4)} mm`);
}

console.log('\nB. THE AWARD, RECOMPUTED');

// The award's own arithmetic.
ok("255°27'44\" minus 238°51'30\" is 16°36'14\"", toDMS(AZ_B - AZ_A) === "016°36'14\"", toDMS(AZ_B - AZ_A));
ok('half of that is 8°18\'07"', toDMS((AZ_B - AZ_A) / 2) === "008°18'07\"", toDMS((AZ_B - AZ_A) / 2));
ok("and the sum is the published 247°09'37\"", toDMS(AZ_A + (AZ_B - AZ_A) / 2) === "247°09'37\"", toDMS(AZ_A + (AZ_B - AZ_A) / 2));
ok('the page reports that arithmetic as exact', DATA.arithmetic.exact === true);

// Britain's two figures.
{
  const rhumbAtN = G.rhumbToLongitude(EI, M.lat, M.lon, AZ_BIS, N.lon);
  let lo = 0, hi = 800 * NM;
  for (let i = 0; i < 200; i++) { const mid = (lo + hi) / 2;
    if (G.direct(EI, M.lat, M.lon, AZ_BIS, mid).lon > N.lon) lo = mid; else hi = mid; }
  const geoAtN = G.direct(EI, M.lat, M.lon, AZ_BIS, (lo + hi) / 2);
  const sep = G.distance(EI, rhumbAtN.lat, N.lon, geoAtN.lat, N.lon) / NM;
  ok('the geodesic lies SOUTH of the rhumb, as the 1977 note said', geoAtN.lat < rhumbAtN.lat,
    `${toDMS(geoAtN.lat, { places: 1 })} vs ${toDMS(rhumbAtN.lat, { places: 1 })}`);
  near('separation at the meridian of N reproduces "approximately 4 nm"', sep, 4, 1.2, ' nm');
  near('and matches the figure the page publishes', sep, DATA.loxodromeVsGeodesic['International 1924'].separationAtLonN_nm, 1e-6, ' nm');
  // the 200 nm run
  const s200 = DATA.loxodromeVsGeodesic['International 1924'].runs['200.0 nm run'].separation_nm;
  near('separation at a 200 nm run reproduces "about 6 miles"', s200, 6, 1.0, ' nm');
  ok('the 200 nm figure exceeds the figure at N, as the note said it would', s200 > sep, `${s200.toFixed(2)} > ${sep.toFixed(2)}`);
  // datum independence
  for (const [nm, key] of [['WGS 84', 'WGS 84'], ['sphere', 'sphere']]) {
    near(`the same separation on ${nm} moves the answer by under 0.6 nm`,
      DATA.loxodromeVsGeodesic[key].separationAtLonN_nm, sep, 0.6, ' nm');
  }
  // the award's own N, and its own stated length
  const miss = G.distance(EI, rhumbAtN.lat, N.lon, N.lat, N.lon) / NM;
  ok('the award\'s Point N sits within its own printed rounding of its own rhumb', miss < 0.5, `miss ${miss.toFixed(3)} nm`);
  const len = G.rhumbInverse(EI, M.lat, M.lon, N.lat, N.lon).s / NM;
  near('M to N is the "approximately 170 nautical miles" the award states', len, 170, 1.5, ' nm');
}

// The two published bearings, and the ambiguity underneath them.
{
  const azAatWing = G.trueEquidistanceBearing(S, LE_CROM, WINGLETANG, WINGLETANG.lon);
  const azBatRunnel = G.trueEquidistanceBearing(S, LE_CROM, RUNNEL, RUNNEL.lon);
  near('line (a): the spherical bearing at Wingletang\'s meridian reproduces the award to 30"',
    (azAatWing - AZ_A) * 3600, 0, 30, '"');
  near('line (b): the spherical bearing at Runnelstone\'s meridian reproduces the award to 120"',
    (azBatRunnel - AZ_B) * 3600, 0, 120, '"');
  // and the plane-Mercator reading is far worse for both: this is the discriminating check
  const pmA = G.mercatorPerpendicularBisector(EI, LE_CROM, WINGLETANG).bearing;
  const pmB = G.mercatorPerpendicularBisector(EI, LE_CROM, RUNNEL).bearing;
  ok('the plane-Mercator reading of (a) is more than 10x worse than the spherical one',
    Math.abs(pmA - AZ_A) > 10 * Math.abs(azAatWing - AZ_A),
    `${((pmA - AZ_A) * 60).toFixed(1)}' vs ${((azAatWing - AZ_A) * 60).toFixed(2)}'`);
  ok('the plane-Mercator reading of (b) is more than 4x worse than the spherical one',
    Math.abs(pmB - AZ_B) > 4 * Math.abs(azBatRunnel - AZ_B),
    `${((pmB - AZ_B) * 60).toFixed(1)}' vs ${((azBatRunnel - AZ_B) * 60).toFixed(2)}'`);
  // the bearing of each named line varies along its own length, which is the finding
  for (const [label, other, want] of [['(a)', WINGLETANG, DATA.lineA], ['(b)', RUNNEL, DATA.lineB]]) {
    const azs = [];
    for (let lon = M.lon; lon > N.lon; lon -= 0.02) {
      const b = G.trueEquidistanceBearing(S, LE_CROM, other, lon);
      if (b != null) azs.push(b);
    }
    const spread = Math.max(...azs) - Math.min(...azs);
    ok(`line ${label}'s own bearing varies by more than 2.5 deg along its length`, spread > 2.5, `${toDMS(spread)}`);
    near(`and matches the spread the page publishes for ${label}`, spread, want.rangeOverRun.spreadDeg, 1e-9, ' deg');
    const pub = label === '(a)' ? AZ_A : AZ_B;
    ok(`the page's published figure for ${label} is the award's own`, want.published === toDMS(pub));
    const above = (pub - Math.max(...azs)) * 60, below = (Math.min(...azs) - pub) * 60;
    ok(`the award's figure for ${label} lies within 3' of the range the line takes over M to N`,
      above < 3 && below < 3, `${above > 0 ? above.toFixed(2) + "' above the range" : below > 0 ? below.toFixed(2) + "' below" : 'inside'}`);
    if (label === '(a)') ok("line (a)'s figure lies strictly inside its range", above < 0 && below < 0);
    if (label === '(b)') ok("line (b)'s figure lies just above its range, because Runnelstone's meridian is east of M",
      above > 0 && above < 3, `${above.toFixed(2)}' above; Runnelstone is ${(G.distance(EI, M.lat, M.lon, M.lat, RUNNEL.lon) / NM).toFixed(2)} nm east of M in longitude`);
  }
  // what the ambiguity is worth on the ground
  // Measured between real rhumbs at the meridian of N, over every candidate reference
  // meridian. An earlier version of this check used sin(spread/2), which is the HALF width;
  // the browser pass caught it by measuring 8.97 nm where the page published 4.3.
  const fan = DATA.ambiguity.fanWidthAtN_nm;
  const worst = DATA.ambiguity.worstAgainstAwardAtN_nm;
  ok('the fan is measured over many reference meridians, not estimated',
    DATA.ambiguity.referenceMeridiansTried > 150, `${DATA.ambiguity.referenceMeridiansTried} meridians`);
  near('the fan at Point N is about 9.7 nm end to end', fan, 9.7, 0.5, ' nm');
  near('and the worst single choice lands about 8.9 nm from the award\'s line', worst, 8.9, 0.5, ' nm');
  ok('the fan is wider than the four miles Britain litigated', fan > 4, `${fan.toFixed(2)} nm`);
  ok('and so is the worst single choice, which is the fair comparison', worst > 4, `${worst.toFixed(2)} nm`);
  // Consistency, with the geometry stated rather than fudged: the fan is measured ALONG the
  // meridian of N, while run x sin(angle) is the separation PERPENDICULAR to the track. The
  // track runs about 23 degrees south of west, so the meridian-wise figure is the larger by
  // roughly 1/cos of that inclination, and the two must reconcile through it.
  const perp = DATA.ambiguity.runMtoN_nm * Math.sin(DATA.ambiguity.bisectorSpreadDeg * D2R);
  ok('the meridian-wise fan exceeds the perpendicular separation, as the geometry requires',
    fan > perp, `${fan.toFixed(2)} > ${perp.toFixed(2)} nm`);
  const incl = Math.abs(270 - AZ_BIS); // degrees the track lies off due west
  near('and the two reconcile through the track inclination to within 5%',
    fan * Math.cos(incl * D2R) / perp, 1, 0.05, ' (ratio)');
}

// The four lines the award's words admit.
{
  const lats = Object.values(DATA.fourLines.atN).map((v) => v.latDeg).filter((v) => v != null);
  ok('the award\'s words admit four distinct lines', lats.length === 4, `${lats.length}`);
  const spread = G.distance(EI, Math.max(...lats), N.lon, Math.min(...lats), N.lon) / NM;
  near('and they are spread across about 6 nm at the meridian of N', spread, 6, 1, ' nm');
  near('matching the figure the page publishes', spread, DATA.fourLines.spreadAtN_nm, 1e-6, ' nm');
  ok('the spread exceeds the four miles Britain litigated', spread > 4, `${spread.toFixed(2)} nm`);
  // the angle bisector is not the area bisector, under either cut
  ok('the area bisector differs from the award\'s angle bisector, meridian cut',
    Math.abs(DATA.areaBisector.meridianMinusAward_arcmin) > 30, `${DATA.areaBisector.meridianMinusAward_arcmin.toFixed(1)}'`);
  ok('and under an arc cut as well', Math.abs(DATA.areaBisector.arcMinusAward_arcmin) > 30,
    `${DATA.areaBisector.arcMinusAward_arcmin.toFixed(1)}'`);
  // the two lines do not cross at M
  const X = G.tripoint(S, LE_CROM, WINGLETANG, RUNNEL, { lat: 49.2, lon: -5.7 });
  const d = [LE_CROM, WINGLETANG, RUNNEL].map((p) => G.distance(S, X.lat, X.lon, p.lat, p.lon));
  ok('the crossing of (a) and (b) is equidistant from all three rocks to under 1 mm',
    Math.max(...d) - Math.min(...d) < 1e-3, `${((Math.max(...d) - Math.min(...d)) * 1000).toFixed(3)} mm`);
  const dM = G.distance(EI, X.lat, X.lon, M.lat, M.lon) / NM;
  near('and it lies about 2.4 nm from Point M, where the award bisects', dM, 2.4, 0.3, ' nm');
  near('matching the page', dM, DATA.crossing.distanceFromM_nm, 1e-6, ' nm');
  // the area, and which mile the award meant
  ok('the area in square nautical miles is within 10% of the award\'s "approximately 4,000"',
    Math.abs(DATA.fourLines.totalArea_sqNm - 4000) / 4000 < 0.10, `${Math.round(DATA.fourLines.totalArea_sqNm)} sq nm`);
  ok('and in square statute miles it is not, which identifies the unit',
    Math.abs(DATA.fourLines.totalArea_sqStatuteMiles - 4000) / 4000 > 0.30, `${Math.round(DATA.fourLines.totalArea_sqStatuteMiles)} sq statute miles`);
}

// The audit of the seventeen turning points.
{
  const rows = DATA.audit.rows;
  ok('all seventeen published turning points are audited', rows.length === 17, `${rows.length}`);
  ok('every basepoint a turning point names is one the award locates',
    AWARD.turningPoints.every((t) => t.from.every((n) => AWARD.basepoints[n])));
  const key = 'great circle (sphere)';
  const constructed = rows.filter((r) => r.id !== 'J');
  const lo = constructed.filter((r) => !DATA.split.simplified.includes(r.id)).map((r) => r.residuals[key]);
  const hi = constructed.filter((r) => DATA.split.simplified.includes(r.id)).map((r) => r.residuals[key]);
  ok('ten points are computed and six are simplified', lo.length === 10 && hi.length === 6, `${lo.length} / ${hi.length}`);
  ok('the two populations do not overlap', Math.max(...lo) < Math.min(...hi),
    `max computed ${Math.max(...lo).toFixed(3)} < min simplified ${Math.min(...hi).toFixed(3)}`);
  ok('the worst simplified point is off by more than a nautical mile', Math.max(...hi) > 1, `${Math.max(...hi).toFixed(2)} nm`);
  // the metric identification, done with no point set aside
  const id = DATA.identification.medianSpreadAll16;
  ok('with no selection at all, the sphere fits better than the plane of the chart',
    id['great circle (sphere)'] < id['Mercator plane'],
    `${id['great circle (sphere)'].toFixed(4)} vs ${id['Mercator plane'].toFixed(4)} nm`);
  ok('and it fits better by at least a factor of five', id['Mercator plane'] / id['great circle (sphere)'] > 5,
    `${(id['Mercator plane'] / id['great circle (sphere)']).toFixed(1)}x`);
  ok('the sphere also beats the International 1924 ellipsoid, so the fit is spherical, not merely curved',
    id['great circle (sphere)'] < id['geodesic Intl 1924'],
    `${id['great circle (sphere)'].toFixed(4)} vs ${id['geodesic Intl 1924'].toFixed(4)} nm`);
  ok('the ten computed points beat the arcsecond rounding floor on the median',
    DATA.split.medianSpreadByMetric[key] < 0.02, `${DATA.split.medianSpreadByMetric[key].toFixed(4)} nm`);
  // spot-check two rows against a from-scratch recomputation
  for (const id2 of ['E', 'D3']) {
    const T = AWARD.turningPoints.find((t) => t.id === id2);
    const p = P(T), rocks = T.from.map((n) => P(AWARD.basepoints[n]));
    const ds = rocks.map((q) => G.distance(S, p.lat, p.lon, q.lat, q.lon));
    const spread = (Math.max(...ds) - Math.min(...ds)) / NM;
    ok(`point ${id2}: recomputed spread ${spread.toFixed(3)} nm ${id2 === 'E' ? 'is tiny' : 'is over a nautical mile'}`,
      id2 === 'E' ? spread < 0.02 : spread > 1);
  }
}

// What the primary source does not say.
{
  ok('the award names Runnelstone as a defining basepoint',
    AWARD.atlantic.lineB.from.some((n) => /Runnelstone/.test(n)));
  ok('and never locates it: it is absent from the basepoint table',
    !Object.keys(AWARD.basepoints).some((n) => /Runnelstone/.test(n)));
  ok('the Runnelstone position used is labelled as an outside input',
    /OpenStreetMap/.test(DATA.runnelstone.source) && /Wikidata/.test(DATA.runnelstone.source));
  const d = DATA.sourceProblems.laHagueTwoLongitudes;
  near('La Hague is printed with two longitudes ten arcseconds apart', Math.abs(d.apartArcsec), 10, 1e-6, '"');
  ok('and point D is nearly equidistant under one reading only',
    d.pointDresidual_nm['with 01°56\'17"W'] < d.pointDresidual_nm['with 01°56\'27"W'],
    `17": ${d.pointDresidual_nm['with 01°56\'17"W'].toFixed(3)} nm, 27": ${d.pointDresidual_nm['with 01°56\'27"W'].toFixed(3)} nm`);
  ok('the datum is recorded as unstated in the award',
    /states no geodetic datum/i.test(DATA.sourceProblems.datumUnstated) && /France conceded/i.test(DATA.sourceProblems.datumUnstated));
}

// Quotations must be present verbatim in the transcription, and used on the page.
{
  const page = readFileSync(`${ROOT}/public/strata/the-line-drawn-with-a-ruler/index.html`, 'utf8');
  const md = readFileSync(`${ROOT}/src/content/strata/the-line-drawn-with-a-ruler.md`, 'utf8');
  ok('the 1978 headnote is transcribed', /neither fatally outmoded nor open to challenge/.test(AWARD.courtsAnswer1978.headnote));
  ok('and quoted in the stratum entry', /neither fatally outmoded nor open to challenge/.test(md));
  ok('paragraph 251 is transcribed with the mid-way wording',
    /line drawn mid-way between those two equidistance lines/.test(AWARD.definitionsOfTheBoundary[0].words));
  ok('paragraph 254 is transcribed with the area wording',
    /bisects the area formed by/.test(AWARD.definitionsOfTheBoundary[1].words));
  ok('the Technical Report\'s own admission of simplification is transcribed',
    /adjusted in certain respects, relatively unimportant/.test(AWARD.courtsAnswer1978.technicalReportPara3));
  ok('and quoted on the page', /adjusted in certain respects, relatively unimportant/.test(page));
  ok('paragraph 103\'s "on Mercator projection" is transcribed', /on Mercator projection/.test(AWARD.courtsAnswer1978.para103));
  ok('Britain\'s four-mile claim is transcribed verbatim',
    /approximately 4 nautical miles to the south/.test(AWARD.unitedKingdomClaims1977.atPointN));
  ok('Britain\'s six-mile claim is transcribed verbatim',
    /about 6 miles at the 200-mile limit/.test(AWARD.unitedKingdomClaims1977.at200Miles));
  ok('the source is cited with its UN URL', /legal\.un\.org\/riaa\/cases\/vol_XVIII/.test(page) && /legal\.un\.org/.test(AWARD.source.url));
  // the page must not hard-code the headline figures: they have to come from data.json
  ok('the page does not hard-code the 4.85 nm figure in its markup', !/4\.8[0-9]\s*nm/.test(page));
  ok('the page does not hard-code the 6 nm figure in its markup', !/6\.0[0-9]\s*nm/.test(page));
  // page and verifier must share one engine, byte for byte
  const a = readFileSync(`${RES}/geodesy.mjs`), b = readFileSync(`${ROOT}/public/strata/the-line-drawn-with-a-ruler/geodesy.js`);
  ok('the page\'s geodesy is byte-identical to the verifier\'s', a.equals(b), `${a.length} vs ${b.length} bytes`);
  const dj = readFileSync(`${RES}/data.json`), dp = readFileSync(`${ROOT}/public/strata/the-line-drawn-with-a-ruler/data.json`);
  ok('the page\'s data is byte-identical to the built data', dj.equals(dp));
  ok('the coastline is labelled as orientation only, not a source of any figure',
    /orientation only/.test(readFileSync(`${RES}/coast.json`, 'utf8')) && /orientation only/.test(page));
  ok('the stratum entry declares the immersive href', /href: "\/strata\/the-line-drawn-with-a-ruler\/"/.test(md));
  ok('and sits in the groundtruth seam', /seam: "groundtruth"/.test(md));
}

console.log('\nC. MUTATION TESTS: break it on purpose, and confirm the checks bite');
{
  const mut = (name, fn) => {
    let caught = false;
    try { caught = fn(); } catch { caught = true; }
    ok(`mutation caught: ${name}`, caught);
  };
  // move Wingletang by one arcminute and the reproduction of (a) must fail
  mut('Wingletang displaced by 1 arcminute breaks the line (a) reproduction', () => {
    const bad = { lat: WINGLETANG.lat + 1 / 60, lon: WINGLETANG.lon };
    const az = G.trueEquidistanceBearing(S, LE_CROM, bad, bad.lon);
    return Math.abs((az - AZ_A) * 3600) > 30;
  });
  // Note the bisector is the MEAN of the two bearings, so swapping them cannot change it;
  // the mutation that bites is perturbing one of them.
  ok('swapping the two bearings leaves the bisector unchanged, as a mean must',
    toDMS(AZ_B + (AZ_A - AZ_B) / 2) === "247°09'37\"");
  mut("moving line (a)'s bearing by 1 arcminute moves the bisector by 30 arcseconds", () => {
    const bad = AZ_A + 1 / 60;
    return Math.abs((bad + (AZ_B - bad) / 2 - AZ_BIS) * 3600 - 30) < 0.001;
  });
  // use a rhumb where a geodesic belongs and the separation collapses to zero
  mut('comparing a rhumb with itself yields no separation, so the 4 nm needs the geodesic', () => {
    const r = G.rhumbToLongitude(EI, M.lat, M.lon, AZ_BIS, N.lon);
    return G.distance(EI, r.lat, N.lon, r.lat, N.lon) / NM < 0.001;
  });
  // if the equidistance solver were returning the midpoint instead of the locus, distances differ
  mut('a midpoint is not an equidistant point, so the solver is doing real work', () => {
    const midLat = (LE_CROM.lat + WINGLETANG.lat) / 2, midLon = (LE_CROM.lon + WINGLETANG.lon) / 2;
    const d1 = G.distance(S, midLat, midLon, LE_CROM.lat, LE_CROM.lon);
    const d2 = G.distance(S, midLat, midLon, WINGLETANG.lat, WINGLETANG.lon);
    const solved = G.trueEquidistantLatitude(S, LE_CROM, WINGLETANG, midLon);
    return Math.abs(d1 - d2) > 1 && Math.abs(solved - midLat) > 1e-4;
  });
  // a wrong Runnelstone must be detectable: shift it 5 nm and (b) stops reproducing
  mut('Runnelstone displaced by 5 nm breaks the line (b) reproduction', () => {
    const bad = G.direct(EI, RUNNEL.lat, RUNNEL.lon, 90, 5 * NM);
    const az = G.trueEquidistanceBearing(S, LE_CROM, bad, bad.lon);
    return Math.abs((az - AZ_B) * 3600) > 120;
  });
  // the dms parser must reject a malformed coordinate rather than silently returning NaN
  mut('the DMS parser throws on a malformed coordinate instead of returning NaN', () => {
    try { dms("48°29'14\"Q"); return false; } catch { return true; }
  });
  // toDMS must carry seconds properly: 59.6" must round up into the next minute
  ok('toDMS carries 59.6" into the next minute', toDMS(10 + 30 / 60 + 59.6 / 3600) === "010°31'00\"",
    toDMS(10 + 30 / 60 + 59.6 / 3600));
  // and the audit must not be able to "pass" by returning null everywhere
  ok('no audited point silently failed to solve',
    DATA.audit.rows.every((r) => Object.values(r.residuals).every((v) => v != null && isFinite(v))));
}

console.log('\nD. THE PAGE, IN A REAL BROWSER');
const LAYER = 'strata/the-line-drawn-with-a-ruler';
const PAGE_FILES = ['index.html', 'geodesy.js', 'data.json'];
const SITE = `${ROOT}/public`;
console.log(`  serving public/ from ${ROOT} (the page's own source, not a build)`);
if (existsSync(`${ROOT}/dist/${LAYER}/index.html`)) {
  // Said, not asserted: a stale build is worth knowing about but is not this page's fault.
  const stale = PAGE_FILES.filter((f) => !existsSync(`${ROOT}/dist/${LAYER}/${f}`) ||
    !readFileSync(`${ROOT}/dist/${LAYER}/${f}`).equals(readFileSync(`${SITE}/${LAYER}/${f}`)));
  console.log(stale.length ? `  note  a dist/ exists here and is STALE for this page (${stale.join(', ')} differ); it was not used`
    : '  note  a dist/ exists here and matches public/ for this page; it was not used');
}
let pw = null;
for (const p of ['/opt/node22/lib/node_modules/playwright/index.js', 'playwright']) {
  try { pw = (await import(p)).default ?? await import(p); break; } catch { /* try the next */ }
}
if (!existsSync(`${SITE}/${LAYER}/index.html`)) {
  ok(`the page exists at public/${LAYER}/index.html`, false);
} else if (!pw) {
  skipped.push('D: Playwright is not importable here, so the page was not driven in a browser');
  console.log('  SKIP  Playwright is not importable here.');
} else {
  const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json',
    '.woff2': 'font/woff2', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' };
  const server = createServer((req, res) => {
    let p = decodeURIComponent(req.url.split('?')[0]);
    if (p.endsWith('/')) p += 'index.html';
    try {
      const buf = readFileSync(join(`${SITE}/`, p));
      res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' });
      res.end(buf);
    } catch { res.writeHead(404); res.end('404'); }
  });
  await new Promise((r) => server.listen(8231, r));
  const browser = await (pw.chromium ?? pw).launch();
  for (const [label, w, h] of [['phone', 390, 844], ['tablet', 768, 1024], ['desktop', 1440, 900]]) {
    const ctx = await browser.newContext({ viewport: { width: w, height: h } });
    const page = await ctx.newPage();
    const errs = [];
    page.on('pageerror', (e) => errs.push(String(e)));
    page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
    await page.goto('http://localhost:8231/strata/the-line-drawn-with-a-ruler/', { waitUntil: 'load' });
    await page.waitForFunction(() => {
      const el = document.getElementById('live');
      return el && !/loading/.test(el.textContent) && el.textContent.trim().length > 40;
    }, { timeout: 15000 });
    ok(`[${label}] no JavaScript errors`, errs.length === 0, errs.slice(0, 2).join(' | '));

    // the instrument drew real geometry, not an empty frame
    const paths = await page.$$eval('#chart path', (e) => e.length);
    ok(`[${label}] the chart drew paths`, paths >= 6, `${paths} paths`);
    const strip = await page.$$eval('#strip circle', (e) => e.length);
    ok(`[${label}] the strip plot drew all sixteen constructed points`, strip === 16, `${strip}`);

    // the rendered figures must match the computed ones
    const uk = await page.$eval('#uk', (e) => e.textContent);
    const sep = DATA.loxodromeVsGeodesic['International 1924'].separationAtLonN_nm.toFixed(2);
    ok(`[${label}] the rendered separation is the computed ${sep} nm`, uk.includes(sep), uk.slice(0, 0));
    ok(`[${label}] and says the geodesic is to the south`, /geodesic to the south/.test(uk));
    const arith = await page.$eval('#arith', (e) => e.textContent);
    ok(`[${label}] the rendered arithmetic shows 247°09'37"`, arith.includes("247°09'37\""));
    const four = await page.$eval('#tbl-four', (e) => e.textContent);
    ok(`[${label}] the four-lines table renders its spread`, four.includes(DATA.fourLines.spreadAtN_nm.toFixed(2)));
    const auditRows = await page.$$eval('#tbl-audit tr', (e) => e.length);
    ok(`[${label}] the audit table renders every point`, auditRows >= 18, `${auditRows} rows`);
    const def = await page.$eval('#tbl-def', (e) => e.textContent);
    ok(`[${label}] the definition table says Runnelstone is never stated`, /never stated in the award/.test(def));

    // the slider must actually change the answer: that is the whole showing
    const readAt = async (v) => {
      await page.$eval('#ref', (el, val) => {
        el.value = String(val); el.dispatchEvent(new Event('input', { bubbles: true }));
      }, v);
      await page.waitForTimeout(60);
      return page.$eval('#live', (e) => e.textContent);
    };
    const t0 = await readAt(0), t1 = await readAt(1000);
    ok(`[${label}] moving the reference point changes the readout`, t0 !== t1);
    const off = (t) => { const m = /([\d.]+) nm (north|south)/.exec(t); return m ? Number(m[1]) : (/0\.00 nm/.test(t) ? 0 : null); };
    const o1 = off(t1);
    ok(`[${label}] and at the far end the boundary has moved several nm`, o1 != null && o1 > 1.5, `offset ${o1} nm`);

    // The projection toggle must not merely redraw: the measured straightness of the two
    // lines has to TRADE PLACES, which is the page's second claim and the one the eye cannot
    // check on its own.
    const sag = async () => {
      const t = await page.$eval('#straightness', (e) => e.textContent);
      const nums = [...t.matchAll(/([\d.]+) nm/g)].map((m) => Number(m[1]));
      return { award: nums[0], greatCircle: nums[1], ellipsoid: nums[2], text: t };
    };
    await page.waitForFunction(() => {
      const e = document.getElementById('straightness');
      return e && !/loading/.test(e.textContent);
    }, { timeout: 10000 });
    const merc = await sag();
    ok(`[${label}] on Mercator the award's rhumb measures straight`, merc.award < 0.05, `${merc.award} nm`);
    // The sagitta from a curve's OWN chord is about a quarter of the divergence between two
    // lines leaving M on the same bearing, because the deviation grows roughly quadratically.
    // 4.85 / 4 = 1.21, and 1.09 is measured: two different quantities, both true.
    ok(`[${label}] and the great circle sags about a quarter of the 4.85 nm divergence`,
      merc.greatCircle > 0.8 && merc.greatCircle < 1.6, `${merc.greatCircle} nm`);
    ok(`[${label}] Mercator names the award's boundary as the straight one`, /straight one is[^]*?award/.test(merc.text.replace(/\s+/g, ' ')));

    const before = await page.$eval('#chart', (e) => e.innerHTML.length);
    await page.click('[data-proj="gnomonic"]');
    await page.waitForTimeout(120);
    const after = await page.$eval('#chart', (e) => e.innerHTML.length);
    ok(`[${label}] switching projection redraws the chart`, after !== before, `${before} -> ${after} chars`);
    const gno = await sag();
    ok(`[${label}] on the gnomonic chart the great circle measures straight`, gno.greatCircle < 0.05, `${gno.greatCircle} nm`);
    ok(`[${label}] and the award's rhumb now sags by the same amount instead`,
      gno.award > 0.8 && gno.award < 1.6, `${gno.award} nm`);
    ok(`[${label}] the two measurements traded places`,
      merc.award < merc.greatCircle && gno.award > gno.greatCircle,
      `mercator ${merc.award}/${merc.greatCircle}, gnomonic ${gno.award}/${gno.greatCircle}`);
    ok(`[${label}] the ellipsoidal geodesic measures straight on the gnomonic chart too, so the sphere/ellipsoid choice does not carry this showing`,
      gno.ellipsoid < 0.05, `${gno.ellipsoid} nm`);
    const pressed = await page.$eval('[data-proj="gnomonic"]', (e) => e.getAttribute('aria-pressed'));
    ok(`[${label}] and the toggle reports its state for assistive tech`, pressed === 'true');
    await page.click('[data-proj="mercator"]');

    const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    ok(`[${label}] no horizontal overflow`, overflow <= 1, `overflow ${overflow}px`);
    await ctx.close();
  }
  await browser.close();
  server.close();
}

console.log(`\n${checks} checks, ${fails} failed` + (skipped.length ? `, ${skipped.length} part SKIPPED (not run, not passed)` : ''));
for (const k of skipped) console.log(`  SKIPPED  ${k}`);
if (!fails) console.log(skipped.length ? 'GREEN FOR WHAT RAN; the skipped part above was not checked' : 'ALL GREEN');
process.exit(fails ? 1 : 0);
