#!/usr/bin/env node
// Offline gate for /strata/is-everest-the-tallest-mountain/.
// Recomputes EVERY number the page shows, two independent ways where possible,
// and exits 0 only if all checks pass. No stored answers: the base-to-peak sums
// and the WGS84 ellipsoid radii are recomputed from first principles here, and
// must match what the page's inline script computes from the same inputs.
//
// Sources (see README.md):
//   Everest 8,848.86 m  — joint China-Nepal survey, announced 2020-12-08.
//   Mauna Kea 4,205 m asl + ~6,000 m submarine base -> ~10,205 m base-to-peak — USGS.
//   Chimborazo 6,263 m at 1.47 S, farthest from Earth's centre — NOAA (~2,072 m > Everest).
//   WGS84: a = 6,378,137 m, 1/f = 298.257223563  ->  b = a(1 - f).

let failures = 0;
const results = [];
function check(name, pass, detail) {
  results.push({ name, pass, detail });
  if (!pass) failures++;
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// ── WGS84 ellipsoid ──────────────────────────────────────────────────────
const A = 6378137.0;                 // equatorial radius, m (defining)
const INV_F = 298.257223563;         // inverse flattening (defining)
const F = 1 / INV_F;
const B = A * (1 - F);               // polar radius, m -> 6,356,752.3142...

// The page hard-codes b = 6,356,752.3142; confirm that rounds from the WGS84 f.
check('WGS84 polar radius b derives from a and 1/f (page uses 6,356,752.3142)',
      approx(B, 6356752.3142, 5e-4), `b = a(1-1/${INV_F}) = ${B.toFixed(4)} m`);

// Method 1: the closed form the page uses.
function radiusClosed(latDeg) {
  const p = latDeg * Math.PI / 180, c = Math.cos(p), s = Math.sin(p);
  return Math.sqrt(((A * A * c) ** 2 + (B * B * s) ** 2) /
                   ((A * c) ** 2 + (B * s) ** 2));
}
// Method 2 (independent): parametric point on the ellipse via reduced latitude.
// A point at geodetic latitude phi lies at radius sqrt(X^2 + Z^2) where
// X = N*cos(phi), Z = N*(1-e^2)*sin(phi), N = A / sqrt(1 - e^2 sin^2 phi).
function radiusGeodetic(latDeg) {
  const p = latDeg * Math.PI / 180, c = Math.cos(p), s = Math.sin(p);
  const e2 = 1 - (B * B) / (A * A);
  const N = A / Math.sqrt(1 - e2 * s * s);
  const X = N * c;
  const Z = N * (1 - e2) * s;
  return Math.sqrt(X * X + Z * Z);
}
// The two radius methods must agree to sub-millimetre across latitudes.
let maxDiff = 0;
for (let lat = 0; lat <= 90; lat += 3) {
  maxDiff = Math.max(maxDiff, Math.abs(radiusClosed(lat) - radiusGeodetic(lat)));
}
check('two independent ellipsoid-radius methods agree (< 1 mm across 0..90 deg)',
      maxDiff < 1e-3, `max disagreement = ${(maxDiff * 1000).toFixed(4)} mm`);

// ── the six mountains (page inputs) ───────────────────────────────────────
const M = {
  everest:    { name: 'Everest',    asl: 8848.86, lat: 27.9881, oceanDepth: 0 },
  maunakea:   { name: 'Mauna Kea',  asl: 4205,    lat: 19.8207, oceanDepth: 6000 },
  chimborazo: { name: 'Chimborazo', asl: 6263,    lat: -1.4693, oceanDepth: 0 },
  denali:     { name: 'Denali',     asl: 6190,    lat: 63.0692, oceanDepth: 0 },
  maunaloa:   { name: 'Mauna Loa',  asl: 4169,    lat: 19.4721, oceanDepth: 5000 },
  aconcagua:  { name: 'Aconcagua',  asl: 6960.8,  lat: -32.6533, oceanDepth: 0 },
};
const keys = Object.keys(M);
const asl    = (m) => M[m].asl;
const base   = (m) => M[m].asl + M[m].oceanDepth;
const centre = (m) => radiusClosed(M[m].lat) + M[m].asl;
function winner(fn) {
  return keys.reduce((best, k) => (fn(k) > fn(best) ? k : best), keys[0]);
}

// ── RULER 1: above sea level -> Everest ───────────────────────────────────
check('RULER 1 (above sea level) winner is Everest', winner(asl) === 'everest',
      `Everest ${asl('everest')} m is highest asl`);

// ── RULER 2: base to peak (sea-floor base) -> Mauna Kea ───────────────────
check('RULER 2 (base to peak) winner is Mauna Kea', winner(base) === 'maunakea',
      `Mauna Kea = ${asl('maunakea')} + ${M.maunakea.oceanDepth} = ${base('maunakea')} m`);
const keaBTP = base('maunakea');
check('Mauna Kea base-to-peak = 10,205 m (4,205 + 6,000)', keaBTP === 10205,
      `${keaBTP} m`);
const overEverest = keaBTP - asl('everest');
check('Mauna Kea out-tops Everest by ~1,356 m (1,300..1,400)',
      overEverest > 1300 && overEverest < 1400, `+${overEverest.toFixed(2)} m`);
// alternate base depth 6,006 m reproduces the widely-quoted ~10,211 m
check('base depth 6,006 m reproduces the USGS-quoted ~10,211 m', 4205 + 6006 === 10211,
      `${4205 + 6006} m`);

// ── RULER 3: farthest from Earth's centre -> Chimborazo ───────────────────
check('RULER 3 (from Earth\'s centre) winner is Chimborazo', winner(centre) === 'chimborazo',
      `Chimborazo ${(centre('chimborazo') / 1000).toFixed(2)} km from centre`);

const chR = centre('chimborazo');
const evR = centre('everest');
const gap = chR - evR;
// The page displays ~6,384.4 km and ~6,382.3 km; confirm those.
check('Chimborazo summit ~6,384.4 km from centre', approx(chR / 1000, 6384.4, 0.1),
      `${(chR / 1000).toFixed(3)} km`);
check('Everest summit ~6,382.3 km from centre', approx(evR / 1000, 6382.3, 0.1),
      `${(evR / 1000).toFixed(3)} km`);
// Reproduces NOAA's published ~2,072 m within input precision (< 15 m).
check('Chimborazo - Everest centre gap reproduces NOAA ~2,072 m (within 15 m)',
      approx(gap, 2072, 15), `computed = ${gap.toFixed(1)} m vs NOAA 2,072 m`);
// It is the bulge, not the mountain: at the equator Everest overtakes Chimborazo.
const evEq = radiusClosed(0) + asl('everest');
check('move Everest to the equator and it beats Chimborazo (the bulge, not the mountain)',
      evEq > chR, `Everest@equator ${(evEq / 1000).toFixed(2)} km > Chimborazo ${(chR / 1000).toFixed(2)} km`);
// Crossover latitude the page reports: bisect for R(phi) = chR - Everest.asl.
const target = chR - asl('everest');
let lo = 0, hi = 90;
for (let i = 0; i < 80; i++) {
  const mid = (lo + hi) / 2;
  if (radiusClosed(mid) > target) lo = mid; else hi = mid;
}
const cross = (lo + hi) / 2;
check('Everest overtakes Chimborazo below a crossover latitude in (0, 28) deg',
      cross > 0 && cross < 28, `crossover lat = ${cross.toFixed(2)} deg`);

// ── the headline claim: Everest wins exactly one of the three rulers ──────
const w1 = winner(asl), w2 = winner(base), w3 = winner(centre);
const everestWins = [w1, w2, w3].filter((w) => w === 'everest').length;
check('Everest wins exactly 1 of the 3 rulers', everestWins === 1,
      `winners: asl=${w1}, base=${w2}, centre=${w3}`);
check('the 3 rulers have 3 DISTINCT winners', new Set([w1, w2, w3]).size === 3,
      `${w1} / ${w2} / ${w3}`);

// ── report ────────────────────────────────────────────────────────────────
console.log('\n  Is Everest the tallest mountain? — offline verification\n');
for (const r of results) {
  console.log(`  ${r.pass ? 'PASS' : 'FAIL'}  ${r.name}`);
  if (r.detail) console.log(`         ${r.detail}`);
}
console.log(`\n  ${results.length - failures}/${results.length} checks passed.\n`);
process.exit(failures === 0 ? 0 : 1);
