#!/usr/bin/env node
// The Sphere of You — offline verifier.
//
// A deposition (archived in deposition-as-received.txt) proposed a page built on
// three real pieces of physics:
//   (1) the future light cone of your birth event is a sphere of radius c*t,
//       i.e. your age in light-years, growing forever at the speed of light;
//   (2) the number of stars inside it follows from the local stellar density;
//   (3) the universe has a *cosmic event horizon* — a finite comoving radius
//       beyond which no signal sent now can ever arrive — so most of the
//       observable universe is permanently beyond reach.
//
// Nothing here is trusted from the deposition. Every number is recomputed from
// published constants, and the deposition's own figures are CHECKED against the
// recomputation — two of them were wrong (see CORRECTIONS at the bottom) and the
// page carries the corrected values. The page must reproduce these live.
//
// Run: node research/sphere-of-you/verify.mjs

// ---------- exact / definitional constants ----------
const C_KM_S   = 299792.458;            // speed of light, km/s (exact, SI definition)
const JULIAN_YR_S = 365.25 * 86400;     // Julian year, seconds (the ly definition year)
const LY_KM    = C_KM_S * JULIAN_YR_S;  // one light-year in km (IAU)
const PC_LY    = 3.2615637771;          // one parsec in light-years (from the AU/arcsec definition)

// ---------- published empirical constants (sourced on the page) ----------
// Local stellar number density. The robust, directly-countable anchor is the
// peer-reviewed 10-parsec census in the Gaia era: Reylé, Jardine, Fouqué, Caballero,
// Smart & Sozzetti (2021), "The 10 parsec sample in the Gaia era", A&A 650, A201,
// compiled independently of RECONS (recons.org), whose count it cites. We carry the count and DERIVE the density,
// rather than quoting a round number, so the arithmetic is auditable.
//   Reylé 2021: 540 objects in 339 systems within 10 pc, of which 375 STARS
//   (incl. 20 white dwarfs + 1 candidate), 85 brown dwarfs (+3 candidates), 77 confirmed planets.
const RECONS_R_PC      = 10;            // census radius, parsecs
const RECONS_SYSTEMS   = 339;           // stellar+substellar systems within 10 pc (Reyle 2021)
const RECONS_STARS     = 375;           // STARS only (excl. brown dwarfs & planets) within 10 pc (Reyle 2021)
// Canonical textbook neighbourhood density, for cross-check (per CUBIC PARSEC).
// The classic "true density" 0.14/pc^3 (Agekjan-Ogorodnikov, binary/IMF-corrected);
// a modern raw 8-pc count (Kirkpatrick/Mamajek) gives ~0.10/pc^3. Range ~0.10-0.14.
const RHO_PC3_CANON    = 0.14;          // ~0.14 stars / pc^3  (solar-neighbourhood standard)

// Cosmology (flat LCDM; Davis & Lineweaver 2004, "Expanding Confusion", PASA 21:97;
// horizons cross-checked against Ord 2021 "The Edges of Our Universe", arXiv:2104.01191).
const PARTICLE_HORIZON_GLY = 46.5;      // comoving radius of the observable universe (D&L; Ord 46.4)
const EVENT_HORIZON_GLY    = 16.0;      // comoving cosmic event horizon, today (Wikipedia; Ord 16.5)
// Corrected 2026-09-27: this was EVENT_HORIZON_MAX_GLY = 17.6, "asymptotic future reach", and the
// check below asserted the event horizon GROWS toward it. In comoving distance the event horizon
// shrinks toward zero (Davis & Lineweaver 2004; Ord 2021); ~17 Gly is its asymptotic PROPER
// distance, c/H_Lambda = (c/H0)/sqrt(Omega_Lambda). Computed here for the D&L model.
const OMEGA_L = 0.7, HUBBLE_GLY_H70 = 299792.458 / 70 * 3.26156e-3;   // c/H0 in Gly at H0=70 (13.97)
const EVENT_HORIZON_PROPER_ASYM_GLY = HUBBLE_GLY_H70 / Math.sqrt(OMEGA_L); // ~16.7 Gly, proper
const GALAXY_REACHABLE_PCT = 5;         // ~% of currently-observable galaxies ever reachable (Ord 2021: 17.5e9/400e9 = 4.4%)

