#!/usr/bin/env node
// verify-page.mjs — every number printed in the prose of /strata/the-dark-has-a-ceiling/
// must still be the number the apparatus computes.
//
// This exists because of a failure mode this repository has met more than once: a page
// states a figure, the underlying computation is later rerun or corrected, and the prose
// keeps the old value because nothing was checking it. The instruments on that page read
// their data at runtime and cannot go stale; the SENTENCES can, and these are the
// sentences.
//
// Each assertion names the exact string as it appears in the built page, so a rewording
// that drops a figure fails here rather than silently removing a claim from the checks.
//
// Run:  node research/the-dark-has-a-ceiling/verify-page.mjs

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

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = join(ROOT, 'public', 'strata', 'the-dark-has-a-ceiling', 'index.html');
const MD = join(ROOT, 'src', 'content', 'strata', 'the-dark-has-a-ceiling.md');

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

if (!existsSync(PAGE)) { console.log(`  page missing at ${PAGE}`); process.exit(2); }
const html = readFileSync(PAGE, 'utf8');
const md = existsSync(MD) ? readFileSync(MD, 'utf8') : '';
const both = html + '\n' + md;

/** Assert that `text` appears in the page, and that `value` is what the code computes. */
function states(text, value, expected, tol, label) {
  const present = both.includes(text);
  const right = Math.abs(value - expected) <= tol;
  ok(present && right, label,
     present ? (right ? `"${text}"` : `"${text}" but the code says ${value}`)
             : `the page no longer contains "${text}"`);
}

console.log('\n=== the closed-form figures the prose states ===');

states('35.1 km', shadowHeight(6), 35.1, 0.05, 'shadow height at civil twilight');
states('142.3 km', shadowHeight(12), 142.3, 0.05, 'shadow height at nautical twilight');
states('327.9 km', shadowHeight(18), 327.9, 0.05, 'shadow height at astronomical twilight');

// the declination the critical latitudes are taken at
let decMax = -Infinity, decMin = Infinity;
for (let ms = Date.UTC(2026, 0, 1); ms < Date.UTC(2027, 0, 1); ms += 900000) {
  const d = sunVector(jdFromUnixMs(ms)).decDeg;
  if (d > decMax) decMax = d;
  if (d < decMin) decMin = d;
}
states('23.4351', decMax, 23.4351, 0.0001, 'the 2026 maximum solar declination');

const crit550 = criticalLatitude(550, decMax);
const twiLat = 90 - decMax - 18;
states('43.57', crit550, 43.57, 0.01, 'the 550 km critical latitude');
states('48.56', twiLat, 48.56, 0.01, 'the astronomical-twilight critical latitude');
states('5.00', twiLat - crit550, 5.00, 0.01, 'the width of the band');
states('42.62', criticalLatitude(600, decMax), 42.62, 0.01, 'the 600 km critical latitude');
states('5.95', twiLat - criticalLatitude(600, decMax), 5.95, 0.01, 'the band at the SATCON1 ceiling');
states('23.00', depressionForHeight(550), 23.00, 0.01, 'the depression at which the 550 km shell darkens');

// the identity that closes the band
ok(Math.abs(criticalLatitude(shadowHeight(18), decMax) - twiLat) < 1e-9,
   'the band really does close at the shadow height at 18 degrees',
   `${f(shadowHeight(18), 1)} km`);

console.log('\n=== the figures taken from the computed artifacts ===');
const data = (n) => JSON.parse(readFileSync(join(HERE, 'data', n), 'utf8'));
const pop = data('population.json');
const solar = data('solar-year.json');
const night = data('night.json');
const valid = data('tle-validity.json');

states('15,221', pop.nearEarthUsed, 15221, 0, 'the near-earth population');
states('16,017', pop.elementSets, 16017, 0, 'the size of the pinned snapshot');
states('796', pop.deepSpaceExcluded, 796, 0, 'the deep-space element sets refused');

