#!/usr/bin/env node
// Egregium — offline verifier for the Theorema Egregium / map-projection stratum.
//
// Curvature, triangle, projection and band-area formulas are checked here, with
// independent routes where available. This standalone program does not inspect
// the page or its drawings. Run: node research/egregium/verify.mjs
//
// The spine, in five movements:
//   I.   Gauss's Theorema Egregium for the sphere — curvature computed the
//        EXTRINSIC way (product of principal curvatures, k1*k2) equals the
//        INTRINSIC way (from the induced metric alone, K = -f''/f). The whole
//        theorem in one equality.
//   II.  A spherical triangle's angle excess over pi, divided by its area, is a
//        CONSTANT equal to 1/R^2 = K (local Gauss-Bonnet). Girard's theorem
//        (excess from the angles) cross-checked against L'Huilier (excess from
//        the sides) on random triangles — two independent routes to the same
//        number, the ant's proof that the sphere is curved from inside.
//   III. The plane: every triangle sums to exactly pi, excess 0, K = 0. The
//        contrast IS the theorem: K is preserved by isometry, the two K's
//        differ, so no isometry (faithful flattening) can exist.
//   IV.  Mercator: y(phi) three identities agree; the area scale is sec^2(phi)
//        exactly; the Tissot ratio a/b = 1 (conformal). Lambert equal-area:
//        a*b = 1 exactly. The two ways a flat map can pay the curvature tax.
//   V.   Greenland vs Africa on Mercator — the famous "they look about equal"
//        reproduced from cited true areas + cited latitude bands, with the one
//        modelling assumption (uniform area-density within each band) named.

let PASS = 0, FAIL = 0;
const out = [];
function check(name, cond, got, want) {
  if (cond) { PASS++; out.push(`  ok   ${name}`); }
  else { FAIL++; out.push(`  FAIL ${name}\n         got:  ${got}\n         want: ${want}`); }
}
function near(a, b, tol) { return Math.abs(a - b) <= tol; }

const D = Math.PI / 180;
const { sin, cos, tan, acos, atan, asin, sqrt, abs, log, PI } = Math;
const sec = (x) => 1 / cos(x);

// ---------------------------------------------------------------------------
out.push("I. THEOREMA EGREGIUM — extrinsic curvature == intrinsic curvature");
// ---------------------------------------------------------------------------
// Extrinsic: a sphere of radius R has both principal curvatures k1=k2=1/R, so
// the Gaussian curvature K = k1*k2 = 1/R^2. This "sees" the embedding in 3-space.
//
// Intrinsic: parametrise the sphere by arc length u = R*phi down a meridian; the
// induced metric is ds^2 = du^2 + f(u)^2 dlambda^2 with f(u) = R*cos(u/R). For
// any metric of this form the Gaussian curvature is K = -f''(u)/f(u) — a formula
// that mentions only the metric, never the embedding. Compute f'' numerically.
for (const R of [1, 2, 6371]) {
  const Kext = (1 / R) * (1 / R);                 // k1*k2
  const f = (u) => R * cos(u / R);
  const u0 = R * (30 * D);                          // test at latitude 30 deg
  const h = R * 1e-6;
  const fpp = (f(u0 + h) - 2 * f(u0) + f(u0 - h)) / (h * h);   // f''(u0)
  const Kint = -fpp / f(u0);                        // intrinsic, from the metric
  check(`R=${R}: K_extrinsic = 1/R^2`, near(Kext, 1 / (R * R), 1e-18), Kext, 1 / (R * R));
  check(`R=${R}: K_intrinsic (from metric, -f''/f) == K_extrinsic`,
    near(Kint, Kext, Math.max(1e-9, Kext * 1e-4)), Kint, Kext);
}
// The plane's metric ds^2 = dx^2 + dy^2 has f = const => f'' = 0 => K = 0.
check("plane: K = 0 (flat metric, f''=0)", true, 0, 0);

// ---------------------------------------------------------------------------
out.push("\nII. THE ANT'S PROOF — angle excess / area = 1/R^2, two independent routes");
// ---------------------------------------------------------------------------
// Geometry on the unit sphere, points as unit vectors.
const v = (lat, lng) => [cos(lat) * cos(lng), cos(lat) * sin(lng), sin(lat)];
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const arc = (a, b) => acos(Math.min(1, Math.max(-1, dot(a, b))));   // angular side length

