#!/usr/bin/env node
// verify.mjs — The moon does not swell at the horizon.
//
// The illusion is real (a fact of perception); the *enlargement of the moon* is
// not. The moon's angular size across the sky is pure geometry — distance from
// the observer's eye to the moon's centre — and we recompute it here from
// published constants. The headline result: at the horizon the moon is, if
// anything, slightly SMALLER than overhead (you are about one Earth-radius
// farther from it), the exact opposite of what we see. The page recomputes the
// same numbers live; this file is the offline twin.
//
// Run: node research/moon-illusion/verify.mjs   (exit 0 = all pass)

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? ' — ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? ' — ' + detail : ''}`); }
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const DEG = 180 / Math.PI;

// ---- Published constants (km). Sources in facts.md. ----
const R_EARTH   = 6371.0;     // Earth mean (volumetric) radius, IAU/IUGG
const D_MEAN    = 384400.0;   // Earth–Moon mean centre-to-centre distance
const D_PERIGEE = 363300.0;   // mean perigee distance
const D_APOGEE  = 405500.0;   // mean apogee distance
const R_MOON    = 1737.4;     // Moon mean radius (so diameter 3474.8 km)
const MOON_DIAM = 2 * R_MOON;

// Angular diameter (deg) of a sphere of radius r seen from distance s (eye→centre).
// Exact: 2*asin(r/s). Small-angle 2*r/s agrees to <1e-4 deg here.
function angDiamDeg(s, r = R_MOON) { return 2 * Math.asin(r / s) * DEG; }

// Eye→Moon-centre distance for the moon at altitude `alt` (deg) above the horizon,
// observer on a spherical Earth of radius R_EARTH, moon centre at range d from
// Earth's centre. Law of cosines in triangle (Earth-centre, observer, moon).
// The angle at the observer between the local UP (zenith) and the moon is
// (90 - alt). cos of that = sin(alt).
function eyeToMoon(d, altDeg) {
  const cosTheta = Math.sin(altDeg / DEG);           // angle(up, moon) = 90-alt
  // |eye->moon|^2 = R^2 + d^2 - 2 R d cos(angle(up,moon))  ... wait: that angle is
  // measured AT the observer between (observer->Earth-centre is -up) ... do it cleanly:
  // Place observer at origin. Earth centre is at distance R straight DOWN (-up).
  // Moon is at distance L along a ray at altitude alt. Earth-centre to moon = d.
  //   d^2 = R^2 + L^2 - 2 R L cos(angle between (down) and (moon ray))
  // angle between DOWN and the moon ray = 90 + alt. cos(90+alt) = -sin(alt).
  //   d^2 = R^2 + L^2 + 2 R L sin(alt)   -> solve for L (positive root).
  const s = Math.sin(altDeg / DEG);
  const A = 1, B = 2 * R_EARTH * s, C = R_EARTH * R_EARTH - d * d;
  const L = (-B + Math.sqrt(B * B - 4 * A * C)) / 2;
  void cosTheta;
  return L;
}

console.log('\n=== The moon does not swell at the horizon ===\n');

// 1. Sanity: at the zenith the eye→moon distance is d − R_EARTH; at the horizon
//    it is sqrt(d² − R²). Confirm the closed forms against the general solver.
console.log('1. Geometry of eye→moon distance vs. altitude.');
const Lzenith  = eyeToMoon(D_MEAN, 90);
const Lhorizon = eyeToMoon(D_MEAN, 0);
check('zenith distance = d − R_earth', approx(Lzenith, D_MEAN - R_EARTH, 1e-6),
      `${Lzenith.toFixed(1)} km vs ${(D_MEAN - R_EARTH).toFixed(1)} km`);
check('horizon distance = √(d² − R²)', approx(Lhorizon, Math.sqrt(D_MEAN**2 - R_EARTH**2), 1e-6),
      `${Lhorizon.toFixed(1)} km vs ${Math.sqrt(D_MEAN**2 - R_EARTH**2).toFixed(1)} km`);
check('horizon moon is FARTHER than zenith moon', Lhorizon > Lzenith,
      `horizon ${Lhorizon.toFixed(0)} km > zenith ${Lzenith.toFixed(0)} km, by ${(Lhorizon-Lzenith).toFixed(0)} km`);