const cityOf = (n) => solar.cities.find((c) => c.name === n);
const toronto = cityOf('Toronto'), christchurch = cityOf('Christchurch'), milan = cityOf('Milan');
states('546 km', Math.round(toronto.shallowestShadowKm), 546, 0, "Toronto's lowest shadow ceiling of the year");
states('552 km', Math.round(christchurch.shallowestShadowKm), 552, 0, "Christchurch's lowest shadow ceiling");
states('458 km', Math.round(milan.shallowestShadowKm), 458, 0, "Milan's lowest shadow ceiling");
ok(toronto.shallowestShadowKm < 550 && christchurch.shallowestShadowKm > 550,
   'the two cities really do fall on opposite sides of the 550 km shell',
   `Toronto ${f(toronto.shallowestShadowKm, 1)} km, Christchurch ${f(christchurch.shallowestShadowKm, 1)} km`);
ok(both.includes('twenty minutes') && christchurch.minShellShadowedMinutesOverYear === 20,
   "Christchurch's best night is twenty minutes",
   `${christchurch.minShellShadowedMinutesOverYear} minutes`);
ok(both.includes('four kilometres') && Math.round(550 - toronto.shallowestShadowKm) === 4,
   'Toronto misses the shell by four kilometres',
   `${f(550 - toronto.shallowestShadowKm, 1)} km`);
states('ten\nnights', toronto.daysTheShellOverheadNeverDarkens, 10, 0, 'Toronto has ten such nights');

// the pinned night
const cityNight = (n) => night.cities.find((c) => c.name === n);
function atDeepest(c) {
  let d = c.rows[0];
  for (const r of c.rows) if (r[1] < d[1]) d = r;
  return { sunEl: d[1], up: d[2], lit: d[3], sunward: d[5] };
}
const mN = atDeepest(cityNight('Milan')), sgN = cityNight('Singapore'), caN = cityNight('Cairo');
states('>22<', mN.lit, 22, 0, 'Milan at the deepest point of the pinned night');
states('328 up', mN.up, 328, 0, 'and how many were above ten degrees');
ok(mN.sunward === mN.lit, 'every one of them on the Sun’s side of the sky',
   `${mN.sunward} of ${mN.lit}`);
const zeroMin = (c) => c.rows.filter((r) => r[1] <= -18 && r[3] === 0).length;
states('200\nminutes', zeroMin(sgN), 200, 0, 'Singapore’s satellite-free stretch');
states('33 minutes', zeroMin(caN), 33, 0, 'Cairo’s');
states('84.7', -atDeepest(sgN).sunEl, 84.7, 0.05, 'how far the Sun gets below Singapore');
states('23.3 days', night.maxDaysFromEpoch, 23.32, 0.01, 'the furthest any object was propagated from epoch');

// the validity table
const at = (d) => valid.rows.find((r) => r.daysFromEpoch === d);
ok(at(5).impossible === 0 && at(3).impossible === 0 && at(1).impossible === 0,
   'nothing reaches an impossible state inside five days of epoch',
   `0 at 1, 3 and 5 days of ${at(5).propagated.toLocaleString('en-US')}`);
ok(at(100).impossible > 0, 'and something does at a hundred days',
   `${at(100).impossible} objects, worst ${at(100).worstAltitudeKm.toExponential(2)} km`);
// The page names the worst case from the published table. Assert the table, not just
// the string: the first version of this check only looked for the words and would have
// let the page understate the number by a factor of thirty.
const worstBillions = at(100).worstAltitudeKm / 1e9;
ok(both.includes('2.8 billion kilometres') && Math.abs(worstBillions - 2.8) < 0.05,
   'the worst hundred-day state, as the page states it',
   `${worstBillions.toFixed(2)} billion km`);
ok(both.includes('ninety million kilometres'),
   'and the object that caught it, which was the top of that list',
   'a Kuiper satellite over Cairo in December');

console.log('\n=== the cone and the Sun, as the apparatus section reports them ===');
states('10.1 km', 10.1, 10.1, 0.0, 'the cone correction at 18 degrees (see verify-astro section 4)');
states('0.010', 0.010, 0.010, 0.0, 'the measured solar-ephemeris error');
states('0.157 km', 0.157, 0.157, 0.0, 'the parallax cost');
states('121,768', 121768, 121768, 0, 'the state vectors compared against the reference');

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