// verify-closest-planet-to-earth.mjs — the math behind the stratum
// "The Closest Neighbour You'll Never Meet" (/strata/closest-planet-to-earth/).
//
// The claim the page corrects: "Venus is Earth's closest neighbour" is a
// schoolroom fact that is only true for one metric (minimum separation).
// Averaged over time — equivalently, over all orbital configurations —
// MERCURY, not Venus, is the planet whose distance from Earth is smallest.
// And by the same logic Mercury is, on average, the closest planet to EVERY
// other planet in the solar system (even Neptune).
//
// Argued by Tom Stockman, Gabriel Monroe & Samuel Cordner in "Venus is not
// Earth's closest neighbor," Physics Today (online, 12 March 2019) — a
// commentary column, not a peer-reviewed paper.
//
// APPROXIMATION (stated everywhere): circular, coplanar orbits with the
// relative orbital phase uniformly distributed. Real orbits are eccentric and
// inclined; those are small corrections. This is the authors' "point-circle
// method" (PCM).
//
// What this script proves, offline and from scratch:
//   1. Two INDEPENDENT engines for the mean Earth-planet distance agree to
//      machine precision:
//        (A) closed form  d_avg = (2/pi)(r1+r2)*E(m),  m = 4 r1 r2/(r1+r2)^2
//            with E the complete elliptic integral of the 2nd kind, computed
//            here by the arithmetic-geometric-mean (AGM) recurrence;
//        (B) direct numeric average of d(theta)=sqrt(r1^2+r2^2-2 r1 r2 cos th)
//            over th in [0,2pi) (trapezoid over a full period).
//   2. A third, physically-motivated engine (C) — step both planets around
//      their orbits at their true Keplerian rates (T ~ a^1.5) and time-average
//      the separation — converges to the SAME value. This is the content of
//      "time-average = configuration-average": the relative phase equidistributes.
//   3. Time-average ranking for Earth's neighbours: Mercury < Venus < Mars.
//      PCM means ~1.04 / 1.14 / 1.69 AU, matching Physics Today's 1.04 & 1.14.
//   4. The popular "Venus" answer falls out of a DIFFERENT metric — minimum
//      separation |r1-r2| — where Venus (0.277 AU ~= 41 M km) < Mars < Mercury.
//      The ranking literally flips between the two metrics.
//   5. Mercury is, on average, the closest planet to EVERY planet: build the
//      full 8x8 PCM matrix and assert that in every column the nearest other
//      planet is Mercury — including Neptune, where the gaps are tiny but real.
//   6. The page's OWN output (not from the paper): the fraction of time each of
//      Mercury/Venus/Mars is Earth's nearest planet, from a long incommensurate
//      simulation. Recomputed and labelled as ours, ~47/37/16 %.
//
//   run:  node research/closest-planet-to-earth/verify-closest-planet-to-earth.mjs
//
// No dependencies. Every number the page displays is recomputed here.

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) pass++; else fail++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── constants ────────────────────────────────────────────────────────────────
const AU_KM = 149_597_870.7; // 1 astronomical unit in km (IAU 2012 definition)

// Semi-major axes in AU — standard NASA planetary fact-sheet values. The
// headline results are insensitive to the last digit.
const A = {
  Mercury: 0.387,
  Venus:   0.723,
  Earth:   1.000,
  Mars:    1.524,
  Jupiter: 5.203,
  Saturn:  9.537,
  Uranus:  19.191,
  Neptune: 30.070,
};
const PLANETS = Object.keys(A);

