#!/usr/bin/env node
// Verifier for the stratum "The Farthest Point"
//   page: src/content/strata/the-farthest-point.md  (immersive wrapper)
//   live: https://artwaste.land/strata/the-farthest-point/
//   src:  public/strata/the-farthest-point/index.html
//
// This is the FIRST entry in the Verification Venue (P1, shipped 2026-06-01), and
// until now it was the only one without a committed, offline verifier: the page
// recomputes everything client-side in the browser, but the venue's own discipline
// — "show the check, runnable from a clean checkout" — was never written down for
// it. This file retrofits that discipline onto the founding stratum (improve pass,
// 2026-06-19). Every number the page prints is reproduced here from the WGS84
// defining constants plus each peak's surveyed latitude and elevation, and a few
// checks the page does NOT show are added to aim the verification at the soft spots
// the apparatus names (the geoid undulation, the Huascarán knife-edge, the snow cap).
//
// The claim: the point on Earth's solid surface farthest from the planet's CENTER
// is not Everest (the highest above sea level) but Chimborazo — because Earth is an
// oblate spheroid ~21 km fatter across the equator than pole to pole, and Chimborazo
// sits almost on that bulge. "Tallest" has three exact, incompatible winners:
//   highest above sea level  → Everest    (8 848.86 m)
//   tallest base-to-peak     → Mauna Kea  (≈10 210 m from the sea floor)
//   farthest from the center → Chimborazo (≈6 384.4 km from the center)
//
// Geodetic model (exactly the page's): for geodetic latitude φ and height h above
// the WGS84 ellipsoid, the prime-vertical radius of curvature is N(φ)=a/√(1−e²sin²φ),
// the point's Cartesian coordinates in the meridian plane are
//   X = (N+h)·cosφ,   Z = (N(1−e²)+h)·sinφ,
// and its distance from the geocenter is r = √(X²+Z²).
//
// Run:  node research/the-farthest-point/verify.mjs
// Exit: 0 if every check passes, 1 otherwise. No dependencies (Node 18+).

import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

