// verify.mjs — "The Cannonball That Never Lands" (why the moon doesn't fall to Earth).
//
// The page's load-bearing claim: the Moon (and every satellite) IS falling —
// continuously accelerating toward Earth's centre — and the only reason it never
// lands is that it moves sideways fast enough that the round Earth curves away
// beneath it by exactly as much as it falls. Newton's cannonball: fire fast enough
// and the trajectory's curvature matches the planet's, so the ball circles forever.
//
// Two misconceptions the page corrects, both checked numerically here:
//   (1) "There's no gravity in space" — at the ISS's altitude gravity is still
//       ~90% of its surface value; astronauts float because they're in free fall.
//   (2) "The Moon is too far for gravity / it just floats" — its inward
//       acceleration is exactly Earth's surface gravity scaled by the inverse
//       square of its distance (Newton's own Moon test, the 1/3600 ratio).
//
// Every constant and threshold the page shows is recomputed here from first
// principles (G, M_earth, R_earth + a few measured orbital inputs), AND the page's
// trajectory engine is cross-checked: an independent velocity-Verlet integration
// of F = GMm/r^2 reproduces the analytic circular-orbit period and the exact
// ellipse the page draws. Shown == checked.
//
// Run:  node research/moon-cannonball/verify.mjs
// No dependencies. Node 18+.

let pass = 0, fail = 0;
const near = (got, want, tol, msg) => {
  const ok = Math.abs(got - want) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}  ${ok ? `(${fmt(got)})` : `→ got ${fmt(got)}, want ${fmt(want)}±${tol}`}`);
  ok ? pass++ : fail++;
};
const truth = (cond, msg) => {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${msg}`);
  cond ? pass++ : fail++;
};
const fmt = (x) => (Math.abs(x) >= 1e4 || (Math.abs(x) < 1e-3 && x !== 0))
  ? x.toExponential(4) : Number(x.toFixed(4)).toString();

// ── measured inputs (CODATA / IAU / standard handbook values) ──────────────────
const G      = 6.67430e-11;   // m^3 kg^-1 s^-2  (CODATA 2018)
const M      = 5.9722e24;     // kg   Earth mass (IAU)
const R      = 6.371e6;       // m    Earth mean radius
const mu     = G * M;         // standard gravitational parameter
const g_std  = 9.80665;       // m/s^2  standard surface gravity (defined)

// ── 1. the gravitational parameter and surface gravity ─────────────────────────
near(mu, 3.986e14, 0.01e14, 'mu = G*M ≈ 3.986e14 m^3/s^2');
const g0 = mu / (R * R);                       // Newtonian g at the mean radius
near(g0, 9.82, 0.02, 'surface gravity mu/R^2 ≈ 9.82 m/s^2 (vs defined 9.807; gap = rotation + oblateness)');
truth(Math.abs(g0 - g_std) < 0.05, 'computed g0 is within 0.05 of standard g (the small gap is real, named on the page)');

// ── 2. the two iconic speeds at the surface ────────────────────────────────────
const vCirc = Math.sqrt(mu / R);               // circular-orbit speed
const vEsc  = Math.sqrt(2 * mu / R);           // escape speed
near(vCirc, 7910, 20, 'circular speed at surface sqrt(mu/R) ≈ 7.91 km/s');
near(vEsc, 11186, 30, 'escape speed at surface sqrt(2 mu/R) ≈ 11.19 km/s');
near(vEsc / vCirc, Math.SQRT2, 1e-6, 'escape speed = sqrt(2) × circular speed (exact)');

// low-circular-orbit period (the famous "~90 minutes")
const Tlow = 2 * Math.PI * Math.sqrt(R ** 3 / mu);
near(Tlow / 60, 84.3, 0.3, 'low circular orbit period 2*pi*sqrt(R^3/mu) ≈ 84 min');

