// verify.mjs — the Unofficial Bureau, audited.
//
// The joke is real about its data. This checks every load-bearing fact:
//   1. the catalogue the page ships (data.js) is byte-for-byte the verified
//      artifact (stars.json), and stars.json's distances are the HYG parsecs
//      correctly converted to light-years;
//   2. the deposition's named anchor stars carry the values it quoted;
//   3. the spectral glossary and constellation map cover the catalogue;
//   4. the name→star hash is deterministic, total, and spreads names across
//      the whole catalogue (no name is unnameable, none collides by construction);
//   5. the computed record (light-travel year, reply year, BCE handling) is right.
//   node research/name-a-star-badly/verify.mjs
import { readFileSync } from 'fs';
import { STARS, META } from '../../public/strata/name-a-star-badly/data.js';
import {
  CONSTELLATIONS, SPECTRAL, parseSpect, hashName, pickStar,
  yearAgo, computeRecord, NOW_YEAR,
} from '../../public/strata/name-a-star-badly/engine.js';

const here = new URL('.', import.meta.url).pathname;
let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`FAIL   ${name}${extra ? '   ' + extra : ''}`); }
};
const near = (a, b, eps) => Math.abs(a - b) <= eps;

// ── 1. catalogue integrity ────────────────────────────────────────────────
const artifact = JSON.parse(readFileSync(here + 'stars.json', 'utf8'));
ok('data.js count == stars.json count', STARS.length === artifact.stars.length, `${STARS.length}`);
ok('data.js == stars.json (deep equal)', JSON.stringify(STARS) === JSON.stringify(artifact.stars));
ok('META count matches array', META.count === STARS.length);
ok('pc→ly constant is the IAU value', near(META.pc_to_ly, 3.2615637769, 1e-9));

// distances are positive, finite, and the conversion is internally consistent:
// re-derive parsecs from ly and back, must round-trip to the stored ly.
let badDist = 0, badRound = 0;
for (const s of STARS) {
  if (!(s.ly > 0) || !isFinite(s.ly)) badDist++;
  const pc = s.ly / META.pc_to_ly;
  if (!near(Math.round(pc * META.pc_to_ly * 10) / 10, s.ly, 1e-9)) badRound++;
}
ok('every distance positive & finite', badDist === 0, `${badDist} bad`);
ok('ly values round-trip through pc', badRound === 0, `${badRound} bad`);

// ── 2. the deposition's anchor stars ──────────────────────────────────────
const find = (n) => STARS.find((s) => s.name === n);
const anchors = [
  ['Sirius', 8.6, 'CMa'],
  ['Betelgeuse', 498, 'Ori'],   // deposition: "498 light-years"
  ['Deneb', 1412, 'Cyg'],       // deposition: "1,412 light-years"
];
for (const [name, ly, con] of anchors) {
  const s = find(name);
  ok(`anchor: ${name} present`, !!s);
  if (s) {
    ok(`anchor: ${name} distance ≈ ${ly} ly`, near(s.ly, ly, 1.0), `got ${s.ly}`);
    ok(`anchor: ${name} in ${con}`, s.con === con, `got ${s.con}`);
  }
}
// the backwards-Venator pair the deposition leans on must both be in Delphinus
for (const name of ['Sualocin', 'Rotanev']) {
  const s = find(name);
  ok(`Venator pair: ${name} in Delphinus`, !!s && s.con === 'Del');
}

// ── 3. glossary coverage + graceful degradation ───────────────────────────
let unCon = new Set(), unSpect = new Set(), emptyRecord = 0;
for (const s of STARS) {
  if (!CONSTELLATIONS[s.con]) unCon.add(s.con);
  if (!parseSpect(s.spect).letter) unSpect.add(s.spect);
  // every star — even the handful with junk spectral data — must yield a
  // non-empty, honest record without throwing.
  const r = computeRecord(s);
  if (!r.typeLine || !r.headline || !r.constellation) emptyRecord++;
}
ok('every constellation abbrev has a full name', unCon.size === 0, [...unCon].join(','));
ok('≥99% of stars yield a known spectral class', unSpect.size <= 5,
  `${unSpect.size} incomplete: ${[...unSpect].join('|')}`);
