#!/usr/bin/env node
// verify-astro.mjs — check the geometry this layer's claims rest on.
//
// Five things get checked, in the order they are relied on:
//
//   1. The Sun, against JPL Horizons. lib/astro.mjs uses a low-precision analytic series.
//      Its error is not quoted here, it is measured: 11,688 airless topocentric solar
//      altitudes fetched from JPL for eight sites across a year (data/horizons-sun.json).
//   2. The closed form h = R(sec D - 1), against a numerical root-find that knows nothing
//      about the algebra and simply asks a shadow model where the boundary is.
//   3. The parallax the closed form ignores: the same root-find with the Sun at one AU
//      rather than infinitely far away.
//   4. The cone the closed form ignores: umbra and penumbra heights against the cylinder.
//   5. The critical-latitude formula, against a year-long scan of the full ephemeris.
//
// Run:  node research/the-dark-has-a-ceiling/verify-astro.mjs

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import {
  R_EARTH_KM, R_SUN_KM, AU_KM,
  shadowHeight, depressionForHeight, criticalLatitude, criticalLatitudeSouth, midnightDepression,
  sunVector, solarAltitude, jdFromUnixMs,
  illumination, illuminationCylindrical,
} from './lib/astro.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
let checks = 0, failures = 0;
const f = (x, n = 4) => Number(x).toFixed(n);
function ok(cond, label, detail = '') {
  checks++;
  console.log(`  ${cond ? 'ok  ' : 'FAIL'} ${label}${detail ? '  ' + detail : ''}`);
  if (!cond) failures++;
}

// ===========================================================================
console.log('\n=== 1. the Sun, against JPL Horizons ===');
const HZ = join(HERE, 'data', 'horizons-sun.json');
if (!existsSync(HZ)) {
  console.log('  data/horizons-sun.json missing; run: node tools/fetch-horizons.mjs');
  failures++;
} else {
  const hz = JSON.parse(readFileSync(HZ, 'utf8'));
  let worst = 0, worstWhere = '', n = 0;
  let worstNight = 0, worstNightWhere = '', nNight = 0;
  for (const site of hz.sites) {
    for (const row of site.rows) {
      // "2026-Sep-13 00:00" -> UTC
      const m = row.t.match(/^(\d{4})-(\w{3})-(\d{2}) (\d{2}):(\d{2})$/);
      if (!m) continue;
      const MON = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
      const ms = Date.UTC(+m[1], MON[m[2]], +m[3], +m[4], +m[5], 0);
      const mine = solarAltitude(site.lat, site.lon, jdFromUnixMs(ms));
      const d = Math.abs(mine - row.el);
      n++;
      if (d > worst) { worst = d; worstWhere = `${site.name} ${row.t} (JPL ${f(row.el, 5)}, ours ${f(mine, 5)})`; }
      // The regime the claims actually live in: the Sun below the horizon.
      if (row.el < 0 && row.el > -40) {
        nNight++;
        if (d > worstNight) { worstNight = d; worstNightWhere = `${site.name} ${row.t}`; }
      }
    }
  }
  ok(n > 10000, 'JPL solar altitudes compared', `${n.toLocaleString('en-US')} rows, 8 sites, a full year`);
  ok(worst < 0.02, 'our Sun agrees with JPL everywhere',
     `worst |d alt| = ${f(worst, 5)} deg  [${worstWhere}]`);
  ok(worstNight < 0.02, 'and in the twilight band the claims live in',
     `worst |d alt| = ${f(worstNight, 5)} deg over ${nNight.toLocaleString('en-US')} rows below the horizon  [${worstNightWhere}]`);
}

// ===========================================================================
console.log('\n=== 2. the closed form, against a root-find that does not know it ===');