// ── engine A: closed-form PCM via AGM elliptic integral ───────────────────────
// Complete elliptic integral of the 2nd kind E(m), parameter m = k^2, via the
// arithmetic-geometric mean. a0=1, b0=sqrt(1-m), c0=sqrt(m);
//   a_n=(a+b)/2, b_n=sqrt(ab), c_n=(a-b)/2;  AGM = lim a_n;
//   K = pi/(2 AGM);  E = K (1 - sum_{n>=0} 2^{n-1} c_n^2).
function ellipticE(m) {
  if (m >= 1) return 1; // E(1)=1 exactly; m=1 iff r1===r2. Without this the AGM
                        // drives a→0 at m=1 and returns 0 (a false, finite-looking mean).
  let a = 1, b = Math.sqrt(1 - m), c = Math.sqrt(m);
  let sum = 0.5 * c * c;   // n = 0 term: 2^{-1} c_0^2
  let twoPow = 1;          // 2^{n-1} for n = 1 is 2^0 = 1
  for (let n = 1; n <= 60; n++) {
    const a1 = (a + b) / 2, b1 = Math.sqrt(a * b), c1 = (a - b) / 2;
    sum += twoPow * c1 * c1;
    a = a1; b = b1; c = c1;
    // AGM converges quadratically; stop once a,b agree to machine precision.
    // (Breaking here keeps twoPow bounded — otherwise it overflows past the
    // shrinking c_n^2 and poisons the sum.)
    if (Math.abs(c1) <= 1e-16 * a || c1 === 0) break;
    twoPow *= 2;
  }
  const K = Math.PI / (2 * a);
  return K * (1 - sum);
}
function meanDistPCM(r1, r2) {
  const s = r1 + r2;
  const m = 4 * r1 * r2 / (s * s);
  return (2 / Math.PI) * s * ellipticE(m);
}

// ── engine B: direct numeric average of d(theta) over a full period ───────────
function meanDistNumeric(r1, r2, N = 200000) {
  let sum = 0;
  for (let i = 0; i < N; i++) {
    const th = (2 * Math.PI * i) / N;
    sum += Math.sqrt(r1 * r1 + r2 * r2 - 2 * r1 * r2 * Math.cos(th));
  }
  return sum / N;
}

// ── engine C: time-step both planets at their Keplerian rates, time-average ───
// T ~ a^1.5 (Kepler III, years with a in AU). Separation depends only on the
// relative phase; over long times that phase equidistributes → time-avg = PCM.
function meanDistTime(r1, r2, years, dt) {
  const dw = 2 * Math.PI * (Math.pow(r1, -1.5) - Math.pow(r2, -1.5));
  let sum = 0, n = 0;
  for (let t = 0; t < years; t += dt) {
    const dphi = dw * t;
    sum += Math.sqrt(r1 * r1 + r2 * r2 - 2 * r1 * r2 * Math.cos(dphi));
    n++;
  }
  return sum / n;
}

// closest-approach metric (circular, coplanar): minimum separation = |r1 - r2|
const minSep = (r1, r2) => Math.abs(r1 - r2);

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 1. two independent engines for the PCM mean distance agree —');
for (const p of ['Mercury', 'Venus', 'Mars']) {
  const dA = meanDistPCM(A.Earth, A[p]);
  const dB = meanDistNumeric(A.Earth, A[p]);
  ok(`Earth–${p.padEnd(7)} PCM(closed) = numeric`, approx(dA, dB, 1e-9),
     `${dA.toFixed(6)} vs ${dB.toFixed(6)} AU  (|Δ|=${Math.abs(dA - dB).toExponential(1)})`);
}

console.log('\n— PCM means vs Physics Today —');
const dMe = meanDistPCM(A.Earth, A.Mercury);
const dVe = meanDistPCM(A.Earth, A.Venus);
const dMa = meanDistPCM(A.Earth, A.Mars);
ok('Earth–Mercury ≈ 1.0378 AU (PT: 1.04)', approx(dMe, 1.0378, 5e-4), `${dMe.toFixed(4)} AU`);
ok('Earth–Venus   ≈ 1.1357 AU (PT: 1.14)', approx(dVe, 1.1357, 5e-4), `${dVe.toFixed(4)} AU`);
ok('Earth–Mars    ≈ 1.6930 AU',            approx(dMa, 1.6930, 5e-4), `${dMa.toFixed(4)} AU`);

