#!/usr/bin/env node
// verify-the-sky-nobody-shares.mjs
//
// Re-derives everything /strata/the-sky-nobody-shares/ prints, and checks the shipped
// page against it. Every claim on the page traces to one of these tests, and this file
// is what a stranger runs to find out whether the page is telling the truth.
//
//   node verify-the-sky-nobody-shares.mjs                # all sections
//   node verify-the-sky-nobody-shares.mjs --no-page      # skip the shipped-page assertions
//
// The precession port lives in research/the-sky-nobody-shares/lib/precess.mjs and is
// checked here against a pyerfa-generated reference table, element by element, before
// any page number is trusted. If ERFA and the port disagree, everything downstream is
// suspect and the run fails loudly.

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

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = (p) => join(ROOT, p);
const HERE = R('research/the-sky-nobody-shares');

const P = await import(join(HERE, 'lib/precess.mjs'));
const B = await import(join(HERE, 'lib/boundaries.mjs'));

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) pass++;
  else { fail++; console.log(`  FAIL  ${name}${detail ? ' — ' + detail : ''}`); }
};
const section = (s) => console.log(`\n${s}`);
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── 1. the JavaScript precession port matches ERFA to machine precision ────
section('1. Precession port vs ERFA (data/erfa-reference.json)');
const ref = JSON.parse(readFileSync(join(HERE, 'data/erfa-reference.json'), 'utf8'));
ok('reference table has 15 epochs', ref.epochs.length === 15, `got ${ref.epochs.length}`);
let worstPmat = 0, worstLtp = 0, worstEcl = 0, worstEqu = 0, worstObl = 0;
for (const e of ref.epochs) {
  const a = P.pmat06(e.julianEpoch), b = P.ltp(e.julianEpoch);
  for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
    worstPmat = Math.max(worstPmat, Math.abs(a[i][j] - e.pmat06[i][j]));
    worstLtp = Math.max(worstLtp, Math.abs(b[i][j] - e.ltp[i][j]));
  }
  const ec = P.ltpecl(e.julianEpoch), eq = P.ltpequ(e.julianEpoch);
  for (let i = 0; i < 3; i++) {
    worstEcl = Math.max(worstEcl, Math.abs(ec[i] - e.ltpecl[i]));
    worstEqu = Math.max(worstEqu, Math.abs(eq[i] - e.ltpequ[i]));
  }
  worstObl = Math.max(worstObl, Math.abs(P.obl06((e.julianEpoch - 2000) / 100) - e.obl06));
}
ok('pmat06 matches ERFA to 1e-15 across 15 epochs', worstPmat < 1e-15, `worst ${worstPmat.toExponential(2)}`);
ok('ltp (Vondrak) matches ERFA to 1e-15', worstLtp < 1e-15, `worst ${worstLtp.toExponential(2)}`);
ok('ltpecl matches ERFA exactly', worstEcl === 0, `worst ${worstEcl.toExponential(2)}`);
ok('ltpequ matches ERFA exactly', worstEqu === 0, `worst ${worstEqu.toExponential(2)}`);
ok('obl06 matches ERFA exactly', worstObl === 0, `worst ${worstObl.toExponential(2)}`);

// ── 2. B1875 handling is correct ───────────────────────────────────────────
section('2. Delporte boundaries and the B1875.0 -> J2000 lift');
const rings = B.readRingsB1875();
ok('89 boundary loops for 88 constellations', rings.size === 89);
let ringCount = 0; for (const [, r] of rings) ringCount += r.length;
ok('one loop per key except Serpens', ringCount === 89);
ok('Serpens is in two pieces', rings.get('Ser1').length === 1 && rings.get('Ser2').length === 1);
ok('Ursa Minor winds once round in RA', Math.abs(B.ringWindingHours(rings.get('UMi')[0])) - 24 < 1e-6);
ok('Octans winds once round in RA', Math.abs(B.ringWindingHours(rings.get('Oct')[0])) - 24 < 1e-6);
ok('Crux ring winding is zero', Math.abs(B.ringWindingHours(rings.get('Cru')[0])) < 1e-6);

// ── 3. constellation areas sum to the sphere, and match Delporte ───────────
section('3. Constellation areas (sphere closure, and per-constellation)');
const areas = B.areasSqDeg({ stepDeg: 0.05 });
let areaSum = 0; for (const [, a] of areas) areaSum += a;
ok('88 areas sum to 4π sr (41252.961 sq deg)', Math.abs(areaSum - 41252.96125) < 0.02, `got ${areaSum.toFixed(3)}`);
// Published Delporte figures from the IAU (via the standard tabulation).
const PUB = {
  Hya: 1302.844, Vir: 1294.428, UMa: 1279.660, Cet: 1231.411, Her: 1225.148,
  Eri: 1137.919, Peg: 1120.794, Dra: 1082.952, Cen: 1060.422, Aqr: 979.854,
  Cru: 68.447, Sge: 79.923, Equ: 71.641, UMi: 255.864, Oct: 291.045,
};
for (const [k, v] of Object.entries(PUB)) {
  ok(`${k} area matches published ${v.toFixed(3)} sq deg`, Math.abs(areas.get(k) - v) < 0.01,
     `got ${areas.get(k).toFixed(3)}`);
}