// Build a geometry with the Sun along +x at distance d, an observer on the unit sphere
// at angle theta from +x, and ask a shadow model where the lit/unlit boundary is over
// that observer's head. Nothing below uses shadowHeight().
function geometryFor(depressionDeg, d) {
  const sun = { x: d, y: 0, z: 0 };
  // find theta such that the TOPOCENTRIC solar depression equals depressionDeg
  const depAt = (theta) => {
    const o = { x: Math.cos(theta), y: Math.sin(theta), z: 0 };
    const O = { x: R_EARTH_KM * o.x, y: R_EARTH_KM * o.y, z: 0 };
    const sx = sun.x - O.x, sy = sun.y - O.y, sz = sun.z - O.z;
    const sm = Math.hypot(sx, sy, sz);
    const elev = Math.asin((sx * o.x + sy * o.y + sz * o.z) / sm) * (180 / Math.PI);
    return -elev;
  };
  let lo = Math.PI / 2, hi = Math.PI; // depression 0 .. 90
  for (let i = 0; i < 200; i++) {
    const mid = (lo + hi) / 2;
    if (depAt(mid) < depressionDeg) lo = mid; else hi = mid;
  }
  const theta = (lo + hi) / 2;
  const o = { x: Math.cos(theta), y: Math.sin(theta), z: 0 };
  return { sun, o, achievedDepression: depAt(theta) };
}

// Root-find the height at which `model` stops calling the overhead point shadowed.
function boundaryHeight(model, sun, o, state) {
  const at = (h) => model({ x: (R_EARTH_KM + h) * o.x, y: (R_EARTH_KM + h) * o.y, z: (R_EARTH_KM + h) * o.z }, sun);
  let lo = 0, hi = 200000;
  if (at(lo) !== state) return null;       // not shadowed even at the ground
  if (at(hi) === state) return Infinity;   // still shadowed at 200,000 km
  for (let i = 0; i < 200; i++) {
    const mid = (lo + hi) / 2;
    if (at(mid) === state) lo = mid; else hi = mid;
  }
  return (lo + hi) / 2;
}

const FAR = AU_KM * 1e6; // effectively infinite: isolates the algebra from parallax
let worstAlgebra = 0, worstAlgebraWhere = '';
for (const D of [1, 3, 6, 9, 12, 15, 18, 20.3, 23.05, 30, 45, 60]) {
  const { sun, o } = geometryFor(D, FAR);
  const numeric = boundaryHeight(illuminationCylindrical, sun, o, 'umbra');
  const closed = shadowHeight(D);
  const rel = Math.abs(numeric - closed) / Math.max(1, closed);
  if (rel > worstAlgebra) { worstAlgebra = rel; worstAlgebraWhere = `D=${D} deg (closed ${f(closed, 3)} km, numeric ${f(numeric, 3)} km)`; }
}
// 1e-7 of a kilometre is a tenth of a millimetre. The residual is the bisection's own
// floating-point floor, not a disagreement: a tighter bound than this would be testing
// the arithmetic of the test.
ok(worstAlgebra < 1e-7, 'h = R(sec D - 1) reproduces the numerical boundary',
   `worst relative disagreement ${worstAlgebra.toExponential(2)}  [${worstAlgebraWhere}]`);

// The numbers the layer will print.
console.log('\n  the closed form, tabulated (R = 6371.0088 km, cylinder, no atmosphere):');
for (const D of [6, 12, 18]) {
  console.log(`    Sun ${String(D).padStart(2)} deg down  ->  shadow overhead reaches ${f(shadowHeight(D), 1).padStart(7)} km`);
}
for (const [label, h] of [['ISS', 420], ['Starlink shell', 550], ['OneWeb shell', 1200]]) {
  console.log(`    ${label.padEnd(14)} at ${String(h).padStart(4)} km  ->  overhead, enters shadow at D = ${f(depressionForHeight(h), 2)} deg`);
}

// ===========================================================================
console.log('\n=== 3. the parallax the closed form ignores ===');
let worstParallax = 0, worstParallaxWhere = '';
for (const D of [6, 12, 18, 20.3, 23.05, 30]) {
  const { sun, o } = geometryFor(D, AU_KM);
  const numeric = boundaryHeight(illuminationCylindrical, sun, o, 'umbra');
  const closed = shadowHeight(D);
  const diff = Math.abs(numeric - closed);
  if (diff > worstParallax) { worstParallax = diff; worstParallaxWhere = `D=${D} deg: ${f(closed, 2)} km closed vs ${f(numeric, 2)} km with the Sun at 1 AU`; }
}
ok(worstParallax < 1.0, 'treating the Sun as infinitely distant costs under a kilometre of shadow height',
   `worst ${f(worstParallax, 3)} km  [${worstParallaxWhere}]`);