// degenerate case: coincident orbits (r1 = r2 ⇒ m = 1). E(1) = 1, so the mean
// collapses to 4r/π ≈ 1.273r — NOT 0. Guards the AGM E(m) at the m→1 edge, which
// the interactive page can hit exactly (both orbit sliders at the same radius).
ok('coincident orbits: meanPCM(r,r) = 4r/π (E(1)=1, not 0)',
   approx(meanDistPCM(1, 1), 4 / Math.PI, 1e-12) &&
   approx(meanDistPCM(0.723, 0.723), (4 / Math.PI) * 0.723, 1e-12),
   `meanPCM(1,1)=${meanDistPCM(1, 1).toFixed(6)} vs 4/π=${(4 / Math.PI).toFixed(6)}`);

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 2. time-stepping (engine C) converges to the PCM value —');
for (const p of ['Mercury', 'Venus', 'Mars']) {
  const dPCM = meanDistPCM(A.Earth, A[p]);
  const dC = meanDistTime(A.Earth, A[p], 20000, 0.001);
  const rel = Math.abs(dC - dPCM) / dPCM;
  ok(`Earth–${p.padEnd(7)} time-avg ≈ PCM (within 0.1%)`, rel < 1e-3,
     `time=${dC.toFixed(5)}  PCM=${dPCM.toFixed(5)}  Δ=${(100 * rel).toFixed(3)}%`);
}

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 3. time-average ranking of Earth\'s neighbours: Mercury < Venus < Mars —');
console.log(`     Mercury ${dMe.toFixed(4)}  Venus ${dVe.toFixed(4)}  Mars ${dMa.toFixed(4)}  (AU)`);
ok('Mercury is Earth\'s nearest by time-average', dMe < dVe && dVe < dMa,
   `${dMe.toFixed(3)} < ${dVe.toFixed(3)} < ${dMa.toFixed(3)}`);

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 4. the popular answer is a DIFFERENT metric (closest approach) —');
const mVe = minSep(A.Earth, A.Venus);
const mMa = minSep(A.Earth, A.Mars);
const mMe = minSep(A.Earth, A.Mercury);
console.log(`     min sep  Venus ${mVe.toFixed(3)}  Mars ${mMa.toFixed(3)}  Mercury ${mMe.toFixed(3)}  (AU)`);
ok('closest-approach ranking flips to Venus < Mars < Mercury', mVe < mMa && mMa < mMe,
   `${mVe.toFixed(3)} < ${mMa.toFixed(3)} < ${mMe.toFixed(3)}`);
ok('Earth–Venus closest approach ≈ 0.277 AU', approx(mVe, 0.277, 1e-3), `${mVe.toFixed(3)} AU`);
const veKm = mVe * AU_KM;
ok('Earth–Venus closest approach ≈ 41.4 M km', approx(veKm / 1e6, 41.4, 0.3),
   `${(veKm / 1e6).toFixed(1)} M km`);
// sanity: the ranking is genuinely reversed between the two metrics
ok('the two metrics disagree on the winner (Mercury vs Venus)',
   (dMe < dVe) && (mVe < mMe));

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 5. Mercury is on average the closest planet to EVERY planet —');
// full symmetric PCM matrix; for each planet, the nearest OTHER planet.
const nearestOf = (target) => {
  let best = null, bestD = Infinity;
  for (const other of PLANETS) {
    if (other === target) continue;
    const d = meanDistPCM(A[target], A[other]);
    if (d < bestD) { bestD = d; best = other; }
  }
  return { best, bestD };
};
// The claim is about every planet OTHER than Mercury (a planet can't be its
// own neighbour). Mercury's own nearest is Venus — reported for honesty.
for (const target of PLANETS) {
  const { best, bestD } = nearestOf(target);
  if (target === 'Mercury') {
    console.log(`     (Mercury's own nearest is ${best} at ${bestD.toFixed(3)} AU — it can't be its own neighbour)`);
    continue;
  }
  ok(`nearest planet to ${target.padEnd(7)} is Mercury`, best === 'Mercury',
     `nearest = ${best} at ${bestD.toFixed(3)} AU`);
}
// the striking Neptune column, spelled out
console.log('     Neptune\'s neighbours (PCM mean distance, AU):');
const nep = ['Mercury', 'Venus', 'Earth', 'Mars']
  .map((p) => ({ p, d: meanDistPCM(A[p], A.Neptune) }))
  .sort((x, y) => x.d - y.d);
