#!/usr/bin/env node
// Olbers' paradox — the computed core, checked offline.
//
// The page ("The Sky Should Be on Fire") makes three quantitative claims. Each is
// recomputed here from explicitly cited inputs, so a reader can run `node verify.mjs`
// and watch every number on the page fall out of the same arithmetic the browser does.
//
// The physics, in one breath: in an infinite, static, eternal universe uniformly
// filled with stars, every line of sight eventually ends on a stellar surface, so the
// whole sky would blaze at the surface brightness of a star. It doesn't. Why not is the
// paradox. The answer is NOT "space is mostly empty" (that's refuted by the equal-shell
// identity below) and is only secondarily "redshift" (Harrison): the dominant reason is
// that the universe is far too YOUNG for sight-lines to have filled in — the mean free
// path to a stellar surface is ~10^23-10^24 ly, ~10^13-10^14 times the distance light has
// had time to travel.  We compute that ratio.
//
// Run: node research/olbers-paradox/verify.mjs
'use strict';

let pass = 0, fail = 0;
const results = [];
function check(name, got, want, tol, unit = '') {
  ok = Math.abs(got - want) <= tol * Math.abs(want);
  results.push([ok, name, `got ${fmt(got)}${unit}`, `want ≈ ${fmt(want)}${unit}`]);
  ok ? pass++ : fail++;
  return got;
}
let ok;
function inRange(name, got, lo, hi, unit = '') {
  // order-of-magnitude claim: assert the value lands inside a stated decade bracket.
  const good = got >= lo && got <= hi;
  results.push([good, name, `got ${fmt(got)}${unit}`, `want in [${fmt(lo)}, ${fmt(hi)}]${unit}`]);
  good ? pass++ : fail++;
  return got;
}
function assert(name, cond) {
  results.push([!!cond, name, cond ? 'holds' : 'FAILS', '']);
  cond ? pass++ : fail++;
}
function fmt(x) {
  if (x === 0) return '0';
  const e = Math.floor(Math.log10(Math.abs(x)));
  if (e >= 6 || e <= -4) return (x / 10 ** e).toFixed(3) + 'e' + e;
  return (+x.toPrecision(5)).toString();
}

// ----------------------------------------------------------------------------
// CITED INPUTS  (all order-of-magnitude robust; sources in the page's footer)
// ----------------------------------------------------------------------------
const M_SUN  = 1.989e30;       // kg            (IAU)
const R_SUN  = 6.957e8;        // m             (IAU nominal solar radius)
const MPC_M  = 3.0857e22;      // m per megaparsec
const LY_M   = 9.4607e15;      // m per light year
const C       = 2.998e8;       // m/s
const GYR_S   = 3.156e16;      // s per gigayear

// Cosmic stellar content (local universe):
//   Omega_stars ≈ 0.0027  (Fukugita & Peebles 2004; Cole et al. 2001 give ~0.0024)
//   rho_crit    ≈ 1.36e11 M_sun / Mpc^3  (for H0 = 70 km/s/Mpc)
// => stellar mass density rho_star ≈ 3.7e8 M_sun / Mpc^3.
const OMEGA_STARS = 0.0027;
const RHO_CRIT    = 1.36e11;                       // M_sun / Mpc^3
const RHO_STAR    = OMEGA_STARS * RHO_CRIT;        // M_sun / Mpc^3  (~3.7e8)

// Mean stellar mass, IMF-weighted: most stars are M dwarfs. ~0.4 M_sun is standard.
const MEAN_STAR_MASS = 0.4;                         // M_sun
// Mean stellar radius: M-dwarf-dominated samples sit BELOW R_sun, but using the full
// solar radius is the *conservative* choice — a bigger disk blocks sight-lines sooner,
// shortening the mean free path and making the paradox HARDER to resolve. If the sky is
// dark even under this generous assumption, it is dark a fortiori for smaller stars.
const MEAN_STAR_RADIUS_M = R_SUN;                  // m  (upper bound -> conservative)

// Age / light-horizon of the universe:
const AGE_GYR  = 13.8;                              // Gyr (Planck 2018)
const HUBBLE_LIGHT_TRAVEL_LY = C * (AGE_GYR * GYR_S) / LY_M;  // ~1.38e10 ly

console.log('Olbers’ paradox — the computed core\n' + '='.repeat(60));

// ----------------------------------------------------------------------------
// CLAIM 1 — THE EQUAL-SHELL IDENTITY (refutes "stars are too far / space is empty")
//   A spherical shell at radius r, thickness dr, holds dN = n * 4*pi*r^2 * dr stars.
//   Each delivers flux f = L / (4*pi*r^2).  Shell flux = dN * f = n * L * dr.
//   => INDEPENDENT of r. Every equal-thickness shell contributes the SAME brightness;
//      the 1/r^2 dimming is exactly cancelled by the r^2 growth in star count.
// We verify numerically across many radii that shell flux is constant.
// ----------------------------------------------------------------------------
{
  const n = 1, L = 1;                // arbitrary units; we test r-independence only
  const dr = 1;
  const shellFlux = (r) => (n * 4 * Math.PI * r * r * dr) * (L / (4 * Math.PI * r * r));
  const samples = [1, 10, 100, 1e4, 1e7, 1e12].map(shellFlux);
  const allEqual = samples.every(v => Math.abs(v - samples[0]) < 1e-9 * samples[0]);
  assert('equal-shell: shell flux is independent of distance r (n*L*dr at every radius)', allEqual);
  console.log(`  shell flux at r = 1, 10, 100, 1e4, 1e7, 1e12  ->  ${samples.map(v => v.toFixed(4)).join(', ')}`);
  console.log('  => farness dims each star as 1/r^2 but multiplies their number as r^2: exact cancel.\n');
}

