// verify.mjs — the show-the-check for the spectral Helmholtz–Hodge decomposition.
// Every claim the immersive page makes about the theorem is asserted here against the
// exact linear algebra, on analytic test fields whose answers are known in closed form.
//   node research/hodge-field/verify.mjs
import { decompose, inner, fdDivCurl, sampleField } from './hodge.mjs';

let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
function ok(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok    ${name}${detail ? '   ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '   ' + detail : ''}`); }
}
const l2 = (x, y) => Math.sqrt(inner(x, y, x, y));
const rms = a => { let s = 0; for (const v of a) s += v * v; return Math.sqrt(s / a.length); };

const N = 64;

// ---------------------------------------------------------------- reconstruction & orthogonality
for (const kind of ['gradient', 'curl', 'harmonic', 'mixed', 'saddle']) {
  const { Fx, Fy } = sampleField(kind, N);
  const D = decompose(Fx, Fy, N);
  const n2 = N * N;

  // 1. EXACT reconstruction: F = grad + curl + harmonic, to machine precision
  let maxErr = 0;
  for (let p = 0; p < n2; p++) {
    maxErr = Math.max(maxErr,
      Math.abs(Fx[p] - (D.gradX[p] + D.curlX[p] + D.harmX)),
      Math.abs(Fy[p] - (D.gradY[p] + D.curlY[p] + D.harmY)));
  }
  ok(`[${kind}] reconstruction F = ∇φ + curl + harmonic is exact`, maxErr < 1e-9, `maxErr=${maxErr.toExponential(2)}`);

  // 2. ORTHOGONALITY: the three parts are mutually L²-orthogonal (the heart of the theorem)
  const harmXarr = new Float64Array(n2).fill(D.harmX), harmYarr = new Float64Array(n2).fill(D.harmY);
  const nF = l2(Fx, Fy) || 1;
  const gc = inner(D.gradX, D.gradY, D.curlX, D.curlY) / (nF * nF);
  const gh = inner(D.gradX, D.gradY, harmXarr, harmYarr) / (nF * nF);
  const ch = inner(D.curlX, D.curlY, harmXarr, harmYarr) / (nF * nF);
  ok(`[${kind}] ⟨gradient, curl⟩ = 0`, approx(gc, 0, 1e-10), `= ${gc.toExponential(2)}`);
  ok(`[${kind}] ⟨gradient, harmonic⟩ = 0`, approx(gh, 0, 1e-10), `= ${gh.toExponential(2)}`);
  ok(`[${kind}] ⟨curl, harmonic⟩ = 0`, approx(ch, 0, 1e-10), `= ${ch.toExponential(2)}`);

  // 3. PYTHAGORAS: ‖F‖² = ‖grad‖² + ‖curl‖² + ‖harmonic‖²
  const lhs = D.energy.F, rhs = D.energy.grad + D.energy.curl + D.energy.harm;
  ok(`[${kind}] ‖F‖² = ‖grad‖²+‖curl‖²+‖harm‖²`, approx(lhs, rhs, 1e-7 * (lhs + 1)), `Δ=${Math.abs(lhs - rhs).toExponential(2)}`);

  // 4. the gradient part is CURL-FREE and the curl part is DIVERGENCE-FREE (finite-diff witness)
  const g = fdDivCurl(D.gradX, D.gradY, N);   // curl of the gradient part → ~0
  const c = fdDivCurl(D.curlX, D.curlY, N);   // divergence of the curl part → ~0
  const scale = rms(Fx) + rms(Fy) + 1e-12;
  ok(`[${kind}] curl(gradient part) ≈ 0`, rms(g.vort) / scale < 2e-2, `rel=${(rms(g.vort) / scale).toExponential(2)}`);
  ok(`[${kind}] div(curl part) ≈ 0`, rms(c.div) / scale < 2e-2, `rel=${(rms(c.div) / scale).toExponential(2)}`);
}

// ---------------------------------------------------------------- pure-case energy limits
console.log('\n  — pure-case energy fractions (the readout the page shows) —');
{
  let D = decompose(...Object.values(sampleField('gradient', N)), N);
  ok('pure gradient field → gradient fraction = 100%', approx(D.frac.grad, 1, 1e-9), `grad=${(100 * D.frac.grad).toFixed(4)}%`);
  ok('pure gradient field → curl fraction = 0%', approx(D.frac.curl, 0, 1e-9), `curl=${(100 * D.frac.curl).toExponential(2)}%`);

  D = decompose(...Object.values(sampleField('curl', N)), N);
  ok('pure curl field → curl fraction = 100%', approx(D.frac.curl, 1, 1e-9), `curl=${(100 * D.frac.curl).toFixed(4)}%`);
  ok('pure curl field → gradient fraction = 0%', approx(D.frac.grad, 0, 1e-9), `grad=${(100 * D.frac.grad).toExponential(2)}%`);

  D = decompose(...Object.values(sampleField('harmonic', N)), N);
  ok('constant flow → harmonic fraction = 100%', approx(D.frac.harm, 1, 1e-9), `harm=${(100 * D.frac.harm).toFixed(4)}%`);
}

// ---------------------------------------------------------------- known mixed fractions
// mixed = 2·(gradient eigenfield) + 1·(curl eigenfield) + 0.5·(constant). The three eigen-
// pieces each carry energy proportional to (amplitude)² × (their own ‖·‖²). The gradient and
// curl eigenfields here are the SAME shape (‖·‖² equal), and the constant contributes n2·0.5².
console.log('\n  — a known mixed field: fractions match the closed-form amplitudes —');
{
  const { Fx, Fy } = sampleField('mixed', N);
  const D = decompose(Fx, Fy, N);
  const n2 = N * N;
  // eigenfield energy: ∫(sin²cos²+cos²sin²) over grid. Compute once from the pure gradient sample.
  const g0 = sampleField('gradient', N);
  let e0 = 0; for (let p = 0; p < n2; p++) e0 += g0.Fx[p] ** 2 + g0.Fy[p] ** 2;
  const eG = 4 * e0, eC = 1 * e0, eH = n2 * 0.25;   // amplitudes 2, 1, 0.5
  const tot = eG + eC + eH;
  ok('mixed: gradient fraction matches amplitude²', approx(D.frac.grad, eG / tot, 1e-6), `got ${(100 * D.frac.grad).toFixed(3)}% vs ${(100 * eG / tot).toFixed(3)}%`);
  ok('mixed: curl fraction matches amplitude²', approx(D.frac.curl, eC / tot, 1e-6), `got ${(100 * D.frac.curl).toFixed(3)}% vs ${(100 * eC / tot).toFixed(3)}%`);
  ok('mixed: harmonic fraction matches amplitude²', approx(D.frac.harm, eH / tot, 1e-6), `got ${(100 * D.frac.harm).toFixed(3)}% vs ${(100 * eH / tot).toFixed(3)}%`);
  ok('mixed: three fractions sum to 1', approx(D.frac.grad + D.frac.curl + D.frac.harm, 1, 1e-12));
}

// ---------------------------------------------------------------- spectral div/vort vs finite-diff
// The spectral divergence/vorticity the page overlays must agree with an independent
// finite-difference computation (different math, same answer) up to discretisation error.
console.log('\n  — spectral div/vort agrees with an independent finite-difference witness —');
{
  const { Fx, Fy } = sampleField('mixed', N);
  const D = decompose(Fx, Fy, N);
  const fd = fdDivCurl(Fx, Fy, N);
  // low-wavenumber fields ⇒ centred differences match spectral to a couple percent
  const relD = rms(D.div.map((v, i) => v - fd.div[i])) / (rms(fd.div) + 1e-12);
  const relV = rms(D.vort.map((v, i) => v - fd.vort[i])) / (rms(fd.vort) + 1e-12);
  ok('spectral divergence ≈ finite-difference divergence', relD < 3e-2, `rel=${relD.toExponential(2)}`);
  ok('spectral vorticity ≈ finite-difference vorticity', relV < 3e-2, `rel=${relV.toExponential(2)}`);
}

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