// verify-how-far-can-you-see-a-lighthouse.mjs: checks every number /strata/how-far-can-you-see-a-lighthouse/
// states, against the engine and data the page actually runs, against IALA's printed table, and
// against a second implementation of Allard's law written here from scratch.
//
//   node verify-how-far-can-you-see-a-lighthouse.mjs          # the frozen data (fetched 2026-09-26)
//   node verify-how-far-can-you-see-a-lighthouse.mjs --live   # also re-fetch Trinity House and NGA
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads engine.mjs and data/lights.json from https://artwaste.land (the bytes your browser runs).
// Exit 0 = every check passed. With --live the live checks may drift as the sources are corrected;
// a drift there is news about the sources, not a fault in the page.

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 = 'how-far-can-you-see-a-lighthouse';
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');
const data = await loadJSON('data/lights.json');

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;

// ── 1. the engine against IALA E-200-2, Annex Table 1, as printed ──────────────────
{
  // [low cd, high cd, miles], transcribed from the table (Edition 1, December 2008, page 14)
  const T = [[1, 2, 1], [3, 9, 2], [10, 23, 3], [24, 53, 4], [54, 107, 5], [108, 203, 6], [204, 364, 7], [365, 632, 8],
    [633, 1060, 9], [1070, 1750, 10], [1760, 2840, 11], [2850, 4530, 12], [4540, 7130, 13], [7140, 11100, 14], [11200, 17100, 15],
    [17200, 26100, 16], [26200, 39700, 17], [39800, 59900, 18], [60000, 89800, 19], [89900, 133000, 20], [134000, 198000, 21],
    [199000, 293000, 22], [294000, 432000, 23], [433000, 634000, 24], [635000, 926000, 25], [927000, 1350000, 26],
    [1360000, 1960000, 27], [1970000, 2840000, 28], [2850000, 4110000, 29], [4120000, 5930000, 30], [5940000, 8530000, 31],
    [8540000, 12200000, 32], [12300000, 17500000, 33], [17600000, 25100000, 34], [25200000, 35900000, 35], [36000000, 51200000, 36],
    [51300000, 72900000, 37], [73000000, 103000000, 38], [104000000, 147000000, 39], [148000000, 209000000, 40]];
  let bad = [];
  for (const [lo, hi, n] of T) { if (E.nominalRange(lo) !== n) bad.push(`${lo}->${E.nominalRange(lo)}`); if (E.nominalRange(hi) !== n) bad.push(`${hi}->${E.nominalRange(hi)}`); }
  ok(T.length * 2 === 80 && bad.length === 1 && bad[0] === '5930000->31', `79 of the 80 printed bounds of Table 1 (1 to 40 miles) round to the table's mile; the exception: ${bad.join(', ')}`);
  const edge = E.intensityFor(30.5), r3 = Number(edge.toPrecision(3));
  ok(r3 === 5930000 && edge < 5930000, `and that one is the true 30/31 boundary, ${Math.round(edge)} cd, printed to three figures as ${r3} (page says so)`);
  ok(near(1852 * 1852 * 2e-7, 0.686, 0.001), `3.43e6 x 2e-7 = ${(1852 * 1852 * 2e-7).toFixed(4)}: the 0.686 in E-200-2's night formula`);
  // an independent Allard's law, in the extinction-coefficient form (E-200-2 equation 1)
  const twin = (I, D, V) => { const z = -Math.log(0.05) / (V * 1852); return I * Math.exp(-z * D * 1852) / (D * 1852) ** 2; };
  let worst = 0;
  for (const I of [1, 50, 2e3, 7e4, 1e6, 3e7]) for (const D of [0.5, 3, 11, 24]) for (const V of [2, 10, 27]) worst = Math.max(worst, Math.abs(twin(I, D, V) / E.illuminance(I, D, V) - 1));
  ok(worst < 1e-12, `the engine's illuminance agrees with an extinction-coefficient twin at 72 points (worst relative ${worst.toExponential(1)})`);
  ok(near(Math.pow(0.05, 0.1), 0.7411, 1e-4), `transmissivity per mile at 10 miles visibility ${Math.pow(0.05, 0.1).toFixed(4)} (page: about 74%; E-200-2: 0.7411)`);
  ok(near(Math.sqrt(1 / 2e-7), 2236, 1), `one candela gives 2e-7 lux at ${Math.sqrt(1 / 2e-7).toFixed(0)} m in vacuum (page: about 2.2 km)`);
}