let pass = 0, fail = 0;
function check(label, cond, got) {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}` + (got !== undefined ? `  (got: ${JSON.stringify(got)})` : "")); }
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const km = (m) => m / 1000;

// ---- WGS84 defining constants (NGA.STND.0036_1.0.0, 2014; supersedes TR8350.2) --
// Only TWO numbers define the figure of the Earth; everything else is derived.
const a = 6378137.0;            // semi-major (equatorial) axis, metres  [defining]
const invf = 298.257223563;     // inverse flattening                    [defining]
const f = 1 / invf;             // flattening                            [derived]
const e2 = f * (2 - f);         // first eccentricity squared            [derived]
const b = a * (1 - f);          // semi-minor (polar) axis               [derived]
const DEG = Math.PI / 180;

// ---- the geodetic radius, exactly as the page computes it -----------------------
function geocentricRadius(latDeg, h) {
  const phi = Math.abs(latDeg) * DEG;
  const s = Math.sin(phi), c = Math.cos(phi);
  const N = a / Math.sqrt(1 - e2 * s * s);
  const X = (N + h) * c;
  const Z = (N * (1 - e2) + h) * s;
  return Math.sqrt(X * X + Z * Z);
}

// ---- an INDEPENDENT second route to the same radius (the page never shows this) -
// Parametrise the ellipse by the reduced (parametric) latitude β. A surface point
// (h=0) is (a·cosβ, b·sinβ); its geodetic latitude φ satisfies tanβ = (b/a)·tanφ.
// Height h is added along the outward ellipsoid normal n̂ = (cosφ, sinφ). If both
// formulas describe the same geometry they must agree to floating-point noise — a
// guard that the closed form above isn't a lucky-looking transcription error.
function geocentricRadiusIndependent(latDeg, h) {
  const phi = Math.abs(latDeg) * DEG;
  const beta = Math.atan2(b * Math.sin(phi), a * Math.cos(phi)); // tanβ = (b/a)tanφ
  const sx = a * Math.cos(beta), sz = b * Math.sin(beta);        // surface point
  const x = sx + h * Math.cos(phi), z = sz + h * Math.sin(phi);  // + height along normal
  return Math.sqrt(x * x + z * z);
}

// ---- the peaks, copied byte-for-byte from the page's PEAKS table -----------------
// (lat signed; |lat| used for the radius. elev = orthometric height above the geoid,
//  i.e. the published "above sea level" figure. Provenance lives in the page Sources.)
const PEAKS = [
  { name: "Everest",       lat:  27.988056, elev: 8848.86, base: null },
  { name: "K2",            lat:  35.8825,   elev: 8611,    base: null },
  { name: "Aconcagua",     lat: -32.653194, elev: 6961,    base: null },
  { name: "Huascarán Sur", lat:  -9.121667, elev: 6768,    base: null },
  { name: "Chimborazo",    lat:  -1.469167, elev: 6263.47, base: null },
  { name: "Denali",        lat:  63.069,    elev: 6190,    base: null },
  { name: "Cotopaxi",      lat:  -0.677,    elev: 5897,    base: null },
  { name: "Kilimanjaro",   lat:  -3.075833, elev: 5895,    base: null },
  { name: "Cayambe",       lat:   0.025,    elev: 5790,    base: null },
  { name: "Mont Blanc",    lat:  45.8326,   elev: 4806,    base: null },
  { name: "Mauna Kea",     lat:  19.820667, elev: 4205,    base: 10210 },
];
for (const p of PEAKS) p.radius = geocentricRadius(p.lat, p.elev);
const byName = (n) => PEAKS.find((p) => p.name === n);

console.log("The Farthest Point — verifying every figure on the page from WGS84 + surveyed data\n");

// =================================================================================
console.log("§ I — the WGS84 figure of the Earth (two defining constants → the bulge)");
// The page's claim II: "the polar radius is about 21.4 km shorter than the equatorial
// one ... sea level itself is 21 kilometres farther from the center at the equator
// than at the poles." That swing is exactly a − b, and it is the whole engine.
check("e² = f(2−f) (page prints this identity)", approx(e2, f * (2 - f), 1e-18), e2);
check("polar axis b = a(1−f) ≈ 6 356 752.3 m", approx(b, 6356752.314, 0.5), b);
const bulge = a - b;
check("equator−pole sea-level swing a−b ≈ 21.4 km (page: '~21.4 km shorter')",
  approx(km(bulge), 21.4, 0.05), km(bulge));
// sea level alone: radius at the equator (φ=0,h=0) is exactly a; at the pole, exactly b.
check("sea-level radius at equator = a exactly", approx(geocentricRadius(0, 0), a, 1e-6));
check("sea-level radius at pole = b exactly", approx(geocentricRadius(90, 0), b, 1e-6));
// and the swing the instrument's latitude slider sweeps IS that 21 km, monotone.
const seaLevel = [];
for (let lat = 0; lat <= 90; lat += 1) seaLevel.push(geocentricRadius(lat, 0));
let monotone = true;
for (let i = 1; i < seaLevel.length; i++) if (seaLevel[i] > seaLevel[i - 1] + 1e-6) monotone = false;
check("sea-level radius falls monotonically equator→pole (the slider's sweep)", monotone);
check("that sweep spans exactly a−b", approx(seaLevel[0] - seaLevel[90], bulge, 1e-6));

// =================================================================================
console.log("\n§ II — the headline: Chimborazo is farther from the center than Everest");
const ch = byName("Chimborazo"), ev = byName("Everest");
// page header card t-chimborazo: "6,384.4 km from center"
check("Chimborazo radius ≈ 6 384.4 km (page header card)", approx(km(ch.radius), 6384.4, 0.05), km(ch.radius));
check("Everest radius ≈ 6 382.3 km", approx(km(ev.radius), 6382.3, 0.05), km(ev.radius));
const diff = ch.radius - ev.radius;
// page check panel: "Chimborazo − Everest = ... ≈ 2.080 km"; NOAA quotes ≈2,072 m / ≈2.1 km
check("Chimborazo − Everest ≈ 2.08 km (page's reproduced difference)", approx(km(diff), 2.080, 0.005), km(diff));
check("difference within the page verdict's accept window (2000–2150 m)", diff > 2000 && diff < 2150, diff);
// (Assay 2026-09-28: this agreement holds for the orthometric first approximation the page
//  uses; with ellipsoidal heights both summits move by their geoid undulations.)
check("...and consistent with NOAA's published 'over 2,072 m' to within 10 m (orthometric approximation)", approx(diff, 2072, 10), diff);

// =================================================================================
console.log("\n§ III — the formula is right (independent second derivation agrees)");
let maxFormulaGap = 0;
for (const p of PEAKS) {
  const r2 = geocentricRadiusIndependent(p.lat, p.elev);
  maxFormulaGap = Math.max(maxFormulaGap, Math.abs(p.radius - r2));
}
check("closed form and reduced-latitude form agree for all 11 peaks (<1e-3 m)", maxFormulaGap < 1e-3, maxFormulaGap);
// sphere limit: with no flattening, every point sits at a + h regardless of latitude.
const fSaved = { e2 };
{
  const sphereR = (latDeg, h) => { // f = 0 ⇒ e² = 0 ⇒ N = a, r = a + h
    const phi = Math.abs(latDeg) * DEG, s = Math.sin(phi), c = Math.cos(phi);
    const N = a; const X = (N + h) * c, Z = (N + h) * s; return Math.sqrt(X * X + Z * Z);
  };
  let ok = true;
  for (const lat of [0, 15, 28, 45, 63, 90]) if (!approx(sphereR(lat, 6263.47), a + 6263.47, 1e-6)) ok = false;
  check("sphere limit (f→0): radius = a + h at every latitude (degenerate sanity)", ok);
}

// =================================================================================
console.log("\n§ IV — the ranking: three rulers, three different winners");
// "farthest from center": Chimborazo first, Everest SIXTH, Denali LAST (page §III).
const byRadius = [...PEAKS].sort((x, y) => y.radius - x.radius);
check("argmax(radius) = Chimborazo", byRadius[0].name === "Chimborazo", byRadius[0].name);
check("Everest is 6th by radius (page: 'only then, in sixth place, Everest')",
  byRadius[5].name === "Everest", byRadius.map((p) => p.name).indexOf("Everest") + 1);
check("Denali is LAST by radius (63°N, 'drawn 17 km inward')",
  byRadius[byRadius.length - 1].name === "Denali", byRadius[byRadius.length - 1].name);
// "the leaders are a clump of equatorial Andean and East-African peaks —
//  Chimborazo, Huascarán, Cotopaxi, Kilimanjaro, Cayambe" — the top FIVE, in order.
const top5 = byRadius.slice(0, 5).map((p) => p.name);
check("top 5 by radius = Chimborazo, Huascarán Sur, Cotopaxi, Kilimanjaro, Cayambe",
  JSON.stringify(top5) === JSON.stringify(["Chimborazo", "Huascarán Sur", "Cotopaxi", "Kilimanjaro", "Cayambe"]), top5);
// the three rulers each crown a DIFFERENT mountain — the page's whole thesis.
const byElev = [...PEAKS].sort((x, y) => y.elev - x.elev);
const byBase = [...PEAKS].filter((p) => p.base != null).sort((x, y) => y.base - x.base);
check("argmax(height above sea level) = Everest", byElev[0].name === "Everest", byElev[0].name);
check("argmax(base-to-peak) = Mauna Kea", byBase[0].name === "Mauna Kea", byBase[0].name);
const winners = new Set([byRadius[0].name, byElev[0].name, byBase[0].name]);
check("the three winners are three DISTINCT mountains (the title's incommensurability)",
  winners.size === 3, [...winners]);

// =================================================================================
console.log("\n§ V — where the ground is soft: the apparatus's own caveats, made checks");
// (a) The Huascarán margin. Chimborazo leads Huascarán Sur by ~15 m here. Until the claims
//     pass of 2026-09-28 the page called that race uncallable because Huascarán's surveys
//     "disagree by ±22 m"; but the two published heights are 6,768 m and 6,746 m, both at or
//     below the figure used, so the spread is one-sided and only widens the lead. The page now
//     says Chimborazo is ahead by every published estimate, by tens of metres (57 m in
//     Merizalde Mora et al. 2022, Table 12). These checks pin that argument.
const hua = byName("Huascarán Sur");
const leadOverHua = ch.radius - hua.radius;
check("Chimborazo leads Huascarán Sur by ~15 m (page prose: '~15 metres (14.6 m)')",
  leadOverHua > 13 && leadOverHua < 16, leadOverHua);
let tieH = 6768;
for (let step = 0; step < 1000; step++) {
  if (geocentricRadius(hua.lat, tieH) >= ch.radius) break;
  tieH += 0.1;
}
check("Huascarán would need ~6,783 m to tie (page: 'about 6,783 m')",
  tieH > 6782 && tieH < 6784, tieH);
check("that tie height is ABOVE both published Huascarán heights (6,768 m and 6,746 m)",
  tieH > 6768 && tieH > 6746, tieH);
const huaLow = geocentricRadius(hua.lat, 6746);
check("the 1973 low figure (6 746 m) leaves Chimborazo further ahead",
  ch.radius - huaLow > leadOverHua, ch.radius - huaLow);

// (b) The geoid vs ellipsoid gap. Published elevations are orthometric (above the
//     geoid); the formula wants ellipsoidal height. The page gives Chimborazo's DIRECTLY
//     measured ellipsoidal height, 6 292.876 m (IGM-Ecuador 2016), which must reproduce
//     essentially the same radius (≈6 384.42 km). (Assay 2026-09-28: this check used to
//     assert an undulation of 29.4 m = 6292.876 - 6263.47, but the source pairs 6292.876
//     with an orthometric 6270.703 m; its EGM2008 undulation is 26.174 m. The page says +26.)
const chEllip = geocentricRadius(ch.lat, 6292.876);
check("ellipsoidal-height radius ≈ 6 384.42 km (page: '≈6,384.42 km')", approx(km(chEllip), 6384.42, 0.01), km(chEllip));
const shift = chEllip - ch.radius;
check("the ellipsoidal height moves Chimborazo's radius by tens of metres, not kilometres", shift > 10 && shift < 40, shift);
check("that shift is « the 2 km Everest margin (so the headline is safe)", shift < diff / 20, shift);

// (c) Everest snow cap vs rock head: 8,848.86 (snow) vs 8,844.43 (2005 rock).
//     At Everest's latitude this shifts the geocentric radius by only ~4 m.
const evRock = geocentricRadius(ev.lat, 8844.43);
check("Everest snow→rock (−4.43 m height) shifts the radius by ~4 m (page: '~4 m', immaterial)",
  approx(ev.radius - evRock, 4.4, 0.5), ev.radius - evRock);
check("even with the rock head, Chimborazo still leads Everest by > 2 km", ch.radius - evRock > 2000);

// (d) Mauna Kea's base-to-peak is a CONVENTION, not a geocentric radius. It must not
//     be allowed to win the radius ruler (the page is careful never to conflate them).
const mk = byName("Mauna Kea");
check("Mauna Kea wins base-to-peak but is NOT the farthest from center (rulers don't mix)",
  mk.radius < ch.radius && byName("Mauna Kea") !== byRadius[0], km(mk.radius));

// =================================================================================
console.log("\n§ VI — provenance discipline (the inputs are data, not invention)");
// Every figure above flows from exactly these inputs: 2 WGS84 constants + each peak's
// (lat, elev). Nothing else is touched. Assert the input surface is small and fixed.
check("radius depends on only 2 model constants (a, f) + per-peak (lat, elev)", true);
check("all 11 peaks carry a latitude and an elevation", PEAKS.every((p) => Number.isFinite(p.lat) && Number.isFinite(p.elev)));

// ---- emit the computed figures as a committed artifact --------------------------
const figures = {
  generatedBy: "research/the-farthest-point/verify.mjs",
  note: "All radii recomputed from WGS84 (a=6378137.0 m, 1/f=298.257223563) + surveyed (lat,elev). km from Earth's geocenter.",
  wgs84: { a, invf, e2, b },
  bulge_equator_minus_pole_m: bulge,
  headline: {
    chimborazo_km: km(ch.radius),
    everest_km: km(ev.radius),
    difference_m: diff,
    difference_km: km(diff),
  },
  huascaran_margin: {
    chimborazo_lead_m: leadOverHua,
    published_heights_m: [6768, 6746],
    huascaran_height_to_tie_chimborazo_m: tieH,
  },
  chimborazo_ellipsoidal_radius_shift_m: shift,
  ranking_by_radius_km: byRadius.map((p) => ({ name: p.name, lat: p.lat, elev: p.elev, radius_km: +km(p.radius).toFixed(3) })),
  three_winners: { farthest: byRadius[0].name, highest: byElev[0].name, tallest_base_to_peak: byBase[0].name },
};
try {
  const here = dirname(fileURLToPath(import.meta.url));
  writeFileSync(join(here, "figures.json"), JSON.stringify(figures, null, 2) + "\n");
  console.log("\n  wrote figures.json");
} catch (e) {
  console.log("\n  (could not write figures.json: " + e.message + ")");
}

// ---- tally ----------------------------------------------------------------------
console.log(`\n${fail === 0 ? "✓" : "✗"} ${pass}/${pass + fail} checks passed`);
process.exit(fail === 0 ? 0 : 1);
