// verify-the-hours-a-glass-ball-could-burn.mjs: checks every number /strata/the-hours-a-glass-ball-could-burn/
// states or computes, against the engine and data the page actually runs, and against second
// implementations written here from scratch.
//
//   node verify-the-hours-a-glass-ball-could-burn.mjs          # frozen station data (2026-09-26)
//   node verify-the-hours-a-glass-ball-could-burn.mjs --live   # re-fetch the 37 files from the Met Office
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads engine.mjs, switch.mjs and data/*.json from https://artwaste.land (the bytes your browser runs).
// Exit 0 = every check passed. With --live the record checks may drift as the Met Office appends months.

import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'the-hours-a-glass-ball-could-burn';
const localDir = join(here, 'public/strata', slug);
const remote = `https://artwaste.land/strata/${slug}/`;
const LIVE = process.argv.includes('--live');
async function loadModule(name) {
  const p = join(localDir, name); if (existsSync(p)) return import(p);
  const src = await (await fetch(remote + name)).text();
  return import('data:text/javascript;base64,' + Buffer.from(src).toString('base64'));
}
async function loadJSON(name) {
  const p = join(localDir, name); if (existsSync(p)) return JSON.parse(readFileSync(p, 'utf8'));
  return (await fetch(remote + name)).json();
}
console.error(`files: ${existsSync(localDir) ? localDir : remote}`);
const E = await loadModule('engine.mjs'), M = await loadModule('switch.mjs');

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const DEG = Math.PI / 180;

// ── 1. the ball ─────────────────────────────────────────────────────────────
{
  const f = E.ballFocal(1.52, 50);
  ok(near(f, 73.077, 0.001), `paraxial focus of a 100 mm sphere at n = 1.52, from its centre: ${f.toFixed(3)} mm (page: 73.08; WMO bowl radius 73 mm)`);
  ok(near(E.ballFocal(1.50, 50), 75, 1e-9), `at n = 1.50 the same formula gives ${E.ballFocal(1.5, 50)} mm (the WMO table's 75 mm focal length)`);
  const lo = E.ballFocal(1.54, 50), hi = E.ballFocal(1.50, 50);
  ok(lo < 73 && 73 < hi, `the 73 mm bowl lies inside the focus range of the stated tolerance 1.52 ± 0.02 (${lo.toFixed(2)} to ${hi.toFixed(2)} mm)`);
  // independent twin: vector Snell's law, a ray 0.01 mm off axis
  const snell = (d, nrm, n1, n2) => { const c = -(d[0] * nrm[0] + d[1] * nrm[1]), r = n1 / n2, k = 1 - r * r * (1 - c * c); return [r * d[0] + (r * c - Math.sqrt(k)) * nrm[0], r * d[1] + (r * c - Math.sqrt(k)) * nrm[1]]; };
  function twin(n, R, h) {
    let p = [-Math.sqrt(R * R - h * h), h], d = [1, 0];
    d = snell(d, [p[0] / R, p[1] / R], 1, n);
    const b = p[0] * d[0] + p[1] * d[1], t = -b + Math.sqrt(b * b - (p[0] ** 2 + p[1] ** 2 - R * R)); p = [p[0] + t * d[0], p[1] + t * d[1]];
    d = snell(d, [-p[0] / R, -p[1] / R], n, 1); return p[0] - p[1] * d[0] / d[1];
  }
  ok(near(twin(1.52, 50, 0.01), f, 0.001), `vector-Snell twin, ray 0.01 mm off axis, crosses at ${twin(1.52, 50, 0.01).toFixed(4)} mm`);
  let worst = 0; for (const h of [-45, -30, -10, 5, 20, 40, 48]) worst = Math.max(worst, Math.abs(twin(1.52, 50, h) - E.traceRay(1.52, 50, h).x));
  ok(worst < 1e-9, `the page's ray tracer agrees with the twin at seven heights on both sides of the axis (worst ${worst.toExponential(1)} mm)`);
  ok(E.traceRay(1.52, 50, 40).x < E.traceRay(1.52, 50, 20).x && E.traceRay(1.52, 50, 20).x < f, `outer rays cross short of the paraxial focus (spherical aberration): h=40 at ${E.traceRay(1.52, 50, 40).x.toFixed(1)} mm, h=20 at ${E.traceRay(1.52, 50, 20).x.toFixed(1)} mm`);
}
// ── 2. the card ─────────────────────────────────────────────────────────────
{
  const F = 7.3; let worst = 0;
  for (const dec of [-23.44, -10, 0, 12, 23.44]) for (let H = -90; H < 90; H += 7.5) {
    const a = E.burnPoint(F, dec, H), b = E.burnPoint(F, dec, H + 15); // one hour later
    const ang = Math.acos((a[0] * b[0] + a[1] * b[1]) / Math.hypot(a[0], a[1]) / Math.hypot(b[0], b[1])) / DEG; // angle about the polar axis
    worst = Math.max(worst, Math.abs(ang - 15));
    const arc = Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); const expect = 2 * F * Math.cos(dec * DEG) * Math.sin(7.5 * DEG); // chord of 15° on a circle of radius F cos(dec)
    worst = Math.max(worst, Math.abs(arc - expect));
    worst = Math.max(worst, Math.abs(Math.hypot(...a) - F));
  }
  ok(worst < 1e-9, `the burn turns exactly 15° per hour about the polar axis and stays on the bowl, at every declination and hour tested (worst ${worst.toExponential(1)})`);
  ok(near(E.hourSpacing(7.3, 0), 1.911, 0.001), `equinox hour spacing on a 73 mm bowl: ${E.hourSpacing(7.3, 0).toFixed(3)} cm; solstice ${E.hourSpacing(7.3, 23.44).toFixed(3)} cm (page readout: 1.75)`);
  // tangent cone at polar distance (90 - |dec|) on a sphere of radius F: apex on the axis at F / sin|dec|; slant = distance apex -> circle
  const dec = 23.44, apex = F / Math.sin(dec * DEG), circle = [F * Math.cos(dec * DEG), F * Math.sin(dec * DEG)];
  const slant = Math.hypot(circle[0], circle[1] - apex);
  ok(near(slant, E.cardUnrollRadius(F, dec), 1e-9) && near(slant, 16.8, 0.05), `the solstice card unrolls to an arc of radius ${slant.toFixed(2)} cm (constructed tangent cone) (page: about 16.8 cm)`);
  ok(E.cardUnrollRadius(F, 0) === Infinity, 'at the equinox the unrolled radius is infinite: a straight card');
}
// ── 3. the beam ─────────────────────────────────────────────────────────────
{
  const pv = await loadJSON('data/pvlib-dni.json'); let worst = 0;
  for (const [N, TL, h, v] of pv.rows) worst = Math.max(worst, Math.abs(E.dniClear(h, TL, N) - v));
  ok(pv.rows.length === 330 && worst < 1e-9, `clear-sky beam agrees with pvlib ${pv.pvlib} ineichen() on ${pv.rows.length} points (worst ${worst.toExponential(1)} W/m²)`);
  // independent loop: daylight and burn minutes at Oxford's latitude on day 172
  let up = 0, burn = 0; const d = E.declination(172);
  for (let t = 0; t < 1440; t++) { const H = (t + 0.5 - 720) / 4; const s = Math.sin(51.5 * DEG) * Math.sin(d * DEG) + Math.cos(51.5 * DEG) * Math.cos(d * DEG) * Math.cos(H * DEG); const h = Math.asin(s) / DEG; if (h > 0) { up++; if (E.dniClear(h, 3.5, 172) >= 120) burn++; } }
  const r = E.dayMinutes(51.5, 172, 120, 3.5);
  ok(r.up === up && r.burn === burn, `51.5°N, 21 June, haze 3.5: sun up ${up} min, beam ≥ 120 W/m² for ${burn} min (engine: ${r.up}, ${r.burn})`);
  ok(near(E.declination(172), 23.44, 0.1) && near(E.declination(80), 0, 0.5), `Spencer declination: ${E.declination(172).toFixed(2)}° on day 172, ${E.declination(80).toFixed(2)}° on day 80`);
}
// ── 4. the record ───────────────────────────────────────────────────────────
let data = await loadJSON('data/stations.json');
if (LIVE) {
  const names = Object.keys(data.stations); data = { ...data, stations: {} };
  for (const k of names) {
    const txt = await (await fetch(`https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/${k}data.txt`)).text();
    const lines = txt.split(/\r?\n/); const ll = txt.match(/Lat\s*(-?[\d.]+)\s*Lon\s*(-?[\d.]+)/);
    const sun = []; for (const l of lines) { const m = l.match(/^\s+(\d{4})\s+(\d{1,2})\s+(.*)$/); if (!m) continue; const c = m[3].trim().split(/\s+/)[4];
      if (!c || c.startsWith('---')) continue; const v = parseFloat(c); if (!isFinite(v)) continue; sun.push([+m[1], +m[2], v, c.includes('#') ? 'KZ' : c.includes('*') ? 'EST' : 'CS']); }
    data.stations[k] = { name: lines[0].trim(), lat: +ll[1], lon: +ll[2], sun };
  }
  console.error('re-fetched 37 station files from the Met Office');
}
const st = M.prepare(data);
{
  const names = Object.keys(data.stations);
  const sw = names.filter(k => data.stations[k].sun.some(r => r[3] === 'KZ'));
  ok(names.length === 37, `${names.length} station files (Met Office historic station data lists 37)`);
  ok(sw.length === 16, `${sw.length} stations carry a # (sensor) value`);
  const first = sw.map(k => data.stations[k].sun.find(r => r[3] === 'KZ')).map(r => r[0] * 12 + r[1]);
  const mn = sw[first.indexOf(Math.min(...first))], mx = sw[first.indexOf(Math.max(...first))];
  ok(mn === 'manston' && mx === 'rossonwye', `first switch ${mn}, last ${mx} (page: Manston Nov 2000, Ross-on-Wye Jan 2019)`);
  let back = 0; for (const k of sw) { const rows = data.stations[k].sun; const i = rows.findIndex(r => r[3] === 'KZ'); back = Math.max(back, rows.slice(i).filter(r => r[3] === 'CS').length); }
  ok(back <= 6, `no switched station reports more than ${back} glass-ball months after its first sensor month`);
  ok(['oxford', 'armagh'].every(k => !data.stations[k].sun.some(r => r[3] === 'KZ')), 'Oxford and Armagh carry no # anywhere');
}
// independent twin of the step: plain loops over the raw rows, no shared code
function twinStep(a, c, T, W = 60) {
  const get = (k, t) => data.stations[k].sun.find(r => (r[0] * 12 + r[1] - 1) === t);
  const cell = [[], []].map(() => Array.from({ length: 12 }, () => ({ a: 0, c: 0, n: 0 })));
  for (let t = T - W; t < T + W; t++) { const ra = get(a, t), rc = get(c, t); if (!ra || !rc || rc[3] !== 'CS') continue;
    const side = t < T ? 0 : 1; if (ra[3] !== (side ? 'KZ' : 'CS')) continue; const x = cell[side][t % 12]; x.a += ra[2]; x.c += rc[2]; x.n++; }
  let sb = [0, 0], sa = [0, 0];
  for (let m = 0; m < 12; m++) { const b = cell[0][m], f = cell[1][m]; if (b.n < 3 || f.n < 3) return null; sb[0] += b.a / b.n; sb[1] += b.c / b.n; sa[0] += f.a / f.n; sa[1] += f.c / f.n; }
  return (sa[0] / sa[1]) / (sb[0] / sb[1]);
}
const hav = (p, q) => { const r = DEG, a = Math.sin((q.lat - p.lat) * r / 2) ** 2 + Math.cos(p.lat * r) * Math.cos(q.lat * r) * Math.sin((q.lon - p.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(a)); };
const med = a => { const s = [...a].sort((x, y) => x - y), n = s.length; return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2; };
{
  const rows = M.switchedSteps(st, { R: 300, W: 60 }); let agree = 0, scored = 0;
  const twinRes = [];
  for (const r of rows) {
    const s = data.stations[r.key]; const T = st[r.key].switchT;
    const steps = Object.keys(data.stations).filter(c => c !== r.key && hav(s, data.stations[c]) <= 300).map(c => twinStep(r.key, c, T)).filter(x => x != null);
    const tw = steps.length >= 2 ? med(steps) : null; if (tw != null) twinRes.push(tw);
    if ((tw == null) === (r.step == null) && (tw == null || near(tw, r.step.annual, 1e-9))) agree++; if (r.step) scored++;
  }
  ok(agree === rows.length, `a second implementation reproduces every station's step (${agree} of ${rows.length} agree, ${scored} scored)`);
  const neg = twinRes.filter(x => x < 1).length, m = med(twinRes);
  ok(twinRes.length === 13 && neg === 12, `${neg} of ${twinRes.length} scored stations drop against their neighbours (page: 12 of 13)`);
  ok(near((m - 1) * 100, -10.3, 0.05), `median step ${((m - 1) * 100).toFixed(1)}% (page: −10.3%)`);
  const p = M.signTest(13, 12); let q = 0; for (const k of [12, 13]) { let c = 1; for (let i = 0; i < k; i++) c = c * (13 - i) / (i + 1); q += c / 8192; }
  ok(near(p, q, 1e-15) && near(p, 0.0017, 0.00005), `sign test, 12 of 13: P = ${q.toFixed(5)} (page: 0.0017)`);
  const pl = M.placebo(st).map(x => x.annual);
  const lo = M.quantile(pl, 0.025), hi = M.quantile(pl, 0.975);
  ok(pl.length === 238 && near((lo - 1) * 100, -7.7, 0.05) && near((hi - 1) * 100, 9.9, 0.05), `no-change steps: ${pl.length} at invented dates, 95% between ${((lo - 1) * 100).toFixed(1)}% and +${((hi - 1) * 100).toFixed(1)}%`);
  ok(twinRes.filter(x => x < lo).length === 8, `${twinRes.filter(x => x < lo).length} real steps fall below the no-change 2.5th percentile (page: 8)`);
  // robustness grid, the page's two sliders
  let allNeg = true; for (const R of [150, 200, 300, 400]) for (const W of [36, 60, 96]) { const s = M.switchedSteps(st, { R, W }).filter(x => x.step); const mm = M.median(s.map(x => x.step.annual)); if (!(mm < 0.95 && mm > 0.87)) allNeg = false; }
  ok(allNeg, 'at every neighbour radius 150–400 km and window 3–8 years tried, the median step lies between −5% and −13%');
}
{
  const ev = M.eventStudy(st, { R: 300, K: 8 });
  const pre = ev.pooled.filter(p => p.k < 0), post = ev.pooled.filter(p => p.k >= 0 && p.k <= 2);
  ok(pre.every(p => near(p.median, 1, 0.02)), `event study: every pre-switch year's median ratio within 2% of 1 (${pre.map(p => p.median.toFixed(3)).join(', ')})`);
  ok(post.every(p => p.median < 0.92 && p.median > 0.9), `first three sensor years: ${post.map(p => p.median.toFixed(3)).join(', ')} (page: about a tenth lower)`);
  const r = M.monthlyR(st, { R: 300, W: 60 }), mean = r.reduce((a, b) => a + b) / 12, pl = M.PERRY_LEGG_RAW_R.reduce((a, b) => a + b) / 12;
  ok(near(pl, 1.096, 0.0005) && near(mean, 1.102, 0.0005), `ball/sensor ratio, mean of twelve months: public files ${mean.toFixed(3)}, Perry & Legg Table 2 raw R ${pl.toFixed(3)}`);
  ok(Math.min(...M.PERRY_LEGG_RAW_R) === 1.037 && Math.max(...M.PERRY_LEGG_RAW_R) === 1.152, 'Perry & Legg raw R runs from 1.037 (December) to 1.152 (May): the page\'s 3.7% and 15.2%');
}
console.log(`\n${passes} passed, ${fails} failed`);
process.exit(fails ? 1 : 0);