// ── 2. the horizon ──────────────────────────────────────────────────────────────────
{
  ok(near(E.horizon(1), 2.07, 0.005), `refraction 0.13 gives ${E.horizon(1).toFixed(4)} x sqrt(h) nm (page: 2.07)`);
  const direct = Math.sqrt(2 * 6371000 / 0.87 * 43) / 1852 + Math.sqrt(2 * 6371000 / 0.87 * 5) / 1852;
  ok(near(E.geographicRange(43, 5), direct, 1e-9) && near(direct, 18.2, 0.05), `Portland Bill 43 m from a 5 m eye: ${direct.toFixed(2)} nm (page: 18.2)`);
  ok(near(E.geographicRange(43, 15), 21.6, 0.05), `and from 15 m: ${E.geographicRange(43, 15).toFixed(2)} nm (page: 21.6)`);
  ok(near(E.hiddenHeight(E.geographicRange(43, 5), 5), 43, 1e-6), `at exactly the geographic range the hidden height equals the lamp height (${E.hiddenHeight(E.geographicRange(43, 5), 5).toFixed(6)} m)`);
}

// ── 3. the prose numbers ─────────────────────────────────────────────────────────────
{
  const r = (I, V = 10) => E.luminousRange(I, V);
  ok(near(r(1), 1.03, 0.01) && near(r(1e3), 9.4, 0.05) && near(r(1e6), 25.7, 0.05) && near(r(1e7), 31.9, 0.05),
    `1 cd -> ${r(1).toFixed(2)}, 1,000 -> ${r(1e3).toFixed(2)}, 1e6 -> ${r(1e6).toFixed(2)}, 1e7 -> ${r(1e7).toFixed(2)} nm (page: about 1, 9.4, 25.7, 31.9)`);
  ok(near(E.geographicRange(31, 5), 16.1, 0.05) && near(r(21500), 16.0, 0.05), `Beachy Head: horizon ${E.geographicRange(31, 5).toFixed(2)}, light ${r(21500).toFixed(2)} nm (page: 16.1 and 16)`);
  ok(E.geographicRange(31, 15) > 19 && r(21500, 5) < 10, `from 15 m the horizon is ${E.geographicRange(31, 15).toFixed(2)} (page: past 19); at 5 miles visibility the light dies at ${r(21500, 5).toFixed(2)} (page: gone by 10)`);
  const q = (a, b) => E.intensityFor(a) / E.intensityFor(b);
  ok(near(q(32, 16), 480, 10), `doubling 16 miles to 32 costs ${q(32, 16).toFixed(0)}x the light (page: about 480)`);
  ok(near(q(24, 18), 11, 0.5), `18 to 24 miles costs ${q(24, 18).toFixed(1)}x (page: about 11)`);
  ok(near(q(25, 18), 16, 0.5) && near(q(21, 18), 3, 0.4), `25 to 18 is ${q(25, 18).toFixed(1)}x less light, 21 to 18 is ${q(21, 18).toFixed(1)}x (page: about 16 and about 3)`);
}

// ── 4. Trinity House's own numbers ──────────────────────────────────────────────────────
const scored = data.th.filter((l) => l.cd != null && l.range != null);
{
  ok(data.th.length === 72, `${data.th.length} Trinity House pages with a position (75 fetched; 3 carry no data at all)`);
  ok(scored.length === 60, `${scored.length} publish both a candela and a range (page: 60)`);
  const d = scored.map((l) => ({ l, diff: l.range - E.nominalRange(l.cd) }));
  const agree = d.filter((x) => x.diff === 0).length, within = d.filter((x) => Math.abs(x.diff) <= 1).length;
  ok(agree === 32 && within === 48, `${agree} agree exactly, ${within} within a mile (page: 32, 48)`);
  const miss = d.filter((x) => x.diff !== 0), lower = miss.filter((x) => x.diff < 0).length;
  ok(miss.length === 28 && lower === 21, `${lower} of ${miss.length} misses publish less range than their candela gives (page: 21 of 28)`);
  const ets = scored.map((l) => E.impliedThreshold(l.cd, l.range)).sort((a, b) => a - b);
  const med = (ets[29] + ets[30]) / 2;
  ok(near(med, 2.01e-7, 0.005e-7), `median implied threshold ${med.toExponential(3)} lux (page: 2.01e-7; IALA: 2e-7)`);
  const sf = scored.filter((l) => E.nominalRange(l.cd * 0.75) === l.range).length;
  ok(sf === 16, `with IALA's 0.75 service factor applied, ${sf} agree exactly (page: 16 instead of 32)`);
  const big = d.filter((x) => Math.abs(x.diff) >= 3).map((x) => x.l.slug.replace(/-lighthouse$/, '')).sort();
  ok(big.join() === 'berry-head,casquets,lynmouth-foreland,south-bishop,southwold', `off by three miles or more: ${big.join(', ')}`);
  const sw = scored.find((l) => l.slug === 'southwold-lighthouse');
  ok(sw.cd === 17100 && sw.range === 24 && E.nominalRange(sw.cd) === 15 && near(E.intensityFor(23.5), 432383, 1) && near(E.intensityFor(24.5), 634114, 1),
    `Southwold: 17,100 cd gives ${E.nominalRange(17100)}; 24 miles needs ${Math.round(E.intensityFor(23.5))} to ${Math.round(E.intensityFor(24.5))} cd`);
  const bh = scored.find((l) => l.slug === 'berry-head-lighthouse');
  ok(bh.cd === 4200 && bh.range === 19 && E.nominalRange(4200) === 12 && E.nominalRange(39800) === 18 && E.nominalRange(59900) === 18, `Berry Head: 4,200 cd gives ${E.nominalRange(4200)}; 18 miles is 39,800 to 59,900 cd`);
}