ok('every star renders a complete record (incl. incomplete-type ones)', emptyRecord === 0, `${emptyRecord} blank`);
// each glossary class has the fields the certificate reads
ok('spectral glossary well-formed', Object.values(SPECTRAL).every((c) => c.color && c.temp && c.blurb));

// ── 4. the hash: deterministic, total, well-spread ────────────────────────
ok('hash is deterministic', hashName('Ada Lovelace') === hashName('Ada Lovelace'));
ok('hash ignores case & extra spaces',
  hashName('  ada   LOVELACE ') === hashName('Ada Lovelace'));
ok('different names usually differ', hashName('Alice') !== hashName('Bob'));
// every name lands a real star (totality) over a big sample
let unnameable = 0;
const names = [];
for (let i = 0; i < 5000; i++) names.push('Visitor #' + i + ' ' + (i * 7919 % 26));
const buckets = new Array(STARS.length).fill(0);
for (const nm of names) {
  const star = pickStar(nm, STARS);
  if (!star || !star.name) unnameable++;
  else buckets[star.index]++;
}
ok('no name is unnameable', unnameable === 0, `${unnameable} fell through`);
// spread: with 5000 names over 459 stars, expect ~10.9 each; assert no star is
// starved to 0 and none hogs an absurd share (loose, just rules out a broken hash)
const hit = buckets.filter((b) => b > 0).length;
const maxShare = Math.max(...buckets) / names.length;
ok('hash reaches most of the catalogue', hit > STARS.length * 0.9, `${hit}/${STARS.length} stars hit`);
ok('no star hogs the hash', maxShare < 0.05, `max share ${(maxShare * 100).toFixed(2)}%`);

// ── 5. the computed record arithmetic ─────────────────────────────────────
ok('yearAgo: 0 yrs = now', yearAgo(0) === `${NOW_YEAR} CE`);
ok('yearAgo: 26 yrs ago', yearAgo(26) === '2000 CE');
ok('yearAgo: exactly NOW_YEAR back = 1 BCE (no year zero)', yearAgo(NOW_YEAR) === '1 BCE');
ok('yearAgo: past zero into BCE', yearAgo(NOW_YEAR + 99) === '100 BCE');
// Sirius: light left ~8.6 yr ago → 2017 CE; reply round-trip ~17.2 yr → 2043 CE
const rec = computeRecord(find('Sirius'));
ok('Sirius record: light left 2017 CE', rec.lightLeft === '2017 CE', rec.lightLeft);
ok('Sirius record: reply by 2043 CE', rec.replyYear === '2043 CE', rec.replyYear);
ok('Sirius record: white A-type named', /white/.test(rec.typeLine), rec.typeLine.slice(0, 40));
ok('Sirius record: brightest-in-sky band', /brightest/.test(rec.magLine), rec.magLine);
// Deneb (~1412 ly): light left in 614 CE
const den = computeRecord(find('Deneb'));
ok('Deneb record: light left 614 CE', den.lightLeft === '614 CE', den.lightLeft);
// a supergiant luminosity word is recovered from "M2Ib"
ok('parseSpect(M2Ib) = red supergiant',
  (() => { const p = parseSpect('M2Ib'); return p.letter === 'M' && p.lum === 'supergiant'; })());
ok('parseSpect(G2V) = main-sequence', parseSpect('G2V').lum.startsWith('main-sequence'));
ok('parseSpect(A0m) = white, no lum', parseSpect('A0m...').letter === 'A');

console.log(`\n${pass}/${pass + fail} checks pass${fail ? ` — ${fail} FAILED` : ''}`);
process.exit(fail ? 1 : 0);