// ===========================================================================
console.log('\n=== 4. the cone the closed form ignores ===');
const coneRows = [];
for (const D of [6, 12, 18, 20.3, 23.05]) {
  const { sun, o } = geometryFor(D, AU_KM);
  const hCyl = shadowHeight(D);
  const hUmb = boundaryHeight(illumination, sun, o, 'umbra');
  const hPen = boundaryHeight((p, s) => (illumination(p, s) === 'sunlit' ? 'sunlit' : 'shadowed'), sun, o, 'shadowed');
  coneRows.push({ D, hCyl, hUmb, hPen });
  console.log(`    D = ${String(D).padStart(5)} deg:  cylinder ${f(hCyl, 1).padStart(7)} km` +
              `   full umbra ends ${f(hUmb, 1).padStart(7)} km` +
              `   penumbra ends ${f(hPen, 1).padStart(7)} km`);
}
// The umbra cone converges, so full shadow ends LOWER than the cylinder says; the
// penumbra diverges, so partial shadow persists HIGHER.
ok(coneRows.every((r) => r.hUmb < r.hCyl && r.hPen > r.hCyl),
   'the cylinder sits inside the penumbra and outside the umbra, as the cone geometry requires');
const worstCone = Math.max(...coneRows.map((r) => Math.max(Math.abs(r.hUmb - r.hCyl), Math.abs(r.hPen - r.hCyl))));
ok(worstCone < 60, 'and the cylinder is within tens of km of both cone boundaries',
   `worst |difference| = ${f(worstCone, 1)} km`);

// ===========================================================================
console.log('\n=== 5. the critical latitude, against a year-long ephemeris scan ===');
//
// The quantity that decides it is NOT how deep the Sun ever gets: it is how SHALLOW the
// deepest point of the night ever is. A shell overhead escapes the shadow on a given
// night when that night's deepest Sun fails to reach D_h, and it escapes on SOME night
// of the year when the shallowest such night (the summer solstice) fails to reach it.
//
// So: for each noon-to-noon window, take the deepest the Sun gets in it (that is local
// midnight); then take the MINIMUM of those over the year. Nothing here assumes the
// answer falls on the solstice, which is the point of scanning rather than asserting.
function shallowestMidnightOfYear(latDeg, year = 2026) {
  let shallowest = Infinity;
  const dayMs = 86400000;
  const yearStart = Date.UTC(year, 0, 1);
  const nDays = Date.UTC(year + 1, 0, 1) === yearStart ? 365 : Math.round((Date.UTC(year + 1, 0, 1) - yearStart) / dayMs);
  for (let d = 0; d < nDays; d++) {
    // noon to noon, so exactly one local midnight sits inside (observer on lon 0)
    const t0 = yearStart + d * dayMs + dayMs / 2;
    let deepest = -Infinity;
    for (let ms = t0; ms <= t0 + dayMs; ms += 10 * 60 * 1000) {
      const dep = -solarAltitude(latDeg, 0, jdFromUnixMs(ms));
      if (dep > deepest) deepest = dep;
    }
    if (deepest < shallowest) shallowest = deepest;
  }
  return shallowest;
}

const SHELL_KM = 550;
const D550 = depressionForHeight(SHELL_KM);

// The maximum solar declination the year actually reaches, measured rather than assumed
// to equal the obliquity.
let decMax = -Infinity, decMaxWhen = '';
let decMin = Infinity, decMinWhen = '';
for (let ms = Date.UTC(2026, 0, 1); ms < Date.UTC(2027, 0, 1); ms += 3600000) {
  const s = sunVector(jdFromUnixMs(ms));
  if (s.decDeg > decMax) { decMax = s.decDeg; decMaxWhen = new Date(ms).toISOString().slice(0, 13); }
  if (s.decDeg < decMin) { decMin = s.decDeg; decMinWhen = new Date(ms).toISOString().slice(0, 13); }
}
const latCrit = criticalLatitude(SHELL_KM, decMax);
console.log(`    ${SHELL_KM} km shell enters shadow overhead at D = ${f(D550, 3)} deg`);
console.log(`    measured maximum solar declination in 2026: ${f(decMax, 4)} deg  (at ${decMaxWhen}Z)`);
console.log(`    measured minimum:                              ${f(decMin, 4)} deg  (at ${decMinWhen}Z)`);
console.log(`    closed form: critical latitude  ->  ${f(latCrit, 3)} deg`);

