#!/usr/bin/env node
// verify.mjs — the self-contained check for /strata/the-dark-has-a-ceiling/.
//
// This is the one program on that page a stranger can run from an empty directory with
// nothing but Node. It needs no catalogue, no compiler, no network beyond fetching its
// own handful of files, and no part of the private workspace. It re-derives the whole
// geometric spine of the layer and compares it with two tables published by other people.
//
//   curl -L --create-dirs -o research/the-dark-has-a-ceiling/verify.mjs \
//     https://artwaste.land/checks/research/the-dark-has-a-ceiling/verify.mjs
//   node research/the-dark-has-a-ceiling/verify.mjs
//
// The two heavier checks, which are published as source but are not runnable from
// nothing, are verify-astro.mjs (needs the pinned JPL ephemeris) and verify-sgp4-port.mjs
// (needs a C++ compiler and Vallado's own distribution, because its entire job is to
// disagree with a second implementation). This one stands alone.

import {
  R_EARTH_KM, AU_KM,
  shadowHeight, depressionForHeight, criticalLatitude, criticalLatitudeSouth,
  midnightDepression, sunVector, solarAltitude, jdFromUnixMs,
  illumination, illuminationCylindrical,
} from './lib/astro.mjs';

const f = (x, n = 3) => Number(x).toFixed(n);

// ---------------------------------------------------------------------------
// THE PUBLISHED VALUES, INLINE.
//
// These are read out of the papers themselves (the arXiv PDFs), not from a secondary
// source, and they are written here rather than loaded from a JSON file beside this one
// so that this program is a program and nothing else. A check that reads a dataset is a
// check a stranger cannot run from an empty directory, which is the whole point of this
// file; research/source-mirror/ refuses to publish the dataset and is right to.
//
// research/the-dark-has-a-ceiling/data/published-values.json holds the same numbers with
// their full citations, and verify-astro.mjs asserts that the two agree, so this copy
// cannot quietly drift from that one.
// ---------------------------------------------------------------------------

// F. Patat, O. Ugolnikov, O. S. Postylyakov, "UBVRI twilight sky brightness at
// ESO-Paranal", A&A 455, 385 (2006), arXiv:astro-ph/0604128. Table A.1, "Height of lower
// boundary of Earth's shadow". Their stated assumptions: a sphere of radius R_0 = 6380 km,
// refraction neglected, the Sun a point source with parallel rays. Their printed formula
// is h_z = R_0 (1 - cos phi) / cos phi.
const PATAT_R_KM = 6380;
const PATAT_TABLE = [
  { depressionDeg: 6, shadowHeightKm: 35.1 },
  { depressionDeg: 12, shadowHeightKm: 142.5 },
  { depressionDeg: 15, shadowHeightKm: 225.1 },
  { depressionDeg: 18, shadowHeightKm: 328.3 },
];

// O. R. Hainaut, A. P. Williams, A&A 636, A121 (2020), arXiv:2003.01992. Table 1,
// column 3: "the elevation of the Sun for which a satellite at Zenith is just
// illuminated". Their R_Earth = 6375 km; their Eq. 1 is gamma_o = arccos(R/(R+h)).
const HW_R_KM = 6375;
const HW_TABLE = [
  { altitudeKm: 340, sunElevationDeg: -18.3 },
  { altitudeKm: 550, sunElevationDeg: -23.0 },
  { altitudeKm: 590, sunElevationDeg: -23.8 },
  { altitudeKm: 610, sunElevationDeg: -24.1 },
  { altitudeKm: 630, sunElevationDeg: -24.5 },
  { altitudeKm: 780, sunElevationDeg: -27.0 },
  { altitudeKm: 1150, sunElevationDeg: -32.1 },
  { altitudeKm: 1200, sunElevationDeg: -32.7 },
  { altitudeKm: 2000, sunElevationDeg: -40.4 },
];
let checks = 0, failures = 0;
function ok(cond, label, detail = '') {
  checks++;
  console.log(`  ${cond ? 'ok  ' : 'FAIL'} ${label}${detail ? '  ' + detail : ''}`);
  if (!cond) failures++;
}

console.log('\nthe dark has a ceiling: the self-contained check');
console.log('================================================\n');

// ---------------------------------------------------------------------------
console.log('1. the closed form, against two tables nobody here wrote');
let worstP = 0;
for (const row of PATAT_TABLE) {
  const ours = shadowHeight(row.depressionDeg, { R: PATAT_R_KM });
  worstP = Math.max(worstP, Math.abs(ours - row.shadowHeightKm));
  console.log(`     D = ${String(row.depressionDeg).padStart(2)} deg   published ${f(row.shadowHeightKm, 1).padStart(6)} km   here ${f(ours, 1).padStart(6)} km`);
}
ok(worstP < 0.05, 'Patat, Ugolnikov & Postylyakov (2006) Table A.1 reproduced',
   `worst ${f(worstP, 3)} km against a table printed to 0.1 km`);

let worstH = 0;
for (const row of HW_TABLE) {
  const ours = -depressionForHeight(row.altitudeKm, { R: HW_R_KM });
  worstH = Math.max(worstH, Math.abs(ours - row.sunElevationDeg));
}
ok(worstH < 0.05, 'Hainaut & Williams (2020) Table 1 column 3 reproduced',
   `${HW_TABLE.length} altitudes, worst ${f(worstH, 3)} deg against a table printed to 0.1 deg`);