// ── 2b. the page's actual launch: a cannon 300 km up (real low-orbit altitude) ──
// Newton's mountain reaches above the atmosphere; 300 km is where real satellites
// orbit, so these are the numbers the simulator shows (the ground values above are
// the textbook ideal, cross-referenced on the page).
const hMtn = 300e3, r0 = R + hMtn;
const vCircMtn = Math.sqrt(mu / r0);
const vEscMtn  = Math.sqrt(2 * mu / r0);
const gMtn     = mu / (r0 * r0);
near(vCircMtn, 7730, 15, 'circular speed at 300 km sqrt(mu/r0) ≈ 7.73 km/s (a real LEO satellite speed)');
near(vEscMtn, 10932, 20, 'escape speed at 300 km ≈ 10.93 km/s');
near(gMtn, 8.96, 0.03, 'gravity at the 300 km launch ≈ 8.96 m/s^2 (still ~91% of surface)');
near(vCircMtn / vCirc, 0.977, 0.005, '300 km circular speed is only ~2% below the ground value — height barely matters');

// ── 3. "no gravity in space" is false: the ISS ─────────────────────────────────
const issAlt = 420e3;                          // m  (ISS orbits ~400–420 km)
const rISS   = R + issAlt;
const gISS   = mu / (rISS * rISS);
near(gISS, 8.68, 0.05, 'gravity at ISS altitude (420 km) ≈ 8.7 m/s^2');
near(gISS / g0, 0.886, 0.01, 'ISS gravity is ~89% of surface gravity — not zero');
const vISS = Math.sqrt(mu / rISS);
near(2 * Math.PI * rISS / vISS / 60, 92.6, 0.5, 'ISS orbital period ≈ 93 min');

// ── 4. Newton's Moon test: the 1/3600 ratio ────────────────────────────────────
const aMoon = 3.844e8;                          // m   Moon mean orbital radius
const Tmoon = 27.3217 * 86400;                  // s   sidereal month
const vMoon = 2 * Math.PI * aMoon / Tmoon;      // mean orbital speed
near(vMoon, 1022, 5, 'Moon mean orbital speed ≈ 1.02 km/s');

const aCentMoon = vMoon * vMoon / aMoon;         // observed centripetal acceleration
const gAtMoon   = mu / (aMoon * aMoon);          // predicted gravity at Moon's distance
near(aCentMoon, 2.72e-3, 0.05e-3, 'Moon centripetal accel v^2/r ≈ 0.0027 m/s^2 (measured from period+distance)');
near(gAtMoon, 2.70e-3, 0.05e-3, 'gravity predicted at Moon distance mu/a^2 ≈ 0.0027 m/s^2');
truth(Math.abs(aCentMoon - gAtMoon) / gAtMoon < 0.02,
  "Newton's test: the Moon's pull-toward-Earth equals Earth's gravity at that distance (<2%)");

const ratio = g0 / gAtMoon;
near(ratio, 3637, 60, 'surface g is ~3600× the Moon-distance g');
near(aMoon / R, 60.3, 0.5, 'Moon is ~60 Earth-radii out');
near((aMoon / R) ** 2, 3640, 60, '...and 60^2 ≈ 3600 — the inverse-square law, confirmed by Newton');

// ── 5. "it falls forever": the per-second fall vs the curving-away Earth ────────
const dt = 1; // one second
const fallPerSec     = 0.5 * gAtMoon * dt * dt; // how far the Moon falls in 1 s
const sidewaysPerSec = vMoon * dt;              // how far it moves sideways in 1 s
const sagitta        = sidewaysPerSec ** 2 / (2 * aMoon); // how far the orbit curves away over that arc
near(fallPerSec * 1000, 1.36, 0.05, 'Moon falls ≈ 1.36 mm toward Earth each second');
near(sidewaysPerSec / 1000, 1.022, 0.01, '...while sweeping ≈ 1.02 km sideways');
truth(Math.abs(fallPerSec - sagitta) / fallPerSec < 0.01,
  'the fall (1.36 mm) equals how much the round path curves away over that 1 km — THAT is the orbit');

