#!/usr/bin/env node
// verify-sgp4-port.mjs — check this project's JavaScript SGP4 against David Vallado's
// own C++ reference, compiled from his unmodified source on this machine.
//
// The chain of trust this establishes, in order:
//
//   1. Vallado's SGP4.cpp is used byte-for-byte as CelesTrak distributes it. Only the
//      driver (tools/refbuild/refdriver.cpp) is ours, because his own TestSGP4.cpp is
//      MSVC-only and patching a reference to make it build is how references stop being
//      references.
//   2. That compiled reference is checked against Vallado's OWN distributed STK
//      ephemeris files (TestSGP4/*.e), which he generated independently of this machine.
//      If our build of his code disagrees with his published output, everything below
//      is worthless and this script says so first.
//   3. Only then is the JavaScript port compared against it: on the 32-case official
//      verification suite, and on every near-earth object in the pinned live catalogue.
//
// Run:  node research/the-dark-has-a-ceiling/verify-sgp4-port.mjs

import { execFileSync } from 'node:child_process';
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 REFDIR = join(HERE, 'tools', 'refbuild');
const REFBIN = join(REFDIR, 'refdriver');
const VERTLE = join(REFDIR, 'SGP4-VER.TLE');
const CATALOGUE = join(HERE, 'data', 'raw', 'celestrak-active.tle');

let checks = 0;
let failures = 0;
function ok(cond, label, detail = '') {
  checks++;
  if (cond) {
    console.log(`  ok   ${label}${detail ? '  ' + detail : ''}`);
  } else {
    failures++;
    console.log(`  FAIL ${label}${detail ? '  ' + detail : ''}`);
  }
}

// ---------------------------------------------------------------------------
console.log('\n=== 0. the reference binary ===');
if (!existsSync(REFBIN)) {
  console.log(`  refdriver not built at ${REFBIN}`);
  console.log(`  build it with:  cd ${REFDIR} && g++ -O2 -w -o refdriver refdriver.cpp SGP4.cpp -I.`);
  console.log(`  (SGP4.cpp/SGP4.h come from https://celestrak.org/software/vallado/cpp.zip;`);
  console.log(`   tools/fetch-sources.mjs fetches and places them.)`);
  process.exit(2);
}
ok(true, 'Vallado reference compiled and present');

// ---------------------------------------------------------------------------
// Step 2: our build of his code vs HIS published ephemeris.
console.log('\n=== 1. our build of the reference vs Vallado\'s own published ephemeris ===');

function runRef(args) {
  return execFileSync(REFBIN, args, { maxBuffer: 1 << 30, encoding: 'utf8' });
}

// SGP4-VER.TLE cases are propagated with wgs72 and afspc mode, which is what the
// distributed .e files were generated with.
const refVerOut = runRef(['ver', VERTLE, 'wgs72', 'a']);
const refVerRows = refVerOut.trim().split('\n').filter((l) => !l.includes('INIT_ERROR'));

// Parse one of Vallado's STK .e files: "EphemerisTimePosVel" then t x y z vx vy vz.
function parseE(path) {
  const txt = readFileSync(path, 'utf8');
  const start = txt.indexOf('EphemerisTimePosVel');
  if (start < 0) return [];
  const rows = [];
  for (const line of txt.slice(start).split(/\r?\n/).slice(1)) {
    const p = line.trim().split(/\s+/).map(Number);
    if (p.length === 7 && p.every((x) => Number.isFinite(x))) rows.push(p);
  }
  return rows;
}

const refBySat = new Map();
for (const line of refVerRows) {
  const p = line.trim().split(/\s+/);
  if (p.length < 9) continue;
  const sat = p[0];
  if (!refBySat.has(sat)) refBySat.set(sat, []);
  refBySat.get(sat).push(p.slice(1, 8).map(Number));
}

let eFilesCompared = 0;
let worstEDiff = 0;
let worstEWhere = '';
for (const sat of refBySat.keys()) {
  const ePath = join(REFDIR, `${sat}.e`);
  if (!existsSync(ePath)) continue;
  const theirs = parseE(ePath);
  const ours = refBySat.get(sat);
  if (!theirs.length) continue;
  eFilesCompared++;
  // Their t is in SECONDS from the file's scenario epoch; ours is minutes from the
  // element-set epoch. Match on position by index where the counts allow, using the
  // seconds/60 = minutes correspondence.
  const byMin = new Map(ours.map((r) => [Math.round(r[0] * 1e6) / 1e6, r]));
  for (const row of theirs) {
    const tmin = Math.round((row[0] / 60) * 1e6) / 1e6;
    const mine = byMin.get(tmin);
    if (!mine) continue;
    for (let k = 1; k <= 3; k++) {
      const d = Math.abs(mine[k] - row[k]);
      if (d > worstEDiff) { worstEDiff = d; worstEWhere = `sat ${sat} t=${tmin} axis ${k}`; }
    }
  }
}
// Vallado's .e files print 8 decimal places; agreement at that printed precision is
// the most the comparison can assert.
ok(eFilesCompared > 0, 'Vallado STK ephemeris files found to compare against', `${eFilesCompared} files`);
ok(worstEDiff < 1e-6, 'our build reproduces his published ephemeris',
   `worst |dr| = ${worstEDiff.toExponential(3)} km (${worstEWhere})`);