const below = shallowestMidnightOfYear(latCrit - 1.0);
const above = shallowestMidnightOfYear(latCrit + 1.0);
console.log(`    scan at ${f(latCrit - 1.0, 2)} deg N: shallowest midnight of the year ${f(below, 3)} deg  (needs > ${f(D550, 3)})`);
console.log(`    scan at ${f(latCrit + 1.0, 2)} deg N: shallowest midnight of the year ${f(above, 3)} deg  (needs < ${f(D550, 3)})`);
ok(below > D550 && above < D550, 'the scan brackets the closed-form critical latitude');

// Locate the crossing by bisection on the scan itself, then compare.
let lo = latCrit - 3, hi = latCrit + 3;
for (let i = 0; i < 16; i++) {
  const mid = (lo + hi) / 2;
  if (shallowestMidnightOfYear(mid) > D550) lo = mid; else hi = mid;
}
const latScan = (lo + hi) / 2;
ok(Math.abs(latScan - latCrit) < 0.05, 'the scanned crossing matches the closed form',
   `scan ${f(latScan, 3)} deg vs closed form ${f(latCrit, 3)} deg  (difference ${f(Math.abs(latScan - latCrit) * 111, 2)} km on the ground)`);

// The southern mirror, scanned the same way. It is not the negative of the northern
// answer on the same DAY, so it has to be scanned against the December solstice.
const latCritS = criticalLatitudeSouth(SHELL_KM, decMin);
const belowS = shallowestMidnightOfYear(latCritS + 1.0);  // equatorward
const aboveS = shallowestMidnightOfYear(latCritS - 1.0);  // poleward
console.log(`    southern closed form  ->  ${f(latCritS, 3)} deg`);
console.log(`    scan at ${f(latCritS + 1.0, 2)} deg: shallowest midnight ${f(belowS, 3)} deg  (needs > ${f(D550, 3)})`);
console.log(`    scan at ${f(latCritS - 1.0, 2)} deg: shallowest midnight ${f(aboveS, 3)} deg  (needs < ${f(D550, 3)})`);
ok(belowS > D550 && aboveS < D550, 'the southern mirror brackets too');

// And the midnight identity itself, which is the one place a sign error hides.
let worstMid = 0, worstMidWhere = '';
for (const lat of [-70, -55, -43.5, -20, 0, 20, 43.5, 55, 70]) {
  for (const doy of [0, 45, 80, 130, 172, 220, 265, 310, 355]) {
    const ms = Date.UTC(2026, 0, 1) + doy * 86400000 + 43200000;
    let deepest = -Infinity, deepestMs = 0;
    for (let t = ms; t <= ms + 86400000; t += 60000) {
      const dep = -solarAltitude(lat, 0, jdFromUnixMs(t));
      if (dep > deepest) { deepest = dep; deepestMs = t; }
    }
    const dec = sunVector(jdFromUnixMs(deepestMs)).decDeg;
    const identity = midnightDepression(lat, dec);
    const d = Math.abs(identity - deepest);
    if (d > worstMid) { worstMid = d; worstMidWhere = `lat ${lat}, doy ${doy}: identity ${f(identity, 3)} vs scan ${f(deepest, 3)}`; }
  }
}
ok(worstMid < 0.25, 'D = 90 - |lat + dec| matches the scanned midnight depression in both hemispheres',
   `worst ${f(worstMid, 3)} deg over 81 latitude-date pairs  [${worstMidWhere}]`);

// The astronomical-twilight latitude, for comparison: the band between them is the
// finding this layer is built on.
const latTwilight = 90 - decMax - 18;
console.log(`\n    astronomical twilight never ends above ${f(latTwilight, 2)} deg`);
console.log(`    the 550 km shell overhead never darkens above ${f(latCrit, 2)} deg`);
ok(latCrit < latTwilight, 'the shell stops darkening at a LOWER latitude than the sky stops darkening',
   `a band of ${f(latTwilight - latCrit, 2)} deg of latitude where the sky goes fully dark and the shell overhead does not`);

// ===========================================================================
console.log('\n=== 6. against tables nobody here wrote ===');
//
// The strongest available check on an implementation is somebody else's published
// numbers. Two independent groups tabulated this quantity, with different Earth radii,
// for different reasons, fourteen years apart. Give our functions THEIR radius and we
// should get THEIR table back, to the digit they printed.
const PUB = JSON.parse(readFileSync(join(HERE, 'data', 'published-values.json'), 'utf8'));