// ── 6. cross-check the page's engine: velocity-Verlet integration of F=GMm/r^2 ──
// The page integrates real Newtonian gravity. Launch a ball tangentially at the
// surface at exactly vCirc; an honest integrator must return it to the start after
// one analytic period, tracing a circle of constant radius R.
function integrate(r0, v0, steps, totalT) {
  const h = totalT / steps;
  let x = 0, y = r0;          // launch at top of the planet
  let vx = v0, vy = 0;        // fired horizontally
  const acc = (px, py) => {
    const r = Math.hypot(px, py);
    const a = -mu / (r * r);  // magnitude toward centre
    return [a * px / r, a * py / r];
  };
  let [ax, ay] = acc(x, y);
  let rmin = r0, rmax = r0;
  for (let i = 0; i < steps; i++) {
    x += vx * h + 0.5 * ax * h * h;
    y += vy * h + 0.5 * ay * h * h;
    const [nax, nay] = acc(x, y);
    vx += 0.5 * (ax + nax) * h;
    vy += 0.5 * (ay + nay) * h;
    ax = nax; ay = nay;
    const r = Math.hypot(x, y);
    rmin = Math.min(rmin, r); rmax = Math.max(rmax, r);
  }
  return { x, y, vx, vy, rmin, rmax };
}

const Tmtn = 2 * Math.PI * Math.sqrt(r0 ** 3 / mu);
const sim = integrate(r0, vCircMtn, 20000, Tmtn);
// after exactly one period the ball is back at the launch point (top, at r0)
near(sim.x / r0, 0, 2e-3, 'Verlet: after one period the integrated ball returns to x≈0 (back at start)');
near(sim.y / r0, 1, 2e-3, 'Verlet: ...and to y≈r0 (the launch altitude)');
// and the radius never strayed from r0 (it really is a circle, not a spiral-in)
truth((sim.rmax - sim.rmin) / r0 < 5e-3,
  'Verlet: radius stays within 0.5% of r0 the whole way — a circle, falling forever (not a spiral into the ground)');

// energy conservation as an honesty check on the integrator itself
const E = (px, py, pvx, pvy) => 0.5 * (pvx * pvx + pvy * pvy) - mu / Math.hypot(px, py);
const E0 = E(0, r0, vCircMtn, 0), E1 = E(sim.x, sim.y, sim.vx, sim.vy);
truth(Math.abs((E1 - E0) / E0) < 1e-4, 'Verlet conserves specific orbital energy to <0.01% (symplectic)');

// ── 7. analytic ellipse used for the page's labels (tangential launch at r0) ───
// Fire at r0 with speed v (tangential ⇒ launch point is a vertex of the ellipse).
// e = |r0 v^2/mu - 1|;  a = 1 / (2/r0 - v^2/mu);  perigee/apogee = a(1∓e).
// Ground is r = R; a perigee below R means it crashes (sub-orbital).
function orbit(v) {
  const energy = 0.5 * v * v - mu / r0;
  const a = -mu / (2 * energy);              // <0 ⇒ unbound
  const e = Math.abs(r0 * v * v / mu - 1);
  const bound = energy < 0;
  const rp = bound ? a * (1 - e) : null;     // perigee radius
  const ra = bound ? a * (1 + e) : null;     // apogee radius
  return { energy, a, e, bound, rp, ra };
}
// well below circular ⇒ perigee dips below the surface ⇒ it crashes (sub-orbital)
truth(orbit(6500).bound && orbit(6500).rp < R, 'v=6.5 km/s: bound but perigee below surface → sub-orbital (lands)');
// exactly circular at the launch altitude ⇒ e≈0
near(orbit(vCircMtn).e, 0, 1e-9, 'v=vCirc(300km): eccentricity = 0 (a circle)');
// between circular and escape ⇒ a real ellipse clearing the surface
truth(orbit(9000).bound && orbit(9000).rp >= R, 'v=9.0 km/s: elliptical orbit clearing the surface');
truth(orbit(9000).ra > r0, '...with apogee above the launch point');
// at/above escape ⇒ unbound
truth(!orbit(vEscMtn + 1).bound, 'v>vEsc(300km): unbound (escapes Earth)');
near(orbit(vEscMtn).energy, 0, 1e6, 'v=vEsc(300km): specific orbital energy = 0 (parabolic boundary)');

// ── tally ──────────────────────────────────────────────────────────────────────
console.log(`\n${pass}/${pass + fail} checks passed${fail ? ` — ${fail} FAILED` : ''}.`);
process.exit(fail ? 1 : 0);
