// verify.mjs — re-derive every headline number in the stratum from scratch.
//
//   node research/ulam-hidden-signal/verify.mjs
//
// Nothing here trusts a stored answer. The sequence is generated two independent
// ways and cross-checked; the hidden frequency alpha is found by a BLIND
// multi-resolution search (never told where it is); the signal statistics are
// recomputed; and the whole thing is anchored to OEIS A002858's published prefix.
// Every assertion reaches the exact range it claims. Reports N/N.

import {
  ulamUpTo, ulamDefinitional, fourierMag, findAlphaBootstrap, signalStats,
} from './engine.mjs';

let pass = 0, fail = 0;
const ok = (cond, msg) => { (cond ? pass++ : fail++); console.log(`  ${cond ? 'ok  ' : 'FAIL'} ${msg}`); };

// OEIS A002858 (the Ulam sequence), first 60 terms, transcribed from oeis.org/A002858.
const OEIS_A002858_60 = [
  1, 2, 3, 4, 6, 8, 11, 13, 16, 18, 26, 28, 36, 38, 47, 48, 53, 57, 62, 69,
  72, 77, 82, 87, 97, 99, 102, 106, 114, 126, 131, 138, 145, 148, 155, 175, 177, 180, 182, 189,
  197, 206, 209, 219, 221, 236, 238, 241, 243, 253, 258, 260, 273, 282, 309, 316, 319, 324, 339, 341,
];

console.log('THE ULAM SEQUENCE (A002858) AND ITS HIDDEN SIGNAL — reproduction\n');

// -- 1. The rule, two independent ways, anchored to OEIS --------------------
console.log('[1] the generating rule');
const sieve = ulamUpTo(400);               // representation-count sieve
const def   = ulamDefinitional(2000);      // definitional, no sieve
ok(OEIS_A002858_60.every((v, i) => v === sieve[i]),
   `sieve matches OEIS A002858 for all 60 published terms`);
ok(OEIS_A002858_60.every((v, i) => v === def[i]),
   `definitional generator matches OEIS A002858 for all 60 published terms`);
const s300k = ulamUpTo(300000);
ok(def.every((v, i) => v === s300k[i]) && def.length === 2000,
   `two independent generators agree on all first 2000 terms (sieve vs definitional)`);
// the density people quote (~0.074) — reported, not asserted to a myth value
const density = s300k.length / 300000;
console.log(`     observed density up to 300000: ${density.toFixed(5)} (commonly quoted ~0.074)`);

// -- 2. Find the hidden frequency alpha, blind ------------------------------
console.log('\n[2] the hidden frequency alpha (found blind, never assumed)');
const { alpha, history } = findAlphaBootstrap();
for (const h of history)
  console.log(`     up to ${String(h.limit).padStart(8)}: N=${String(h.n).padStart(6)}  alpha=${h.alpha.toFixed(10)}  |A|=${h.mag.toFixed(4)}`);
const ALPHA_PUB = 2.5714474995;            // Steinerberger, Exp. Math. 2017
ok(Math.abs(alpha - ALPHA_PUB) < 1e-6,
   `blind search recovers alpha=${alpha.toFixed(10)} within 1e-6 of published ${ALPHA_PUB}`);

// -- 3. The peak is REAL: it stays sharp, noise would not -------------------
console.log('\n[3] the peak is a real resonance, not a fluctuation');
const s1M = ulamUpTo(1000000);             // 74084 terms
const onPeak  = fourierMag(s1M, alpha);
const control = fourierMag(s1M, alpha + 0.037);   // an arbitrary off-peak frequency
const noiseFloor = 1 / Math.sqrt(s1M.length);      // scale of a random |A| for N points
ok(onPeak > 0.75,
   `on-peak magnitude |A(alpha)| = ${onPeak.toFixed(4)} stays ~0.79 at N=${s1M.length} (does not decay)`);
ok(control < 10 * noiseFloor,
   `off-peak control |A| = ${control.toFixed(4)} sits at the noise floor (~${noiseFloor.toFixed(4)})`);
ok(onPeak / Math.max(control, 1e-9) > 100,
   `on-peak / off-peak contrast = ${(onPeak / Math.max(control, 1e-9)).toFixed(0)}x`);

// -- 4. The signal itself: cos(alpha a_n) < 0 for all but a handful ---------
console.log('\n[4] the signal — cos(alpha a_n) is negative for almost every term');
const st = signalStats(s1M, alpha);
console.log(`     mean cos(alpha a_n) = ${st.meanCos.toFixed(5)}   (a spread-out set would give ~0)`);
ok(st.meanCos < -0.78 && st.meanCos > -0.81,
   `mean cos(alpha a_n) = ${st.meanCos.toFixed(5)} (Steinerberger reports ~ -0.79)`);
ok(st.fractionNeg > 0.9999,
   `${(100 * st.fractionNeg).toFixed(4)}% of all ${st.n} terms below 10^6 satisfy cos(alpha a_n) < 0`);
const EXPECTED_EXC = [2, 3, 47, 69];
ok(st.exceptions.length === 4 && EXPECTED_EXC.every((v, i) => v === st.exceptions[i]),
   `the ONLY exceptions among all ${st.n} terms below 10^6 are {${st.exceptions.join(', ')}}`);
console.log(`     lambda = 2*pi/alpha = ${(2 * Math.PI / alpha).toFixed(6)} (the wavelength the numbers avoid landing on)`);

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