const patat = PUB.sources.find((s) => s.id === 'patat2006');
let worstPatat = 0;
for (const row of patat.rows) {
  const ours = shadowHeight(row.depressionDeg, { R: patat.earthRadiusKm });
  const d = Math.abs(ours - row.shadowHeightKm);
  if (d > worstPatat) worstPatat = d;
  console.log(`    Patat+2006  D = ${String(row.depressionDeg).padStart(2)} deg:  published ${f(row.shadowHeightKm, 1).padStart(6)} km   ours ${f(ours, 1).padStart(6)} km`);
}
ok(worstPatat < 0.05, 'we reproduce Patat, Ugolnikov & Postylyakov (2006) Table A.1',
   `worst difference ${f(worstPatat, 3)} km, against a table printed to 0.1 km`);

const hw = PUB.sources.find((s) => s.id === 'hainaut2020');
let worstHW = 0;
for (const row of hw.rows) {
  const ours = -depressionForHeight(row.altitudeKm, { R: hw.earthRadiusKm });
  const d = Math.abs(ours - row.sunElevationDeg);
  if (d > worstHW) worstHW = d;
}
console.log(`    Hainaut & Williams 2020 Table 1: ${hw.rows.length} altitudes from 340 to 2000 km`);
ok(worstHW < 0.05, 'we reproduce Hainaut & Williams (2020) Table 1, column 3',
   `worst difference ${f(worstHW, 3)} deg, against a table printed to 0.1 deg`);

// And the sentence in Ragazzoni (2020): an 18-degree threshold means a shell at the
// shadow height for 18 degrees. That is the same fact as Patat's table row, arrived at
// from the other direction, so the two published sources must agree with each other.
const ragazzoniImpliedKm = shadowHeight(18, { R: patat.earthRadiusKm });
ok(Math.abs(ragazzoniImpliedKm - patat.rows.find((r) => r.depressionDeg === 18).shadowHeightKm) < 0.05,
   'Ragazzoni (2020) Eq. 5 at 18 deg and Patat (2006) Table A.1 are the same number',
   `${f(ragazzoniImpliedKm, 1)} km`);

// ===========================================================================
console.log('\n=== 7. the runnable check carries the same published values ===');
// verify.mjs writes the two published tables out INLINE, because a check that reads a
// dataset is a check a stranger cannot run from an empty directory. Two copies of a
// number is two chances to be wrong, so the copies are compared here.
const runnable = readFileSync(join(HERE, 'verify.mjs'), 'utf8');
let drift = 0, driftWhere = '';
for (const row of patat.rows) {
  const pat = new RegExp(`\\{\\s*depressionDeg:\\s*${row.depressionDeg}\\s*,\\s*shadowHeightKm:\\s*([0-9.]+)\\s*\\}`);
  const m = runnable.match(pat);
  if (!m || Math.abs(Number(m[1]) - row.shadowHeightKm) > 1e-9) {
    drift++; driftWhere = `Patat D=${row.depressionDeg}: json ${row.shadowHeightKm}, inline ${m ? m[1] : 'absent'}`;
  }
}
for (const row of hw.rows) {
  const pat = new RegExp(`\\{\\s*altitudeKm:\\s*${row.altitudeKm}\\s*,\\s*sunElevationDeg:\\s*(-?[0-9.]+)\\s*\\}`);
  const m = runnable.match(pat);
  if (!m || Math.abs(Number(m[1]) - row.sunElevationDeg) > 1e-9) {
    drift++; driftWhere = `Hainaut h=${row.altitudeKm}: json ${row.sunElevationDeg}, inline ${m ? m[1] : 'absent'}`;
  }
}
ok(drift === 0, 'the inline tables in verify.mjs match data/published-values.json',
   drift === 0 ? `${patat.rows.length + hw.rows.length} values agree` : `${drift} disagree, e.g. ${driftWhere}`);
ok(runnable.includes('PATAT_R_KM = 6380') && runnable.includes('HW_R_KM = 6375'),
   'and it uses each paper\'s own Earth radius, as they state it');

// ===========================================================================
console.log(`\n${checks} checks, ${failures} failed\n`);
process.exit(failures === 0 ? 0 : 1);