// ── 4. the population profile totals the GHS-POP grid ──────────────────────
section('4. Population by latitude');
const POP = JSON.parse(readFileSync(join(HERE, 'data/pop-by-latitude-raw.json'), 'utf8'));
ok('grid is 43202 × 21384', POP.nrow === 21384 && POP.ncol === 43202);
ok('total is close to 7.84 billion (GHS-POP 2020)', Math.abs(POP.total - 7.84e9) < 5e7,
   `got ${(POP.total / 1e9).toFixed(3)} bn`);
// hemisphere split (the anchor number for the whole study)
let n = 0, s = 0;
for (let i = 0; i < POP.nrow; i++) {
  const lat = POP.lat0 - (i + 0.5) * POP.dlat;
  if (lat >= 0) n += POP.rows[i]; else s += POP.rows[i];
}
ok('~87% of humanity lives north of the equator', Math.abs(n / POP.total - 0.866) < 0.01,
   `${(n / POP.total * 100).toFixed(2)}%`);

// ── 5. the shipped page matches the compute output ─────────────────────────
if (!process.argv.includes('--no-page')) {
  section('5. The shipped page vs research/the-sky-nobody-shares/browser-data.json');
  const PAGE = R('public/strata/the-sky-nobody-shares/index.html');
  ok('the immersive page exists', existsSync(PAGE));
  if (existsSync(PAGE)) {
    const html = readFileSync(PAGE, 'utf8');
    const m = html.match(/<script id="sky-data" type="application\/json">([\s\S]*?)<\/script>/);
    ok('page carries its data inline', m !== null);
    if (m) {
      const embedded = m[1];
      const source = readFileSync(join(HERE, 'browser-data.json'), 'utf8');
      ok('embedded JSON is byte-identical to browser-data.json', embedded === source,
         `embedded ${embedded.length} bytes, source ${source.length} bytes`);
      const D = JSON.parse(embedded);
      // hemisphere: the compute agrees on ~86.6%, and the page fills that in at runtime
      // from D.hemispheres.northFrac; the static HTML carries a "…" placeholder in that
      // slot until JS runs. The check here is on the number the JS will write.
      ok('compute says 86% to 87% live north of the equator',
         D.hemispheres.northFrac > 0.86 && D.hemispheres.northFrac < 0.87,
         `got ${(D.hemispheres.northFrac * 100).toFixed(2)}%`);
      ok('the placeholder that JS fills is present in the raw HTML',
         html.includes('<span data-fill="northFrac">'));
      // pole ratio
      ok('north-pole audience is between 85% and 88%', D.poles.north.frac > 0.85 && D.poles.north.frac < 0.88);
      ok('south-pole audience is between 12% and 15%', D.poles.south.frac > 0.12 && D.poles.south.frac < 0.15);
      // constellations
      ok('all 88 constellations are present (89 rings)', D.constellations.length === 89);
      const oct = D.constellations.find((c) => c.abbrev === 'Oct');
      ok('Octans encloses a celestial pole', oct.enclosesPole === -1);
      ok('Octans is the least-fully-visible ring', D.constellations[0].abbrev === 'Oct');
      // sanity: least seen point is the south pole
      ok('the least-seen point of the sky is at declination -90', Math.abs(D.leastSeen.geometric.dec + 90) < 1e-6);
      // Acrux, from Alexandria, set some time between the fall of Rome and the modern era
      const acrux = D.drift.find((s) => s.id === 'Acrux');
      const alx = acrux.perCity.find((c) => c.city === 'Alexandria');
      ok('Acrux crossing at Alexandria is in the second millennium CE', alx.crossingEpoch > 1000 && alx.crossingEpoch < 1500,
         `got ${alx.crossingEpoch}`);
      const canA = D.drift.find((s) => s.id === 'Canopus').perCity.find((c) => c.city === 'Athens');
      ok('Canopus never rises from Athens', canA.crossingEpoch === null && !canA.visibleNow);
      const canX = D.drift.find((s) => s.id === 'Canopus').perCity.find((c) => c.city === 'Alexandria');
      ok('Canopus rises from Alexandria today', canX.visibleNow && canX.maxAltNow > 0.5);
      // the em-dash gate holds on the shipped page
      ok('no em dashes in shipped page prose', !html.includes('—'));
    }
  }
}

