// verify-alignment.mjs — every claim /tools/alignment/ makes, and the data under it.
//
//   node verify-alignment.mjs
//
// The kit's own pure maths is tested in public/_kit/horizon.test.mjs. This file is
// about the TOOL: that its catalogue is what the committed SIMBAD responses say, that
// its base rate behaves the way a probability must, that its astronomy lands where
// independent published figures put it, and that the page states nothing it did not
// compute. Several checks are controls: a check that cannot fail is not evidence.
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const R = (f) => path.join(ROOT, 'research/alignment', f);

const sandbox = { globalThis: null }; sandbox.globalThis = sandbox;
vm.runInContext(fs.readFileSync(path.join(ROOT, 'public/_kit/horizon.js'), 'utf8'), vm.createContext(sandbox));
const H = sandbox.AW.horizon;

const cat = JSON.parse(fs.readFileSync(R('catalogue.json'), 'utf8'));
const sites = fs.readFileSync(R('data/wikidata-sites.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
const html = fs.readFileSync(path.join(ROOT, 'public/tools/alignment/index.html'), 'utf8');

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 section = (s) => console.log(`\n${s}`);

// ===========================================================================
section('1. The catalogue is what the committed responses say');
// ===========================================================================
{
  const raw = fs.readFileSync(R('data/simbad-bright.csv'), 'utf8');
  ok('the committed SIMBAD response is a real response, not an error page',
    raw.startsWith('main_id,') && !raw.includes('QUERY_STATUS') && raw.split('\n').length > 100,
    `${raw.split('\n').length - 2} rows`);
  // BOTH committed responses, because the named extras (Thuban, Alcyone, Mintaka)
  // are deliberately fetched outside the magnitude cut and live in the second file.
  // Checking only the first reported a failure that was the check's fault, which is
  // the right way round for a check to be wrong.
  const extrasRaw = fs.readFileSync(R('data/simbad-extras.csv'), 'utf8');
  const both = raw + '\n' + extrasRaw;
  const untraceable = cat.stars.filter((s) => !both.includes(s.id));
  ok('every catalogue star traces to a row in one of the two committed responses',
    untraceable.length === 0, untraceable.length ? untraceable.map((s) => s.id).join(', ') : `${cat.stars.length} stars`);
  ok('and the named extras really did come from outside the magnitude cut',
    ['Thuban', 'Alcyone', 'Mintaka'].every((n) => {
      const s = cat.stars.find((x) => x.name === n);
      return s && extrasRaw.includes(s.id);
    }));
  ok('no galaxy or supernova survived the filter',
    cat.stars.every((s) => s.otype !== 'G' && s.otype !== 'SN*'),
    `${cat.droppedNonStellar.length} dropped: ${cat.droppedNonStellar.map((d) => d.id).join(', ')}`);
}
{
  // The stars an alignment claim is actually made about must be present. This is the
  // check that would have caught the first version of the type filter, which threw
  // away Aldebaran and Deneb because it was an allowlist assembled from memory.
  const need = ['Sirius', 'Vega', 'Arcturus', 'Capella', 'Rigel', 'Aldebaran', 'Deneb',
    'Antares', 'Spica', 'Regulus', 'Fomalhaut', 'Betelgeuse', 'Thuban', 'Polaris', 'Alcyone'];
  const missing = need.filter((n) => !cat.stars.some((s) => s.name === n));
  ok('every star an alignment claim is normally made about is present', missing.length === 0,
    missing.length ? `missing ${missing.join(', ')}` : `${need.length} checked`);
}
{
  // No two catalogue entries may sit closer than the merge radius, or the base rate's
  // target count double-counts one place on the sky. Alpha Centauri arrives three
  // times from SIMBAD and is the case this exists for.
  let worstPair = null, closest = 1e9;
  for (let i = 0; i < cat.stars.length; i++) {
    for (let j = i + 1; j < cat.stars.length; j++) {
      const a = cat.stars[i], b = cat.stars[j];
      const d = Math.acos(Math.max(-1, Math.min(1,
        Math.sin(a.dec * Math.PI / 180) * Math.sin(b.dec * Math.PI / 180) +
        Math.cos(a.dec * Math.PI / 180) * Math.cos(b.dec * Math.PI / 180) *
        Math.cos((a.ra - b.ra) * Math.PI / 180)))) * 180 / Math.PI;
      if (d < closest) { closest = d; worstPair = `${a.name} / ${b.name}`; }
    }
  }
  ok('no two catalogue entries are closer together than the merge radius',
    closest >= cat.mergeRadiusDeg, `closest pair ${worstPair} at ${closest.toFixed(4)} deg`);
  ok('CONTROL: the merge actually did something, so the check above is not vacuous',
    cat.mergedComponents.length > 0,
    `${cat.mergedComponents.length} merged, including ${cat.mergedComponents[0].dropped}`);
}
{
  ok('every star carries a proper motion field', cat.stars.every((s) => Number.isFinite(s.pmRaMasPerYr) && Number.isFinite(s.pmDecMasPerYr)));
  const fast = cat.stars.filter((s) => Math.hypot(s.pmRaMasPerYr, s.pmDecMasPerYr) > 1000);
  ok('and several of them move fast enough that ignoring it would matter',
    fast.length >= 3, `${fast.length} stars over 1000 mas/yr: ${fast.slice(0, 4).map((s) => s.name).join(', ')}`);
}

// ===========================================================================
section('2. The base rate behaves the way a probability must');
// ===========================================================================
const buildTargets = (lat, year, skyline, mag, moon) => {
  const eps = H.meanObliquity(H.jdFromYear(year));
  const out = [];
  const add = (dec, kind) => {
    const h = H.geometricAltitudeAtSkyline(skyline, kind);
    const r = H.risingAzimuth(dec, lat, h);
    if (r === null) return;
    out.push(r); out.push(360 - r);
  };
  add(eps, 'sun'); add(-eps, 'sun'); add(0, 'sun');
  if (moon) { add(eps + 5.145, 'moon'); add(-(eps + 5.145), 'moon'); add(eps - 5.145, 'moon'); add(-(eps - 5.145), 'moon'); }
  for (const s of cat.stars.filter((s) => s.vmag !== null && s.vmag <= mag)) {
    add(H.epochDeclination(s, year).dec, 'star');
  }
  return out;
};
{
  const t = buildTargets(51.1789, -2500, 0.5, 3.05, true);
  let mono = true, prev = -1;
  for (let tol = 0.1; tol <= 5; tol += 0.1) {
    const p = H.baseRate(t, tol).probability;
    if (p < prev - 1e-12) mono = false;
    prev = p;
  }
  ok('the base rate rises monotonically with tolerance', mono);
  ok('and never exceeds one', H.baseRate(t, 90).probability <= 1 + 1e-12);
}
{
  // The instrument's whole argument, as a test: a longer target list is a higher
  // base rate, at fixed tolerance.
  const lat = 51.1789, y = -2500, sk = 0.5;
  const sunOnly = H.baseRate(buildTargets(lat, y, sk, -99, false), 1).probability;
  const withMoon = H.baseRate(buildTargets(lat, y, sk, -99, true), 1).probability;
  const mag2 = H.baseRate(buildTargets(lat, y, sk, 2.0, true), 1).probability;
  const mag3 = H.baseRate(buildTargets(lat, y, sk, 3.05, true), 1).probability;
  ok('accepting more targets strictly raises the base rate',
    sunOnly < withMoon && withMoon < mag2 && mag2 < mag3,
    `sun ${(sunOnly * 100).toFixed(1)}% < +moon ${(withMoon * 100).toFixed(1)}% < mag2 ${(mag2 * 100).toFixed(1)}% < mag3 ${(mag3 * 100).toFixed(1)}%`);
  ok('the Sun alone at one degree is a genuinely demanding target list',
    sunOnly < 0.12, `${(sunOnly * 100).toFixed(1)}%`);
  ok('and the generous list is not evidence of anything',
    mag3 > 0.5, `${(mag3 * 100).toFixed(1)}% of all bearings hit something`);
}
{
  // The headline the page prints, stated as a check so it cannot drift: with the
  // full list and a two-degree tolerance a random bearing hits something more often
  // than not.
  const p = H.baseRate(buildTargets(51.1789, -2500, 0.5, 3.05, true), 2).probability;
  ok('with everything to magnitude 3 and two degrees of slop, a random bearing usually hits something',
    p > 0.5, `${(p * 100).toFixed(1)}%`);
}

// ===========================================================================
section('3. Against published figures the tool did not compute');
// ===========================================================================
{
  // Stonehenge. The solstitial axis is conventionally given near 50 degrees, and the
  // point of this check is that the tool reaches it from latitude, epoch, obliquity
  // and refraction alone, with no site-specific number anywhere in it.
  const lat = sites.find((s) => s.label === 'Stonehenge').lat;
  const eps = H.meanObliquity(H.jdFromYear(-2500));
  const az = H.risingAzimuth(eps, lat, H.geometricAltitudeAtSkyline(0.5, 'sun'));
  ok('June solstice sunrise at Stonehenge in 2500 BC lands on the conventional axis',
    az > 48 && az < 51.5, `${az.toFixed(2)} deg, against the usually quoted 49 to 51`);
  ok('CONTROL: the same computation at a different latitude does NOT land there',
    Math.abs(H.risingAzimuth(eps, 20, H.geometricAltitudeAtSkyline(0.5, 'sun')) - az) > 8,
    `at latitude 20 it is ${H.risingAzimuth(eps, 20, H.geometricAltitudeAtSkyline(0.5, 'sun')).toFixed(2)} deg`);
}
{
  // The obliquity was larger in antiquity, so the solstice sun rose further north.
  const then = H.meanObliquity(H.jdFromYear(-2500)), now = H.meanObliquity(H.J2000);
  ok('the obliquity was larger in 2500 BC than today, by about half a degree',
    then - now > 0.4 && then - now < 0.7, `${then.toFixed(4)} vs ${now.toFixed(4)} deg`);
}
{
  // Thuban, as an end-to-end test of precession inside the tool's own catalogue
  // entry rather than a hand-typed position.
  const th = cat.stars.find((s) => s.name === 'Thuban');
  let best = 1e9, bestYear = null;
  for (let y = -3500; y <= -2000; y++) {
    const d = 90 - H.epochDeclination(th, y).dec;
    if (d < best) { best = d; bestYear = y; }
  }
  ok('the catalogue entry for Thuban reproduces its turn as pole star in the 28th century BC',
    bestYear < -2600 && bestYear > -2900 && best < 0.2,
    `closest ${-bestYear} BC at ${(best * 60).toFixed(1)} arcmin`);
}
{
  // The skyline claim the page makes in prose.
  const lat = 51.1789;
  const flat = H.risingAzimuth(20, lat, H.geometricAltitudeAtSkyline(0, 'sun'));
  const hill = H.risingAzimuth(20, lat, H.geometricAltitudeAtSkyline(4, 'sun'));
  ok('four degrees of skyline moves a rising bearing by more than a degree',
    Math.abs(hill - flat) > 1, `${Math.abs(hill - flat).toFixed(2)} deg`);
}

// ===========================================================================
section('4. The sites, and the page');
// ===========================================================================
{
  ok('every preset site carries the search description that identified it',
    sites.every((s) => s.searchDescription && s.searchDescription.length > 5));
  ok('and a plausible position', sites.every((s) => Math.abs(s.lat) <= 66 && Math.abs(s.lon) <= 180));
  const sh = sites.find((s) => s.label === 'Stonehenge');
  ok('Stonehenge is where Stonehenge is',
    Math.abs(sh.lat - 51.1789) < 0.01 && Math.abs(sh.lon + 1.8262) < 0.01,
    `${sh.lat.toFixed(4)}, ${sh.lon.toFixed(4)}`);
}
{
  ok('the page loads the shared kit by URL rather than shipping a copy',
    html.includes('src="/_kit/horizon.js"') && !html.includes('function risingAzimuth'));
  ok('the page carries the SIMBAD acknowledgement required by CDS',
    html.includes('SIMBAD') && html.includes('CDS'));
  ok('the page states the catalogue size it actually ships',
    html.includes(`${cat.count} stars`), `${cat.count}`);
  ok('the page names its own verifier and the kit test file',
    html.includes('verify-alignment') && html.includes('horizon.test.mjs'));
  ok('the page carries the canonical way out', html.includes('aw-wayout'));
  ok('the page carries the site top bar', html.includes('/media/home-banner.js'));
  ok('no unfilled template placeholder survived', !/__[A-Z_]+__/.test(html));
}

console.log(`\n${pass}/${pass + fail} checks passed`);
if (fail) { console.log(`${fail} FAILED`); process.exit(1); }