// ---------------------------------------------------------------------------
console.log('\n2. the closed form, against a root-find that does not use it');
// Sun along +x, effectively infinitely far. Observer on the sphere at an angle chosen so
// the topocentric solar depression is D. Ask a shadow model, not the algebra, where the
// boundary over that observer's head is.
function boundaryFor(D, sunDistanceKm = AU_KM * 1e6) {
  // The default puts the Sun effectively infinitely far away, which is the assumption the
  // closed form makes: parallel rays, no cone. Pass the real AU to get the real cone.
  const sun = { x: sunDistanceKm, y: 0, z: 0 };
  const depAt = (th) => {
    const o = { x: Math.cos(th), y: Math.sin(th), 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);
    return -Math.asin((sx * o.x + sy * o.y + sz * o.z) / sm) * (180 / Math.PI);
  };
  let lo = Math.PI / 2, hi = Math.PI;
  for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2; if (depAt(m) < D) lo = m; else hi = m; }
  const th = (lo + hi) / 2, o = { x: Math.cos(th), y: Math.sin(th), z: 0 };
  const at = (h) => illuminationCylindrical({ x: (R_EARTH_KM + h) * o.x, y: (R_EARTH_KM + h) * o.y, z: 0 }, sun);
  let a = 0, b = 200000;
  for (let i = 0; i < 200; i++) { const m = (a + b) / 2; if (at(m) === 'umbra') a = m; else b = m; }
  return { h: (a + b) / 2, sun, o };
}
let worstR = 0, worstRw = '';
for (const D of [1, 3, 6, 9, 12, 15, 18, 20.26, 23, 30, 45]) {
  const num = boundaryFor(D).h, closed = shadowHeight(D);
  const d = Math.abs(num - closed);
  if (d > worstR) { worstR = d; worstRw = `D=${D}: ${f(closed, 4)} vs ${f(num, 4)} km`; }
}
ok(worstR < 1e-6, 'h = R(sec D - 1) reproduces a numerical shadow boundary',
   `worst ${worstR.toExponential(2)} km  [${worstRw}]`);

// ---------------------------------------------------------------------------
console.log('\n3. the cone the closed form leaves out');
for (const D of [18, 23]) {
  const { sun, o } = boundaryFor(D, AU_KM);
  const state = (h) => illumination({ x: (R_EARTH_KM + h) * o.x, y: (R_EARTH_KM + h) * o.y, z: 0 }, sun);
  const find = (want) => {
    let a = 0, b = 200000;
    for (let i = 0; i < 200; i++) { const m = (a + b) / 2; if (want(state(m))) a = m; else b = m; }
    return (a + b) / 2;
  };
  const umb = find((s) => s === 'umbra');
  const pen = find((s) => s !== 'sunlit');
  const cyl = shadowHeight(D);
  console.log(`     D = ${String(D).padStart(2)} deg   umbra ends ${f(umb, 1).padStart(7)} km   cylinder ${f(cyl, 1).padStart(7)} km   penumbra ends ${f(pen, 1).padStart(7)} km`);
  ok(umb < cyl - 1 && cyl + 1 < pen, `at ${D} deg the cylinder lies between the two cone boundaries`,
     `umbra ${f(cyl - umb, 1)} km below it, penumbra ${f(pen - cyl, 1)} km above it`);
}

// ---------------------------------------------------------------------------
console.log('\n4. the midnight identity, in both hemispheres');
let worstM = 0, worstMw = '';
for (const lat of [-60, -43.5, -20, 0, 20, 43.5, 60]) {
  for (const doy of [10, 80, 172, 265, 354]) {
    const ms = Date.UTC(2026, 0, 1) + doy * 86400000 + 43200000;
    let deepest = -Infinity, at = 0;
    for (let t = ms; t <= ms + 86400000; t += 120000) {
      const dep = -solarAltitude(lat, 0, jdFromUnixMs(t));
      if (dep > deepest) { deepest = dep; at = t; }
    }
    const id = midnightDepression(lat, sunVector(jdFromUnixMs(at)).decDeg);
    const d = Math.abs(id - deepest);
    if (d > worstM) { worstM = d; worstMw = `lat ${lat}, day ${doy}: ${f(id, 3)} vs ${f(deepest, 3)}`; }
  }
}
ok(worstM < 0.25, 'D = 90 - |lat + dec| matches a scan of the full ephemeris',
   `worst ${f(worstM, 3)} deg over 35 pairs  [${worstMw}]`);

// ---------------------------------------------------------------------------
console.log('\n5. the band, and the altitude at which it closes');
let decMax = -Infinity, decMin = Infinity;
for (let ms = Date.UTC(2026, 0, 1); ms < Date.UTC(2027, 0, 1); ms += 3600000) {
  const d = sunVector(jdFromUnixMs(ms)).decDeg;
  if (d > decMax) decMax = d;
  if (d < decMin) decMin = d;
}
const twiLat = 90 - decMax - 18;
for (const h of [340, 420, 550, 600, 1200]) {
  const n = criticalLatitude(h, decMax), s = criticalLatitudeSouth(h, decMin);
  console.log(`     ${String(h).padStart(4)} km shell: darkens overhead at ${f(depressionForHeight(h), 2)} deg` +
              `   never darkens above ${f(n, 2)} N / below ${f(s, 2)} S` +
              `   band ${f(twiLat - n, 2)} deg`);
}
ok(Math.abs(criticalLatitude(550, decMax) - 43.57) < 0.02, 'the 550 km critical latitude is 43.57 N',
   f(criticalLatitude(550, decMax), 4));
ok(Math.abs(twiLat - 48.56) < 0.02, 'astronomical twilight stops ending above 48.56 N', f(twiLat, 4));
// The band closes where arccos(R/(R+h)) = 18 deg, i.e. where h is the shadow height at 18.
const closeKm = shadowHeight(18);
ok(Math.abs(criticalLatitude(closeKm, decMax) - twiLat) < 1e-9,
   'the band closes exactly at the shadow height at 18 degrees',
   `${f(closeKm, 1)} km, the same number as the ceiling in section 1`);

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