// ── 6. DOM: drive the page and check what a reader actually sees ──────────
if (!process.argv.includes('--no-browser') && !process.argv.includes('--no-page')) {
  section('6. DOM (browser render, interactive)');
  let pw = null;
  try { pw = await import('playwright'); }
  catch { console.log('  playwright not installed; skipping (run with --no-browser to silence).'); }
  if (pw) {
    // The container's Chromium may sit at a version older than the playwright package
    // expects, so pin the executable path if the standard location differs.
    const cands = ['/opt/pw-browsers/chromium-1194/chrome-linux/chrome',
                   '/opt/pw-browsers/chromium-1140/chrome-linux/chrome',
                   process.env.PW_CHROMIUM || ''];
    const exe = cands.find((p) => p && existsSync(p));
    const browser = await pw.chromium.launch(exe ? { executablePath: exe } : undefined);
    try {
      const page = await browser.newPage({ viewport: { width: 1000, height: 1400 } });
      const errs = []; page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
      page.on('pageerror', (e) => errs.push('PAGEERR: ' + e.message));
      const html = readFileSync(R('public/strata/the-sky-nobody-shares/index.html'), 'utf8')
        .replace('<script src="/media/home-banner.js" defer></script>', '')
        .replace('<link rel="stylesheet" href="/fonts/fonts.css" />', '');
      await page.setContent(html, { waitUntil: 'domcontentloaded' });
      await page.waitForTimeout(300);
      const vals = await page.evaluate(() => ({
        northPole: document.querySelector('[data-fill=northPole]').textContent,
        southPole: document.querySelector('[data-fill=southPole]').textContent,
        northFrac: document.querySelector('[data-fill=northFrac]').textContent,
        octLine: document.querySelector('[data-fill=octLine]').textContent,
        canopus: document.querySelector('[data-fill=canopusLine]').textContent,
        rankRows: document.querySelectorAll('.rankrow').length,
        driftOut: document.getElementById('driftOut').textContent,
        audOut: document.getElementById('audienceOut').textContent,
      }));
      ok('page reports 86.6% at the north celestial pole', /^86\.6%$/.test(vals.northPole.trim()), vals.northPole);
      ok('page reports 13.4% at the south celestial pole', /^13\.4%$/.test(vals.southPole.trim()), vals.southPole);
      ok('page reports 86.6% north of the equator', /86\.6%/.test(vals.northFrac), vals.northFrac);
      ok('octLine mentions 13.4%', /13\.4%/.test(vals.octLine));
      ok('canopusLine mentions Alexandria and Athens', /Alexandria/.test(vals.canopus) && /Athens/.test(vals.canopus));
      ok('ranking shows first 20 by default', vals.rankRows === 20, `got ${vals.rankRows}`);
      ok('drift instrument boots on Acrux from Alexandria in 137 CE',
         /Acrux/.test(vals.driftOut) && /Alexandria/.test(vals.driftOut) && /137 CE/.test(vals.driftOut));
      // move the latitude to London and re-read the audience readout
      await page.evaluate(() => {
        const r = document.getElementById('latRange'); r.value = '51.5'; r.dispatchEvent(new Event('input'));
      });
      await page.waitForTimeout(120);
      const londonOut = await page.evaluate(() => document.getElementById('audienceOut').textContent);
      ok('at latitude 51.5 the page names the missing declination band',
         /never rises/.test(londonOut) && /−?38\.5°/.test(londonOut), londonOut.slice(0, 140));
      // switch the ranking to "any" and check top row is different
      await page.evaluate(() => document.querySelector('#rankToggle button[data-mode=any]').click());
      await page.waitForTimeout(60);
      const anyTop = await page.evaluate(() => document.querySelector('.rankrow')?.dataset.abbrev);
      ok('switching to "any" changes the loneliest ring', anyTop && anyTop !== 'Oct', `top ${anyTop}`);
      ok('no JS errors in the browser', errs.length === 0, errs.join(' | '));
    } finally { await browser.close(); }
  }
}

// ── 7. the em-dash gate holds on the stratum front-matter ──────────────────
section('7. The em-dash gate (this study\'s new prose)');
const STRATA = R('src/content/strata/the-sky-nobody-shares.md');
if (existsSync(STRATA)) {
  const md = readFileSync(STRATA, 'utf8');
  ok('stratum markdown has no em dashes', !md.includes('—'));
}

// ── result ─────────────────────────────────────────────────────────────────
console.log(`\n${pass} pass, ${fail} fail`);
process.exit(fail ? 1 : 0);