// Milky Way stellar-disk diameter (the figure the page compares the sphere to).
const MW_DISK_LY = 100000;              // ~100,000 ly (classic value; range named on page)

// ---------- helpers ----------
const sphereVol = (r) => (4/3) * Math.PI * r*r*r;     // volume of a sphere, radius r (any unit -> unit^3)
let pass = 0, fail = 0;
const approx = (a, b, tol, msg) => {
  const ok = Math.abs(a - b) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}   got ${typeof a === 'number' ? a.toPrecision(6) : a}  expect ${b}±${tol}`);
  ok ? pass++ : fail++;
};
const assert = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'}  ${msg}`); cond ? pass++ : fail++; };

console.log('=== (1) the future light cone: radius = age in light-years ===');
// One light-year is, by definition, the distance light travels in one year, so
// the radius of a future light cone after t years is exactly t light-years.
// Confirm numerically: c (in ly/yr) is 1 to machine precision.
const c_ly_per_yr = (C_KM_S * JULIAN_YR_S) / LY_KM;
approx(c_ly_per_yr, 1, 1e-12, 'c expressed in light-years per year is exactly 1');
// So an age in years equals a radius in light-years. Spot-check a 40-year-old.
const ageDemo = 40;
approx(ageDemo /* ly radius */, 40, 1e-9, 'a 40-year-old: sphere radius = 40 light-years (radius = age)');
// The cosmological (Hubble) correction over a human lifetime is negligible:
const H0_km_s_Mpc = 70, MPC_KM = 3.0857e19;
const H0_per_s = H0_km_s_Mpc / MPC_KM;
const r100_km = 100 * LY_KM;                          // 100 ly in km
const fracCorr = (r100_km / (C_KM_S)) * H0_per_s;     // r*H0/c, dimensionless
assert(fracCorr < 1e-7, `Hubble correction to "radius = age" over 100 ly is ~${fracCorr.toExponential(2)} (negligible)`);

console.log('\n=== (2) local stellar density, from the RECONS 10-pc census ===');
const volPc3 = sphereVol(RECONS_R_PC);                       // pc^3
const rho_pc3 = RECONS_STARS / volPc3;                       // stars / pc^3
const r_pc_in_ly = RECONS_R_PC * PC_LY;                      // 10 pc in ly
const volLy3 = sphereVol(r_pc_in_ly);                        // ly^3
const rho_ly3 = RECONS_STARS / volLy3;                       // stars / ly^3
console.log(`  10 pc = ${r_pc_in_ly.toFixed(2)} ly;  volume = ${volPc3.toFixed(0)} pc^3 = ${volLy3.toExponential(3)} ly^3`);
console.log(`  RECONS-derived density: ${rho_pc3.toFixed(4)} stars/pc^3  =  ${rho_ly3.toExponential(3)} stars/ly^3`);
// The unit-conversion identity the deposition got wrong: pc^3 -> ly^3 divides by PC_LY^3 (~34.7).
approx(rho_pc3 / (PC_LY**3), rho_ly3, 1e-9, 'density/pc^3 -> density/ly^3 divides by (pc/ly)^3 = ' + (PC_LY**3).toFixed(2));
// Canonical 0.14 stars/pc^3, converted, is ~0.004 stars/ly^3 — NOT 0.14/ly^3.
const rhoCanon_ly3 = RHO_PC3_CANON / (PC_LY**3);
approx(rhoCanon_ly3, 0.00403, 0.0002, '0.14 stars/pc^3  =  ~0.004 stars/ly^3 (the deposition wrote 0.14/ly^3 — 35x too high)');
assert(rho_ly3 < 0.01, 'every honest local density is a few thousandths of a star per ly^3, never 0.14/ly^3');