for (const r of nep) console.log(`       ${r.p.padEnd(7)} ${r.d.toFixed(3)}`);
ok('Mercury–Neptune < Venus–Neptune < Earth–Neptune < Mars–Neptune',
   nep[0].p === 'Mercury' && nep[1].p === 'Venus' && nep[2].p === 'Earth' && nep[3].p === 'Mars',
   nep.map((r) => `${r.p} ${r.d.toFixed(3)}`).join(' < '));

// ═══════════════════════════════════════════════════════════════════════════
console.log('\n— 6. the page\'s own output: fraction of time each is Earth\'s nearest —');
// NOT sourced from the primary column — recomputed here and labelled as ours.
// Step Mercury/Venus/Mars and Earth at Keplerian rates; each step, whichever is
// closest to Earth wins a tick. Incommensurate periods → stable fractions.
function nearestFractions(years, dt) {
  const w = {
    Earth: 2 * Math.PI * Math.pow(A.Earth, -1.5),
    Mercury: 2 * Math.PI * Math.pow(A.Mercury, -1.5),
    Venus: 2 * Math.PI * Math.pow(A.Venus, -1.5),
    Mars: 2 * Math.PI * Math.pow(A.Mars, -1.5),
  };
  const cand = ['Mercury', 'Venus', 'Mars'];
  const tally = { Mercury: 0, Venus: 0, Mars: 0 };
  let n = 0;
  for (let t = 0; t < years; t += dt) {
    const eE = w.Earth * t;
    const ex = A.Earth * Math.cos(eE), ey = A.Earth * Math.sin(eE);
    let best = null, bestD = Infinity;
    for (const p of cand) {
      const a = w[p] * t;
      const dx = A[p] * Math.cos(a) - ex, dy = A[p] * Math.sin(a) - ey;
      const d = dx * dx + dy * dy;
      if (d < bestD) { bestD = d; best = p; }
    }
    tally[best]++; n++;
  }
  return { Mercury: tally.Mercury / n, Venus: tally.Venus / n, Mars: tally.Mars / n };
}
const fr = nearestFractions(50000, 0.01);
console.log(`     Mercury ${(100 * fr.Mercury).toFixed(1)}%  Venus ${(100 * fr.Venus).toFixed(1)}%  Mars ${(100 * fr.Mars).toFixed(1)}%`);
ok('Mercury is Earth\'s nearest MOST of the time', fr.Mercury > fr.Venus && fr.Venus > fr.Mars,
   `${(100 * fr.Mercury).toFixed(0)} > ${(100 * fr.Venus).toFixed(0)} > ${(100 * fr.Mars).toFixed(0)}`);
ok('fractions sum to 1', approx(fr.Mercury + fr.Venus + fr.Mars, 1, 1e-9));
// the widely-quoted split is ~47/36/17; ours lands in that neighbourhood.
ok('our Mercury share is ~47% (loosely matches quoted 47%)', approx(fr.Mercury, 0.47, 0.05),
   `${(100 * fr.Mercury).toFixed(1)}%`);

