#!/usr/bin/env node
// verify.mjs -- one command that re-runs the whole check ladder for the aliquot
// frontier and fails loudly on any mismatch. The census (100,000 starts, ~60-90s)
// and the Lehmer-five deep trajectories (~1-2 minutes) are re-computed from
// scratch by the census.mjs and lehmer.mjs steps, so a reader with only this
// repo can reproduce every number the page prints.
//
//   node research/aliquot-frontier/verify.mjs
//
// The exit code is 0 only if EVERY census check passes and EVERY headline number
// this file asserts matches the JSON the page reads.

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));

// Re-run the census (writes data/census.json and prints its own checks).
execSync(`node ${join(HERE, 'census.mjs')} --nmax 100000 --depth 500 --term 1e15`, { stdio: 'inherit' });
const census = JSON.parse(readFileSync(join(HERE, 'data', 'census.json'), 'utf8'));

// Re-run the Lehmer deep trajectories (writes data/lehmer.json).
execSync(`node ${join(HERE, 'lehmer.mjs')} --depth 200 --term 1e40`, { stdio: 'inherit' });
const lehmer = JSON.parse(readFileSync(join(HERE, 'data', 'lehmer.json'), 'utf8'));

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

// Every headline number the page states, asserted here so a change in the
// upstream census or the deep runner can never silently rewrite the prose.
const asserts = [];
const assert = (name, got, want) => {
  const ok = JSON.stringify(got) === JSON.stringify(want);
  asserts.push({ name, ok, got, want });
  console.log(`  ${ok ? 'OK ' : 'BAD'}  ${name}: ${JSON.stringify(got)}`);
  if (!ok) console.log(`         wanted ${JSON.stringify(want)}`);
};

assert('census parameters were (N=100000, D=500, T=1e15)',
  [census.params.N_MAX, census.params.DEPTH, census.params.TERM_CAP],
  [100000, 500, '1000000000000000']);

assert('perfect numbers found under 100,000 are exactly {6, 28, 496, 8128}',
  census.perfectFound, ['6', '28', '496', '8128']);

// The classical five smallest amicable pairs (Euler + earlier). Verified by
// running the census; this test protects the ordering the page prints.
assert('the five smallest amicable pairs found in the census',
  census.amicablePairs.slice(0, 5).map((p) => [p.a, p.b]),
  [['220', '284'], ['1184', '1210'], ['2620', '2924'], ['5020', '5564'], ['6232', '6368']]);

// The sociable cycles found in the census: the length-5 at 12496 (Poulet 1918)
// and the length-28 at 14316 (Poulet 1918). These are the only sociable cycles
// whose smallest member is under 100,000. (The length-4 cycles all have a
// smallest member above 10^6.)
const soc = census.sociableCycles;
assert('exactly two sociable cycles have their smallest member <= 100,000',
  soc.length, 2);
assert('the sociable cycle of length 5 with smallest 12496',
  { length: soc[0].length, min: soc[0].min, members: soc[0].members },
  { length: 5, min: '12496', members: ['12496', '14288', '15472', '14536', '14264'] });
assert('the sociable cycle of length 28 with smallest 14316',
  { length: soc[1].length, min: soc[1].min, memberCount: soc[1].members.length },
  { length: 28, min: '14316', memberCount: 28 });

// The five classical Lehmer starts are open at this census budget.
const openSet = new Set(census.openUnder1000.map((o) => o.n));
assert('each of the Lehmer five is open at census budget',
  [276, 552, 564, 660, 966].map((n) => openSet.has(n)),
  [true, true, true, true, true]);

// The Lehmer starts each reach a terminal term > 10^14 within the census budget.
for (const n of [276, 552, 564, 660, 966]) {
  const rec = census.openUnder1000.find((o) => o.n === n);
  const term = BigInt(rec.terminalTerm);
  const ok = term > 10n ** 14n;
  asserts.push({ name: `Lehmer ${n}: terminal term > 10^14`, ok, got: rec.terminalTerm, want: '> 10^14' });
  console.log(`  ${ok ? 'OK ' : 'BAD'}  Lehmer ${n}: terminal term ${rec.terminalTerm} > 10^14`);
}

// From the deep runner: 138 terminates within 200 steps.
{
  const r138 = lehmer.starts.find((s) => s.start === '138');
  assert('deep runner: 138 terminates within 200 steps',
    { ended: r138.ended, terms: r138.terms }, { ended: 'terminates', terms: r138.terms });
  assert('deep runner: 138 peaks between 10^11 and 10^12',
    r138.peakLog10 >= 11 && r138.peakLog10 <= 12, true);
}

// From the deep runner: every Lehmer start does NOT terminate within the deep
// budget (depth 200 OR term 10^40); each ends by hitting one of those caps.
for (const n of ['276', '552', '564', '660', '966']) {
  const r = lehmer.starts.find((s) => s.start === n);
  const notEnded = r && (r.ended === 'depth-cap' || r.ended === 'term-cap');
  asserts.push({ name: `deep runner: Lehmer ${n} still climbing at deep-budget cap`, ok: notEnded, got: r && r.ended, want: 'depth-cap or term-cap' });
  console.log(`  ${notEnded ? 'OK ' : 'BAD'}  deep runner: Lehmer ${n} still climbing (ended=${r && r.ended}, peak ~10^${r && r.peakLog10.toFixed(1)})`);
}

const badAsserts = asserts.filter((a) => !a.ok);
const passN = asserts.filter((a) => a.ok).length;
console.log(`\n  research/aliquot-frontier -- headline asserts: ${passN}/${asserts.length} pass\n`);
if (badAsserts.length) process.exit(1);