// ── 5. NGA against Trinity House ──────────────────────────────────────────────────────
{
  const m = data.th.filter((l) => l.nga && l.range != null);
  const diff = m.filter((l) => l.nga.range !== l.range);
  ok(m.length === 70 && m.length - diff.length === 67, `${m.length} matched to NGA, ${m.length - diff.length} with the same range (page: 67 of 70)`);
  const got = diff.map((l) => `${l.slug}:${l.range}/${l.nga.range}`).sort().join(' ');
  ok(got === 'portland-bill-lighthouse:18/25 st-catherines-lighthouse:18/25 trevose-head:18/21', `the three disagreements: ${got}`);
  const pb = data.th.find((l) => l.slug === 'portland-bill-lighthouse');
  ok(pb.nga.notice === 201514, `NGA's Portland Bill record carries notice ${pb.nga.notice} (page: 14/2015)`);
  const bh = data.th.find((l) => l.slug === 'berry-head-lighthouse');
  ok(bh.nga.range === 19, `NGA prints Berry Head at ${bh.nga.range} (page: 19, same as Trinity House's own page)`);
}

// ── 6. the review's appendix ──────────────────────────────────────────────────────────
{
  const g = data.gla, c = {}; for (const x of g) c[x.range] = (c[x.range] || 0) + 1;
  ok(g.length === 352, `${g.length} non-buoy lights parsed from the review's appendix (page: 352)`);
  const sorted = Object.entries(c).sort((a, b) => b[1] - a[1]);
  ok(sorted[0][0] === '18' && sorted[0][1] === 54 && sorted[1][0] === '8' && sorted[1][1] === 26, `mode ${sorted[0][0]} miles with ${sorted[0][1]}; next ${sorted[1][0]} with ${sorted[1][1]} (page: 54 at 18, then 26 at 8)`);
  ok(g.filter((x) => x.range > 18).length === 60, `${g.filter((x) => x.range > 18).length} above 18 (page: 60)`);
  const red = g.filter((x) => /reduce/i.test(x.comment) && /18/.test(x.comment)).map((x) => x.name).sort().join(', ');
  ok(/FLAMBOROUGH/.test(red) && /BISHOP ROCK/.test(red) && /TREVOSE/.test(red) && /ST CATHERINES/.test(red) && /NASH POINT/.test(red), `marked for reduction to 18: ${red}`);
}

// ── 7. live: the sources as they stand today ──────────────────────────────────────────
if (LIVE) {
  const th = async (p) => (await (await fetch('https://www.trinityhouse.co.uk/' + p, { headers: { 'user-agent': 'Mozilla/5.0' } })).text()).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ');
  const notices = [
    ['notice-to-mariners/7/2019-berry-head-lighthouse', 'Nominal range of light will be reduced to 18nm'],
    ['notice-to-mariners/10/2019-portland-bill-lighthouse', 'Nominal range of light will be reduced to 18nm'],
    ['notice-to-mariners/11/2021-st-catherines-lighthouse', 'revised nominal range of 18nm'],
    ['notice-to-mariners/22/2023-trevose-head-lighthouse', 'permanently reduced from 21nm to 18nm'],
    ['notice-to-mariners/01/2016-southwold-lighthouse', 'with a nominal range of 24nm'],
  ];
  for (const [p, s] of notices) { const t = await th(p); ok(t.includes(s), `live: ${p} says "${s}"`); }
  const sw = await th('lighthouses-and-lightvessels/southwold-lighthouse');
  console.log(`INFO  live: Southwold page intensity/range now: ${(sw.match(/Intensity\s+([\d,]+)/) || [])[1]} / ${(sw.match(/Range of light\s+(\d+)/) || [])[1]}`);
  const nga = await (await fetch('https://msi.nga.mil/api/publications/ngalol/lights-buoys?volume=114&includeRemovals=false&output=json')).json();
  const pb = nga.ngalol.find((r) => /Bill of Portland/.test(r.name || ''));
  console.log(`INFO  live: NGA Portland Bill range now ${pb && pb.range} (frozen 2026-09-26: 25)`);
}

console.log(`\n${passes} passed, ${fails} failed`);
process.exit(fails ? 1 : 0);