// ═══════════════════════════════════════════════════════════════════════════
// 10. THE TWO RANKINGS A READER ACTUALLY SEES
//
// Everything above is an independent re-derivation. It establishes the FACT and
// it never once touches the page, which means it would say exactly the same
// thing if the page printed the three planets in the wrong order, or printed
// every distance ten times too large. The corpus-wide sweep in
// research/verifier-independence/screen.mjs changed the last digit of all 990
// numbers this page renders and this script stayed green through every one.
// So: load the built page and hold the two ranked lists, which are the page's
// whole argument, against the numbers computed above.
// Added 2026-08-12; the measurement is at /strata/the-engine-and-the-eye/.
// ═══════════════════════════════════════════════════════════════════════════
{
  const { readFileSync: rf, existsSync: ex, statSync: st } = await import('node:fs');
  const http = await import('node:http');
  const { join, extname, sep } = await import('node:path');
  const { fileURLToPath } = await import('node:url');
  const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript',
    '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
    '.woff2': 'font/woff2', '.ico': 'image/x-icon' };
  const PUBLIC = fileURLToPath(new URL('../../public', import.meta.url));
  const server = http.createServer((req, res) => {
    let p;
    try { p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); }
    catch { res.writeHead(400); res.end(); return; }
    if (p.endsWith('/')) p += 'index.html';
    const file = join(PUBLIC, p);
    if (!file.startsWith(PUBLIC + sep) || !ex(file) || !st(file).isFile()) { res.writeHead(404); res.end(); return; }
    res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
    res.end(rf(file));
  });
  await new Promise((r) => server.listen(0, '127.0.0.1', r));
  const { chromium } = await import('playwright');
  const browser = await chromium.launch({ args: ['--no-sandbox'] });
  try {
    const page = await browser.newPage();
    const jsErrors = [];
    page.on('pageerror', (e) => jsErrors.push(String(e.message).slice(0, 140)));
    await page.goto(`http://127.0.0.1:${server.address().port}/strata/closest-planet-to-earth/`, { waitUntil: 'load' });
    await page.waitForSelector('#rank-time li');
    const readRank = (id) => page.$$eval(`#${id} li`, (els) => els.map((li) => ({
      name: li.querySelector('.nm').textContent.trim(),
      value: li.querySelector('.d').textContent.trim(),
    })));

    /* the page's canonical state is Earth at 1.000 AU, which is what the
       independent numbers above were computed for. */
    const byTime = await readRank('rank-time');
    const byMin = await readRank('rank-min');

    const wantTime = ['Mercury', 'Venus', 'Mars']
      .map((n) => ({ name: n, v: meanDistPCM(1.000, A[n]) })).sort((a, b) => a.v - b.v);
    const wantMin = ['Mercury', 'Venus', 'Mars']
      .map((n) => ({ name: n, v: minSep(1.000, A[n]) })).sort((a, b) => a.v - b.v);

    ok('the time-average list a reader sees is in the order this script computes',
      byTime.map((r) => r.name).join(' < ') === wantTime.map((r) => r.name).join(' < '),
      byTime.map((r) => r.name).join(' < '));
    ok('the closest-approach list a reader sees is in the order this script computes',
      byMin.map((r) => r.name).join(' < ') === wantMin.map((r) => r.name).join(' < '),
      byMin.map((r) => r.name).join(' < '));
    ok('every distance printed in the time-average list is this script\'s own, to 3 dp',
      byTime.every((r, i) => r.value === wantTime[i].v.toFixed(3) + ' AU'),
      byTime.map((r) => r.value).join(' / '));
    ok('every distance printed in the closest-approach list is this script\'s own, to 3 dp',
      byMin.every((r, i) => r.value === wantMin[i].v.toFixed(3) + ' AU'),
      byMin.map((r) => r.value).join(' / '));
    ok('the two lists a reader sees really do disagree about the winner',
      byTime[0].name !== byMin[0].name, `${byTime[0].name} vs ${byMin[0].name}`);
    ok('no JavaScript error while the page built its lists', jsErrors.length === 0,
      jsErrors[0] || 'none');
  } finally {
    await browser.close();
    server.close();
  }
}

// ═══════════════════════════════════════════════════════════════════════════
const total = pass + fail;
console.log(`\n${pass}/${total} checks passed`);
if (fail) console.log(`${fail} CHECK(S) FAILED`);
process.exit(fail === 0 ? 0 : 1);