// ----------------------------------------------------------------------------
// CLAIM 2 — MEAN FREE PATH to a stellar surface, lambda = 1 / (n * sigma)
//   n     = stellar number density = rho_star / mean_star_mass
//   sigma = geometric cross-section of one star = pi * R^2
//   lambda = the distance at which, on average, every sight-line has struck one star
//            (i.e. the depth at which the sky "fills in" to full stellar brightness).
//   Independent target: Harrison, Darkness at Night (1987), gives ~10^23 ly.
// ----------------------------------------------------------------------------
let lambda_ly;
{
  const n_per_Mpc3 = RHO_STAR / MEAN_STAR_MASS;          // stars / Mpc^3
  const n_per_m3   = n_per_Mpc3 / (MPC_M ** 3);          // stars / m^3
  const sigma_m2   = Math.PI * MEAN_STAR_RADIUS_M ** 2;  // m^2
  const lambda_m   = 1 / (n_per_m3 * sigma_m2);          // m
  lambda_ly        = lambda_m / LY_M;                    // light years
  console.log(`CLAIM 2 — mean free path to a stellar surface`);
  console.log(`  stellar number density n = ${fmt(n_per_Mpc3)} stars/Mpc^3 = ${fmt(n_per_m3)} /m^3`);
  console.log(`  cross-section sigma = pi R_sun^2 = ${fmt(sigma_m2)} m^2`);
  console.log(`  lambda = 1/(n sigma) = ${fmt(lambda_m)} m = ${fmt(lambda_ly)} ly`);
  // Computed ~2e24 ly from the inputs above; Harrison's independent estimate is ~1e23 ly.
  // The spread is honest: it is entirely set by what you call "a typical star." Both land
  // in the same window, and BOTH are astronomically larger than the light horizon.
  inRange('mean free path lambda is of order 10^23–10^24 ly (Harrison ~1e23)', lambda_ly, 1e22, 1e25, ' ly');
  console.log('');
}

// ----------------------------------------------------------------------------
// CLAIM 3 — THE AGE RATIO: how many times too young is the universe?
//   The sky reaches full stellar-surface brightness only at depth ~ lambda.
//   Light has only had time to travel ~ c * age ~ 1.4e10 ly.
//   ratio = lambda / (light-travel distance) ~ 10^13-10^14.  THIS is why the sky is dark:
//   not emptiness, but a horizon ~10^13-10^14x too close for sight-lines to fill in.
// ----------------------------------------------------------------------------
let ratio;
{
  ratio = lambda_ly / HUBBLE_LIGHT_TRAVEL_LY;
  console.log(`CLAIM 3 — the age ratio`);
  console.log(`  light-travel distance in ${AGE_GYR} Gyr = ${fmt(HUBBLE_LIGHT_TRAVEL_LY)} ly`);
  console.log(`  ratio lambda / (c*age) = ${fmt(ratio)}`);
  inRange('universe is ~10^13–10^14 times too young for sight-lines to fill the sky', ratio, 1e12, 1e15);
  console.log('');
}

// ----------------------------------------------------------------------------
// CLAIM 4 — SKY COVERAGE LAW (the instrument's engine)
//   The probability a random line of sight is still UNobstructed at depth r is
//   Poisson: P_open(r) = exp(-r/lambda).  Covered fraction C(r) = 1 - exp(-r/lambda).
//   At r = lambda the sky is ~63% covered; at r << lambda it is ~r/lambda (sparse points).
//   Plug the actual horizon r = c*age ~ 1e-13 lambda  ->  coverage ~ 1e-13 = night.
// ----------------------------------------------------------------------------
{
  const cover = (rOverLambda) => 1 - Math.exp(-rOverLambda);
  check('coverage at r = lambda is 1 - 1/e', cover(1), 1 - 1 / Math.E, 1e-9);
  check('coverage at r = 3*lambda', cover(3), 1 - Math.exp(-3), 1e-9);
  const rHorizon = HUBBLE_LIGHT_TRAVEL_LY / lambda_ly;   // r/lambda at the real horizon
  const coverNow = cover(rHorizon);
  console.log(`CLAIM 4 — sky coverage at the real horizon`);
  console.log(`  r_horizon / lambda = ${fmt(rHorizon)}  =>  covered fraction = ${fmt(coverNow)}`);
  // for tiny x, 1-exp(-x) ~ x, so coverage ~ 1/ratio ~ 6e-15 (~10^-14)
  check('covered fraction of the night sky ~ 1/ratio (~6e-15, i.e. ~10^-14)', coverNow, 1 / ratio, 0.01);
  assert('coverage rises monotonically and saturates below 1 (never overcounts)',
         cover(0.5) < cover(1) && cover(1) < cover(10) && cover(30) > 0.999999 && cover(30) < 1);
  console.log('  => the daytime-bright sky needs depth ~lambda; we see ~10^-14 of it: a sprinkle of points.\n');
}

// ----------------------------------------------------------------------------
// SUMMARY
// ----------------------------------------------------------------------------
console.log('-'.repeat(60));
for (const [ok, name, got, want] of results) {
  console.log(`  ${ok ? '✓' : '✗'} ${name}`);
  if (!ok) console.log(`      ${got}   ${want}`);
}
console.log('-'.repeat(60));
console.log(`${pass}/${pass + fail} checks pass${fail ? `  (${fail} FAILED)` : ''}`);
process.exit(fail ? 1 : 0);
