#!/usr/bin/env node
// One command that re-runs the whole check ladder and fails loudly on any
// mismatch. The heavy data acquisition (fetching katlas, running SnapPy) is in
// the Python/shell steps documented in README.md; this re-derives every claim
// the page makes from the committed data files, so a reader with only this repo
// can confirm the page in a few seconds.
//
//   node research/perko-pair/verify.mjs

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

const HERE = dirname(fileURLToPath(import.meta.url));

// census.mjs writes data/census.json and prints every check; run it and read back.
execSync(`node ${join(HERE, 'census.mjs')}`, { stdio: 'inherit' });
const census = JSON.parse(readFileSync(join(HERE, 'data', 'census.json'), 'utf8'));

const failed = census.checks.filter((c) => !c.ok);
console.log(`\n  research/perko-pair — ${census.checks.length - failed.length}/${census.checks.length} checks pass`);
if (failed.length) {
  console.log('  FAILURES:');
  for (const f of failed) console.log(`   - ${f.name}  [${f.detail}]`);
  process.exit(1);
}

// A couple of headline numbers the page states, asserted here so a change in the
// data can never silently rewrite the prose.
const assert = (name, got, want) => {
  const ok = JSON.stringify(got) === JSON.stringify(want);
  console.log(`  ${ok ? 'OK ' : 'BAD'}  ${name}: ${JSON.stringify(got)}`);
  if (!ok) { console.log(`        wanted ${JSON.stringify(want)}`); process.exitCode = 1; }
};
assert('tables run to 165 / 165 / 166 (Atlas / KnotInfo / SnapPy)',
  [census.tableSizes.knotAtlas, census.tableSizes.knotInfo, census.tableSizes.snappy], [165, 165, 166]);
assert('the one duplicate is 10_161 = 10_162 in the old numbering', census.doubled[0][1], ['10_161', '10_162']);
assert('seven names denote different knots in SnapPy than in the modern tables', census.disagreements.length, 7);
assert('Alexander-polynomial coincidences among the 249 distinct knots', census.census.alexanderPairs, 40);
assert('Jones-polynomial coincidences among the 249 distinct knots', census.census.jonesPairs, 14);
assert('pairs neither Alexander nor Jones can separate', census.census.bothPairs, 5);
assert('the volume ladder leaves exactly one pair unseparated (9_42, 10_132)',
  census.ladder.find((l) => l.label === 'hyperbolic volume').pairs, 1);
assert('the isometry signature separates every pair it is defined on', census.ladder.find((l) => l.label.startsWith('isometry')).pairs, 0);