// ---------------------------------------------------------------------------
console.log('\n=== 2. the JavaScript port vs the reference, official verification suite ===');
const { twoline2satrec, propagate, parseTleFile } = await import('./lib/sgp4.mjs');

function compareAgainst(refRows, records, opsmode) {
  // refRows: array of [satnum, t, x,y,z, vx,vy,vz, err]
  const bySat = new Map();
  for (const r of refRows) {
    if (!bySat.has(r[0])) bySat.set(r[0], []);
    bySat.get(r[0]).push(r);
  }
  let worstR = 0, worstV = 0, worstWhere = '', compared = 0, skippedDeep = 0, skippedErr = 0;
  const deepSats = [];
  for (const rec of records) {
    const satrec = twoline2satrec(rec.line1, rec.line2, 'wgs72', opsmode);
    const rows = bySat.get(satrec.satnum);
    if (!rows) continue;
    if (satrec.deepSpace) { skippedDeep++; deepSats.push({ sat: satrec.satnum, period: satrec.periodMin }); continue; }
    for (const row of rows) {
      const refErr = row[8];
      const st = propagate(satrec, row[1]);
      if (refErr !== 0 || st.error !== 0) {
        // Both sides erroring on the same case is agreement, not a comparison.
        if (refErr !== 0 && st.error !== 0) { skippedErr++; continue; }
        worstWhere = `sat ${satrec.satnum} t=${row[1]} error mismatch ref=${refErr} js=${st.error}`;
        worstR = Infinity;
        continue;
      }
      compared++;
      for (let k = 0; k < 3; k++) {
        const dr = Math.abs(st.r[k] - row[2 + k]);
        const dv = Math.abs(st.v[k] - row[5 + k]);
        if (dr > worstR) { worstR = dr; worstWhere = `sat ${satrec.satnum} t=${row[1]}`; }
        if (dv > worstV) worstV = dv;
      }
    }
  }
  return { worstR, worstV, worstWhere, compared, skippedDeep, skippedErr, deepSats };
}

const verRecords = parseTleFile(readFileSync(VERTLE, 'utf8'));
const verRefRows = refVerOut.trim().split('\n')
  .filter((l) => !l.includes('INIT_ERROR'))
  .map((l) => { const p = l.trim().split(/\s+/); return [p[0], ...p.slice(1).map(Number)]; });

const verRes = compareAgainst(verRefRows, verRecords, 'a');
ok(verRes.compared > 0, 'verification-suite states compared', `${verRes.compared} state vectors`);
ok(verRes.worstR < 1e-9, 'position agrees with the reference',
   `worst |dr| = ${verRes.worstR.toExponential(3)} km (${verRes.worstWhere})`);
ok(verRes.worstV < 1e-12, 'velocity agrees with the reference',
   `worst |dv| = ${verRes.worstV.toExponential(3)} km/s`);
console.log(`       (${verRes.skippedDeep} deep-space element sets refused by the port, as designed;`);
console.log(`        ${verRes.skippedErr} cases where both implementations raise the same error)`);
ok(verRes.deepSats.every((d) => d.period >= 225),
   'every refused element set really is deep-space (period >= 225 min)',
   verRes.deepSats.map((d) => `${d.sat}:${d.period.toFixed(0)}m`).join(' '));

// ---------------------------------------------------------------------------
console.log('\n=== 3. the JavaScript port vs the reference, the whole live catalogue ===');
if (!existsSync(CATALOGUE)) {
  console.log(`  catalogue snapshot missing at ${CATALOGUE}; run tools/fetch-sources.mjs`);
  failures++;
} else {
  // A day either side of epoch at irregular offsets, so no step can coincide with a
  // period and hide a phase error.
  const tsinces = [-1440, -613.7, -97.3, 0, 41.9, 233.1, 719.5, 1440];
  const catRefOut = runRef(['batch', CATALOGUE, 'wgs72', 'i', tsinces.join(',')]);
  const catRefRows = catRefOut.trim().split('\n')
    .filter((l) => !l.includes('INIT_ERROR'))
    .map((l) => { const p = l.trim().split(/\s+/); return [p[0], ...p.slice(1).map(Number)]; });
  const catRecords = parseTleFile(readFileSync(CATALOGUE, 'utf8'));
  const catRes = compareAgainst(catRefRows, catRecords, 'i');
  ok(catRes.compared > 1e5, 'catalogue states compared', `${catRes.compared.toLocaleString('en-US')} state vectors from ${catRecords.length.toLocaleString('en-US')} element sets`);
  ok(catRes.worstR < 1e-9, 'position agrees across the live catalogue',
     `worst |dr| = ${catRes.worstR.toExponential(3)} km (${catRes.worstWhere})`);
  ok(catRes.worstV < 1e-12, 'velocity agrees across the live catalogue',
     `worst |dv| = ${catRes.worstV.toExponential(3)} km/s`);
  console.log(`       (${catRes.skippedDeep.toLocaleString('en-US')} deep-space element sets refused by the port;`);
  console.log(`        ${catRes.skippedErr.toLocaleString('en-US')} cases where both implementations raise the same error)`);
}

// ---------------------------------------------------------------------------
console.log(`\n${checks} checks, ${failures} failed\n`);
process.exit(failures === 0 ? 0 : 1);