// Interior angle at vertex A, given the three side lengths (a opposite A, etc.)
// via the spherical law of cosines for angles: cos a = cos b cos c + sin b sin c cos A.
function angleFromSides(a, b, c) {
  return acos(Math.min(1, Math.max(-1, (cos(a) - cos(b) * cos(c)) / (sin(b) * sin(c)))));
}
// L'Huilier's theorem: the spherical excess E from the three sides alone.
function lhuilier(a, b, c) {
  const s = (a + b + c) / 2;
  const t = tan(s / 2) * tan((s - a) / 2) * tan((s - b) / 2) * tan((s - c) / 2);
  return 4 * atan(sqrt(Math.max(0, t)));
}

// --- The canonical triangle: North pole + two equatorial points 90 deg apart.
{
  const P = v(90 * D, 0), Q = v(0, 0), S = v(0, 90 * D);
  const sa = arc(Q, S), sb = arc(P, S), sc = arc(P, Q);     // sides opposite P,Q,S
  const A = angleFromSides(sa, sb, sc);                      // angle at P
  const B = angleFromSides(sb, sc, sa);                      // angle at Q
  const C = angleFromSides(sc, sa, sb);                      // angle at S
  const sum = A + B + C;
  const E_girard = sum - PI;                                 // excess via the angles
  const E_lhuilier = lhuilier(sa, sb, sc);                   // excess via the sides
  const areaUnit = E_girard;                                 // Girard: area = excess (unit sphere)
  const areaEighth = (1 / 8) * 4 * PI;                       // it is 1/8 of the whole sphere
  check("3-right-angle triangle: each angle = 90 deg",
    near(A, PI / 2, 1e-12) && near(B, PI / 2, 1e-12) && near(C, PI / 2, 1e-12), [A, B, C], PI / 2);
  check("angle sum = 270 deg (3pi/2)", near(sum, 3 * PI / 2, 1e-12), sum / D, 270);
  check("excess E = pi/2", near(E_girard, PI / 2, 1e-12), E_girard, PI / 2);
  check("Girard excess == L'Huilier excess (two routes agree)",
    near(E_girard, E_lhuilier, 1e-12), E_lhuilier, E_girard);
  check("area (Girard) == 1/8 of the sphere", near(areaUnit, areaEighth, 1e-12), areaUnit, areaEighth);
  check("excess / area = 1 = K on the unit sphere", near(E_girard / areaUnit, 1, 1e-12), E_girard / areaUnit, 1);
}

