#!/usr/bin/env node
/*
 * verify.mjs — offline proof for "The Circles That Draw You".
 *
 * Loads the SAME engine.js the immersive page loads, and checks every claim the page makes:
 *   1. round-trip exactness   IDFT(DFT(z)) = z to machine precision, on random + structured paths
 *   2. linearity of the DFT   DFT(a·x + b·y) = a·DFT(x) + b·DFT(y)
 *   3. Parseval               Σ|z[n]|² = N · Σ|Z[k]|²  (this normalisation)
 *   4. a single circle        a pure k=1 loop has ALL energy in one coefficient → 1 epicycle suffices, exactly
 *   5. truncation error       measured MSE of an M-circle drawing == tail energy of dropped circles (both ways agree)
 *   6. monotone improvement   keeping more circles never increases the error
 *   7. epicycle == IDFT       the epicycle chain with ALL circles lands on the exact samples
 *   8. signed frequency       circle k and its alias k-N evaluate to identical points on the grid
 *
 * Run: node research/fourier-epicycles/verify.mjs
 */
import * as E from '../../public/strata/the-circles-that-draw-you/engine.js';

let pass = 0, fail = 0;
const EPS = 1e-9;
function ok(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok  ${name}${detail ? '  — ' + detail : ''}`); }
  else { fail++; console.log(`FAIL  ${name}${detail ? '  — ' + detail : ''}`); }
}
const maxDiff = (a, b) => { let m = 0; for (let i = 0; i < a.length; i++) m = Math.max(m, Math.hypot(a[i].re - b[i].re, a[i].im - b[i].im)); return m; };

// deterministic pseudo-random path so the run is reproducible
let seed = 0x9e3779b1;
function rnd() { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; seed >>>= 0; return seed / 0xffffffff; }
function randomPath(N) { const z = []; for (let n = 0; n < N; n++) z.push({ re: rnd() * 2 - 1, im: rnd() * 2 - 1 }); return z; }
// a structured "drawing": a noisy ellipse, the kind of thing a finger traces
function ellipsePath(N, a = 2, b = 1) {
  const z = [];
  for (let n = 0; n < N; n++) { const t = E.TAU * n / N; z.push({ re: a * Math.cos(t) + 0.15 * Math.cos(5 * t), im: b * Math.sin(t) + 0.1 * Math.sin(3 * t) }); }
  return z;
}

console.log('The Circles That Draw You — engine verification\n');

// 1. round-trip exactness, several N and several path shapes
for (const N of [8, 16, 60, 128]) {
  for (const [label, z] of [['random', randomPath(N)], ['ellipse', ellipsePath(N)]]) {
    const back = E.idft(E.dft(z));
    ok(`round-trip IDFT(DFT(z)) = z   N=${N} ${label}`, maxDiff(z, back) < 1e-9, `maxΔ=${maxDiff(z, back).toExponential(2)}`);
  }
}

// 2. linearity
{
  const N = 64, x = randomPath(N), y = randomPath(N), a = 1.7, b = -0.4;
  const lhs = E.dft(x.map((v, i) => ({ re: a * v.re + b * y[i].re, im: a * v.im + b * y[i].im })));
  const Zx = E.dft(x), Zy = E.dft(y);
  const rhs = Zx.map((v, i) => ({ re: a * v.re + b * Zy[i].re, im: a * v.im + b * Zy[i].im }));
  ok('DFT is linear  DFT(a·x+b·y) = a·DFT(x)+b·DFT(y)', maxDiff(lhs, rhs) < 1e-9, `maxΔ=${maxDiff(lhs, rhs).toExponential(2)}`);
}

// 3. Parseval for this normalisation
for (const N of [32, 100]) {
  const z = ellipsePath(N), Z = E.dft(z);
  const ePath = E.energyPath(z), eSpec = N * E.energySpec(Z);
  ok(`Parseval  Σ|z|² = N·Σ|Z|²   N=${N}`, Math.abs(ePath - eSpec) < 1e-6 * (1 + ePath), `Σ|z|²=${ePath.toFixed(6)}  N·Σ|Z|²=${eSpec.toFixed(6)}`);
}

// 4. a single circle: z[n] = exp(2πi n/N) is pure frequency 1 → one coefficient, one epicycle
{
  const N = 64; const z = [];
  for (let n = 0; n < N; n++) { const t = E.TAU * n / N; z.push({ re: Math.cos(t), im: Math.sin(t) }); }
  const Z = E.dft(z);
  // exactly Z[1] = 1, the rest 0
  const big = Z.map((v, k) => ({ k, a: E.cAbs(v) })).filter(o => o.a > 1e-9);
  ok('pure circle has exactly one nonzero coefficient', big.length === 1 && big[0].k === 1, `nonzero at k=${big.map(o => o.k).join(',')}`);
  const eps = E.epicycles(Z);
  const { measuredMSE } = E.truncationError(z, eps, 1);
  ok('one epicycle redraws a circle exactly', measuredMSE < 1e-18, `MSE(M=1)=${measuredMSE.toExponential(2)}`);
}

// 5 & 6 & 7. truncation error == tail energy, monotone, full chain == samples
for (const N of [60, 120]) {
  const z = ellipsePath(N), Z = E.dft(z), eps = E.epicycles(Z);
  // full chain lands on samples
  const full = E.truncationError(z, eps, eps.length).measuredMSE;
  ok(`full epicycle chain = exact samples   N=${N}`, full < 1e-18, `MSE(all)=${full.toExponential(2)}`);

  let prev = Infinity, monotone = true, agreeAll = true;
  for (let M = 1; M <= eps.length; M++) {
    const { measuredMSE, predictedMSE } = E.truncationError(z, eps, M);
    // measured MSE (mean squared dist) vs predicted = (tail energy)/N — Parseval per-sample
    const predPerSample = predictedMSE; // dropped Σ|amp|² already equals MSE for an orthonormal-on-the-lap basis
    if (Math.abs(measuredMSE - predPerSample) > 1e-9 * (1 + measuredMSE)) agreeAll = false;
    if (measuredMSE > prev + 1e-12) monotone = false;
    prev = measuredMSE;
  }
  ok(`truncation error = energy of dropped circles   N=${N}`, agreeAll, 'measured MSE == Σ|amp|² over dropped circles, every M');
  ok(`more circles never increase the error   N=${N}`, monotone, 'MSE(M) non-increasing in M');
}

// 8. signed vs unsigned frequency land on the same grid points
{
  const N = 50, k = 40; // alias of k-N = -10
  // build a single high-index exponential and confirm a -10 circle hits the same samples
  const f1 = (n) => ({ re: Math.cos(E.TAU * k * n / N), im: Math.sin(E.TAU * k * n / N) });
  const f2 = (n) => ({ re: Math.cos(E.TAU * (k - N) * n / N), im: Math.sin(E.TAU * (k - N) * n / N) });
  let m = 0; for (let n = 0; n < N; n++) m = Math.max(m, Math.hypot(f1(n).re - f2(n).re, f1(n).im - f2(n).im));
  ok('signed frequency: circle k ≡ circle k−N on the sample grid', m < 1e-9, `maxΔ=${m.toExponential(2)}`);
}

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