// 2. The headline correction: horizon angular diameter is SMALLER, not larger.
console.log('\n2. The angular diameter therefore SHRINKS from zenith to horizon.');
const angZ = angDiamDeg(Lzenith);
const angH = angDiamDeg(Lhorizon);
const shrinkPct = (1 - angH / angZ) * 100;
check('zenith angular diameter ≈ 0.527°', approx(angZ, 0.527, 0.004), `${angZ.toFixed(4)}°`);
check('horizon angular diameter ≈ 0.518°', approx(angH, 0.518, 0.004), `${angH.toFixed(4)}°`);
check('horizon disc is ~1.7% SMALLER than zenith disc', approx(shrinkPct, 1.67, 0.2),
      `shrinks ${shrinkPct.toFixed(2)}% (the OPPOSITE of the illusion)`);

// 3. The arc-minute figures people quote, and the perigee/apogee spread, which is
//    far larger than the horizon/zenith difference — yet nobody "sees" it.
console.log('\n3. Angular size in arc-minutes, and the real (orbital) size change.');
const arcmin = (deg) => deg * 60;
check('mean moon ≈ 31.6 arc-minutes overhead', approx(arcmin(angZ), 31.6, 0.3), `${arcmin(angZ).toFixed(2)}′`);
const angPeri = angDiamDeg(D_PERIGEE - R_EARTH);   // perigee, overhead
const angApo  = angDiamDeg(D_APOGEE  - R_EARTH);   // apogee, overhead
const orbitSwingPct = (angPeri / angApo - 1) * 100;
check('perigee-vs-apogee swing ≈ 12% (real, and mostly unnoticed)',
      approx(orbitSwingPct, 12, 1.5),
      `perigee ${arcmin(angPeri).toFixed(1)}′ vs apogee ${arcmin(angApo).toFixed(1)}′`);
check('orbital swing dwarfs the horizon–zenith change',
      orbitSwingPct > shrinkPct * 5,
      `12% orbital vs ${shrinkPct.toFixed(1)}% horizon–zenith — we notice neither, yet "see" a 50% horizon swell`);

// 4. The coin / pinky-nail test: what width at arm's length just covers the moon.
console.log('\n4. The "held at arm’s length" test — one object covers it all night.');
const ARM = 700;                       // mm, a typical adult arm's length (varies!)
// width w that subtends angle a at distance ARM: w = 2*ARM*tan(a/2)
const coverW = (deg) => 2 * ARM * Math.tan(deg / 2 / DEG);
const wZ = coverW(angZ), wH = coverW(angH);
check('moon ≈ 6.4 mm wide at arm’s length (overhead)', approx(wZ, 6.4, 0.3), `${wZ.toFixed(2)} mm @ ${ARM} mm`);
check('a pinky-nail (≈10–12 mm) more than covers it', wZ < 10 && wH < 10,
      `needs only ${wZ.toFixed(1)}–${wH.toFixed(1)} mm; a fingernail is ~10–12 mm`);
check('the covering width barely changes horizon→zenith', approx(wZ - wH, 0, 0.2),
      `${(wZ - wH).toFixed(3)} mm difference — the same object covers both`);

// 5. Atmospheric refraction does NOT magnify; near the horizon it FLATTENS.
//    Standard-atmosphere refraction lifts the apparent altitude; the lift is
//    larger for the lower limb than the upper, compressing the disc vertically.
//    (Horizontal width is essentially untouched.) Figures are standard-atmosphere
//    approximations — named as such on the page and in facts.md.
console.log('\n5. Refraction squashes the low moon — it never magnifies it.');
const refrHorizonArcmin = 34.0;        // standard refraction at the true horizon (approx)
const refrHalfDegUp     = 29.0;        // ~refraction ~0.5° up (approx, std atmosphere)
const vertCompressArcmin = refrHorizonArcmin - refrHalfDegUp; // lower limb lifted more
check('horizon refraction ≈ 34′ (lifts the whole disc, std atmosphere)',
      approx(refrHorizonArcmin, 34, 0.001), `${refrHorizonArcmin}′ — enough to set the disc visually below the true horizon`);
check('differential refraction COMPRESSES the disc vertically (oval, wider than tall)',
      vertCompressArcmin > 0, `~${vertCompressArcmin.toFixed(0)}′ of vertical squash — the opposite of swelling`);

// 6. The illusion's SIZE is a perceptual measurement (named, not asserted as a constant).
console.log('\n6. The illusion itself — reported as a measured range, not a theorem.');
const reportedLow = 1.3, reportedHigh = 2.0, typical = 1.5;
check('reported horizon/zenith perceived-size ratio sits in ~1.3–2.0',
      typical >= reportedLow && typical <= reportedHigh,
      `typical ≈${typical}× (Kaufman & Rock; Ross & Plug) — a perception measurement, cause still debated`);

console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAIL'} — ${pass} passed, ${fail} failed\n`);
process.exit(fail === 0 ? 0 : 1);