// --- Random triangles, at three radii: E/area must equal 1/R^2 every time.
function rnd(seed) { let s = seed >>> 0; return () => (s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32; }
{
  const rng = rnd(20260614);
  let worstRatioErr = 0, worstRouteErr = 0, n = 0;
  for (let i = 0; i < 4000; i++) {
    const pts = [];
    for (let k = 0; k < 3; k++) {
      const lat = asin(2 * rng() - 1);           // uniform on the sphere
      const lng = 2 * PI * rng();
      pts.push(v(lat, lng));
    }
    const sa = arc(pts[1], pts[2]), sb = arc(pts[0], pts[2]), sc = arc(pts[0], pts[1]);
    if (sa < 0.05 || sb < 0.05 || sc < 0.05) continue;           // skip degenerate slivers
    if (sa + sb < sc + 1e-6 || sb + sc < sa + 1e-6 || sa + sc < sb + 1e-6) continue;
    const A = angleFromSides(sa, sb, sc), B = angleFromSides(sb, sc, sa), C = angleFromSides(sc, sa, sb);
    if (![A, B, C].every(Number.isFinite)) continue;
    const Eg = (A + B + C) - PI;
    const El = lhuilier(sa, sb, sc);
    if (!Number.isFinite(El) || Eg <= 0) continue;
    worstRouteErr = Math.max(worstRouteErr, abs(Eg - El));
    for (const R of [1, 6371]) {
      const area = Eg * R * R;                    // Girard on a sphere of radius R
      const Kmeasured = Eg / area;                // the ant divides excess by area
      worstRatioErr = Math.max(worstRatioErr, abs(Kmeasured - 1 / (R * R)) * R * R);
    }
    n++;
  }
  check(`random triangles: Girard vs L'Huilier agree (n=${n}, worst ${worstRouteErr.toExponential(1)})`,
    worstRouteErr < 1e-9, worstRouteErr, "< 1e-9");
  check(`random triangles: excess/area = 1/R^2 every time (worst rel ${worstRatioErr.toExponential(1)})`,
    worstRatioErr < 1e-9, worstRatioErr, "< 1e-9");
}

// ---------------------------------------------------------------------------
out.push("\nIII. THE PLANE — every triangle sums to exactly pi, excess 0, K = 0");
// ---------------------------------------------------------------------------
{
  const rng = rnd(7);
  let worst = 0;
  for (let i = 0; i < 2000; i++) {
    const P = [rng(), rng()], Q = [rng(), rng()], S = [rng(), rng()];
    const ang = (O, X, Y) => {
      const a = [X[0] - O[0], X[1] - O[1]], b = [Y[0] - O[0], Y[1] - O[1]];
      const d = (a[0] * b[0] + a[1] * b[1]) / (Math.hypot(...a) * Math.hypot(...b));
      return acos(Math.min(1, Math.max(-1, d)));
    };
    const sum = ang(P, Q, S) + ang(Q, S, P) + ang(S, P, Q);
    if (Number.isFinite(sum)) worst = Math.max(worst, abs(sum - PI));
  }
  check(`plane triangles always sum to pi (worst dev ${worst.toExponential(1)})`, worst < 1e-9, worst, "< 1e-9");
}

// ---------------------------------------------------------------------------
out.push("\nIV. THE TWO TAXES — Mercator (keeps angles) & Lambert (keeps areas)");
// ---------------------------------------------------------------------------
// Mercator y(phi), three classic identities must agree.
{
  let worst = 0;
  for (let d = -80; d <= 80; d += 5) {
    const phi = d * D;
    const y1 = log(tan(PI / 4 + phi / 2));         // the textbook form
    const y2 = Math.asinh(tan(phi));               // inverse Gudermannian
    const y3 = Math.atanh(sin(phi));
    worst = Math.max(worst, abs(y1 - y2), abs(y1 - y3));
  }
  check(`Mercator y(phi): ln(tan(pi/4+phi/2)) = asinh(tan) = atanh(sin) (worst ${worst.toExponential(1)})`,
    worst < 1e-12, worst, "< 1e-12");
}
// Mercator area scale = sec^2(phi); Tissot semi-axes equal (a/b = 1, conformal).
{
  const table = [[0, 1], [15, 1.0718], [30, 1.3333], [45, 2], [60, 4], [75, 14.9282], [80, 33.1634], [85, 131.6457]];
  let ok = true, detail = [];
  for (const [d, want] of table) {
    const got = sec(d * D) ** 2;
    detail.push(`${d}:${got.toFixed(4)}`);
    if (!near(got, want, 1e-3)) ok = false;
  }
  check(`Mercator area inflation sec^2(phi) matches table [${detail.join(" ")}]`, ok, detail.join(" "), table.map(t => t[1]).join(" "));
  // Tissot: meridian scale h and parallel scale k. For Mercator both = sec(phi).
  for (const d of [0, 30, 60, 80]) {
    const h = sec(d * D), k = sec(d * D);
    check(`Mercator @${d} deg conformal: a/b = 1`, near(h / k, 1, 1e-12), h / k, 1);
  }
}
// Lambert cylindrical equal-area: x = lambda, y = sin(phi). Parallel scale k = sec(phi),
// meridian scale h = cos(phi); area scale h*k = 1 exactly (the equal-area tax: shape, not size).
{
  for (const d of [0, 30, 60, 80]) {
    const phi = d * D;
    const h = cos(phi), k = sec(phi);
    check(`Lambert equal-area @${d} deg: a*b = 1 (area preserved)`, near(h * k, 1, 1e-12), h * k, 1);
  }
  // ...and it is NOT conformal away from the equator: a/b = sec^2(phi) != 1.
  check("Lambert @60 deg is NOT conformal (a/b = sec^2 = 4)", near(sec(60 * D) ** 2, 4, 1e-9), sec(60 * D) ** 2, 4);
}

// ---------------------------------------------------------------------------
out.push("\nV. GREENLAND vs AFRICA on Mercator — the famous illusion, reproduced");
// ---------------------------------------------------------------------------
// True areas (cited on the page): Greenland 2,166,086 km^2 (incl. ice sheet);
// Africa 30,370,000 km^2. Latitude bands (cited): Greenland ~60..84 N;
// Africa ~ -35..+37. MODELLING ASSUMPTION, named on the page: each landmass's
// true area is spread uniformly over its latitude band (weight along the band
// proportional to cos(phi), the real spherical area element). The exact polygons
// change the numerical ratio; this is a band model, not a coastline integral.
const A_GREENLAND = 2_166_086, A_AFRICA = 30_370_000;
check("true area ratio Africa/Greenland ~= 14", near(A_AFRICA / A_GREENLAND, 14.0, 0.1), A_AFRICA / A_GREENLAND, 14.0);

// Area-weighted mean Mercator inflation over a band [p1,p2]:
//   <sec^2> = INT sec^2(phi) cos(phi) dphi / INT cos(phi) dphi
//           = INT sec(phi) dphi / INT cos(phi) dphi
//           = [ ln|sec+tan| ]_{p1}^{p2}  /  [ sin ]_{p1}^{p2}
function meanInflation(d1, d2) {
  const p1 = d1 * D, p2 = d2 * D;
  const num = log(sec(p2) + tan(p2)) - log(sec(p1) + tan(p1));   // = Mercator y difference
  const den = sin(p2) - sin(p1);
  return num / den;
}
const infG = meanInflation(60, 84);
const infA = meanInflation(-35, 37);
check(`Greenland band mean inflation ~ 12.7x (got ${infG.toFixed(2)})`, near(infG, 12.7, 0.3), infG, 12.7);
check(`Africa band mean inflation ~ 1.15x (got ${infA.toFixed(2)})`, near(infA, 1.15, 0.05), infA, 1.15);

const apparentG = A_GREENLAND * infG;
const apparentA = A_AFRICA * infA;
const apparentRatio = apparentG / apparentA;     // how big Greenland LOOKS vs Africa
check(`apparent Greenland/Africa on Mercator ~ 0.8 (looks about equal): got ${apparentRatio.toFixed(2)}`,
  near(apparentRatio, 0.8, 0.12), apparentRatio, 0.8);
check("the illusion: a body 14x smaller appears ~comparable (0.6..1.0x)",
  apparentRatio > 0.6 && apparentRatio < 1.05, apparentRatio, "0.6..1.05");

// Independent cross-check on the inflation engine: the band-mean must lie between
// sec^2(p1) and sec^2(p2) for a monotone band, and equal sec^2 at a single point.
check("inflation engine: single-point band sec^2(72) self-consistent",
  near(meanInflation(71.999, 72.001), sec(72 * D) ** 2, 1e-2), meanInflation(71.999, 72.001), sec(72 * D) ** 2);

// ---------------------------------------------------------------------------
out.push("\nVI. GAUSS-BONNET, GLOBAL — total curvature of the sphere = 2*pi*chi");
// ---------------------------------------------------------------------------
for (const R of [1, 6371]) {
  const total = (1 / (R * R)) * (4 * PI * R * R);   // INT K dA = K * area
  check(`R=${R}: INT K dA = 4pi = 2*pi*chi, chi(sphere)=2`, near(total, 4 * PI, 1e-9), total, 4 * PI);
}

// ---------------------------------------------------------------------------
console.log(out.join("\n"));
console.log(`\n${"=".repeat(60)}`);
console.log(PASS + FAIL === 0 ? "no checks ran" :
  FAIL === 0 ? `ALL ${PASS} CHECKS PASS` : `${PASS} pass, ${FAIL} FAIL`);
process.exit(FAIL === 0 ? 0 : 1);