console.log('\n=== (2b) star counts in a personal sphere (order of magnitude, lower bound) ===');
// Use the RECONS-derived density (a *known-stars* density, hence a lower bound:
// faint dwarfs are still being found). Counts are presented as approximate.
const starsIn = (r_ly) => rho_ly3 * sphereVol(r_ly);
for (const r of [20, 40, 50, 90]) {
  console.log(`  within ${r} ly:  ~${Math.round(starsIn(r))} stars   (sphere volume ${sphereVol(r).toExponential(2)} ly^3)`);
}
assert(starsIn(50) > 100 && starsIn(50) < 5000, 'within 50 ly: hundreds-to-low-thousands of stars (order of magnitude)');

console.log('\n=== (3) the cosmic event horizon and what is permanently beyond reach ===');
assert(EVENT_HORIZON_GLY < PARTICLE_HORIZON_GLY, 'the event horizon (what we can ever REACH) is smaller than the particle horizon (what we can SEE)');
const volFracReach = (EVENT_HORIZON_GLY / PARTICLE_HORIZON_GLY) ** 3;
approx(volFracReach * 100, 4.07, 0.6, 'reachable fraction by comoving VOLUME = (Re/Rp)^3 ≈ 4%');
approx((1 - volFracReach) * 100, 95.9, 0.6, '... so ~96% of the observable universe by volume is beyond the event horizon');
approx(HUBBLE_GLY_H70, 13.97, 0.05, 'Hubble sphere c/H0 at H0=70 is ~14.0 Gly (14.4 Gly is the Planck-H0 value Ord uses)');
approx(EVENT_HORIZON_PROPER_ASYM_GLY, 16.7, 0.1, 'the event horizon tends to a PROPER distance c/H_Lambda (~17 Gly); in COMOVING distance it only shrinks, so it is never cubed against the comoving particle horizon');
// The galaxy-NUMBER reachable fraction is a *different* calculation (~5%, Ord 2021),
// not equal to the volume fraction — the page must not conflate them. (The popular
// "~3%" figure mistakenly uses the Hubble sphere, not the event horizon; avoided.)
assert(GALAXY_REACHABLE_PCT > 0 && GALAXY_REACHABLE_PCT < 10,
  `the galaxy-count reachable fraction (~${GALAXY_REACHABLE_PCT}%, Ord 2021) is its own figure, distinct from the ~4% by volume`);
// Ord's cross-check identity: affectable (16.5) + observable (46.4) = future-visibility limit.
approx(16.5 + 46.4, 62.9, 0.2, 'cross-check: affectable 16.5 + observable 46.4 = 62.9 Gly (the eventually-observable limit, Ord 2021)');

console.log('\n=== sphere vs the Milky Way disk ===');
const ratioDemo = (2 * ageDemo) / MW_DISK_LY;            // diameter ratio for the 40-yr demo
approx(ratioDemo * 100, 0.08, 0.001, 'a 40-year-old sphere spans ~0.08% of the Milky Way disk diameter (a near-invisible dot)');

console.log('\n=== CORRECTIONS the gate made to the deposition (see facts.md) ===');
console.log('  • "0.14 stars/ly^3"  ->  0.14 stars/PC^3 = ~0.004 stars/ly^3 (unit error, 35x).');
console.log('  • "360 systems within 83 ly"  ->  ~375 STARS sit within 10 pc = 32.6 ly (Reyle 2021), not 83 ly; and within 83 ly');
console.log('     (25 pc) the count is ~2000+ systems, not 360 (RECONS 25pc db). Both radius and label were off.');
console.log('  • "130 systems within 50 ly"  ->  that is the NAKED-EYE count (133 stars, mag<6.5); the true count');
console.log('     within 50 ly is ~1400 systems / ~2000 stars (Durham/Atlas of the Universe).');
console.log('  (Corrected 2026-09-27: a fourth line here charged the deposition with "~3% reachable (Loeb)". The');
console.log('   deposition says ~4% by volume and never names Loeb; that line is withdrawn. The page keeps Ord 2021\'s');
console.log('   separate ~5% by galaxy count and Loeb 2002\'s z>~1.8 cutoff.)');

console.log(`\n${fail === 0 ? 'ALL CHECKS PASS' : 'SOME CHECKS FAILED'} — ${pass} pass, ${fail} fail`);
process.exit(fail === 0 ? 0 : 1);
