// verify.mjs: selected Chladni frequency parameters and sampled mode features.
// Comparisons with published values are specified below. Run:
//   node research/chladni-figures/verify.mjs        (exit 0 = all pass)
//
// It imports the SAME core module the live page runs in the browser
// (../../public/strata/chladni-figures/chladni-core.mjs), so this is a check of
// the page's own maths, not a parallel re-implementation that could drift.
//
// What it checks, and against what:
//   A. Free-free beam wavenumbers β (roots of cos β cosh β = 1) vs the standard
//      values 4.730041, 7.853205, 10.995608, 14.137165, 17.278760.
//   B. The beam basis is orthonormal → the Ritz mass matrix is the identity, so
//      the plate eigenproblem is a standard symmetric one (K symmetric too).
//   C. The free SQUARE PLATE has exactly 3 rigid-body modes at λ = 0.
//   D. The first five free-plate frequency parameters λ = ω a² √(ρh/D)
//      reproduce Leissa's (1973) beam-function values for ν = 0.3, as reproduced
//      in Huang, Leissa and Liao (2008), Table 1: 13.49, 19.79, 24.43, 35.02, 35.02.
//      https://ir.lib.nycu.edu.tw/bitstream/11536/8502/1/000259156600003.pdf
//      These are Rayleigh–Ritz upper bounds; the larger basis gives lower values.
//   E. The free-plate normalized frequencies depend on ν; a uniform membrane's
//      frequency ratios do not. This solver's fundamental rises 13.48 to 14.12
//      as ν changes from .300 to .225. Leissa's NASA SP-160, Table 4.67, gives
//      upper bounds of 13.464 and 14.111 respectively, not these readout values.
//   F. Partial nodal checks: the first mode on x=0.5, the second on y=x,
//      and the third mode's centre amplitude. These do not establish complete
//      cross, X or closed-ring nodal patterns.
//   G. The membrane baseline: lowest mode, (m,n)/(n,m) degeneracy, a sampled
//      straight nodal line, and a finite centre value for an equal mode mixture.

import {
  beamRoots, gaussLegendre, beamTables, assembleK, jacobiEigen,
  solvePlate, evalPlate, membraneModes, evalMembrane,
} from '../../public/strata/chladni-figures/chladni-core.mjs';

let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  — ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  — ' + detail : ''}`); }
}

// ---------------------------------------------------------------------------
console.log('\nA. Free-free beam wavenumbers β  (cos β · cosh β = 1)');
{
  const want = [4.730041, 7.853205, 10.995608, 14.137165, 17.278760];
  const got = beamRoots(5);
  want.forEach((w, i) => check(`β${i + 1} = ${w}`, approx(got[i], w, 5e-6), `got ${got[i].toFixed(6)}`));
  // each root really satisfies the characteristic equation. Use the well-scaled
  // form cos β = sech β (≡ cos β cosh β = 1) — the raw product carries a cosh β≈1.6e7
  // amplification that swamps it in absolute terms for the higher roots.
  check('roots satisfy cos β = sech β', got.every((b) => approx(Math.cos(b), 1 / Math.cosh(b), 1e-12)));
}

// ---------------------------------------------------------------------------
console.log('\nB. Beam basis orthonormal ⇒ Ritz mass matrix = I, stiffness symmetric');
{
  const N = 8;
  const broots = beamRoots(N - 2);
  const tab = beamTables(N, broots, 48);
  let maxOff = 0;
  for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) {
    const target = i === j ? 1 : 0;
    maxOff = Math.max(maxOff, Math.abs(tab.Mass[i][j] - target));
  }
  check('∫ φ_i φ_j = δ_ij (mass = identity)', maxOff < 1e-7, `max |M−I| = ${maxOff.toExponential(1)} (48-pt Gauss)`);
  // ∫ φ_m'' φ_m'' = β_m⁴ for the elastic modes (a second, independent integral check)
  check('∫ (φ₃″)² = β₁⁴', approx(tab.E[2][2], Math.pow(broots[0], 4), 1e-3),
    `${tab.E[2][2].toFixed(3)} vs ${Math.pow(broots[0], 4).toFixed(3)}`);
  const { K } = assembleK(tab, 0.3);
  let sym = 0;
  for (let i = 0; i < K.length; i++) for (let j = 0; j < K.length; j++) sym = Math.max(sym, Math.abs(K[i][j] - K[j][i]));
  check('Ritz stiffness K is symmetric', sym < 1e-9, `max |K−Kᵀ| = ${sym.toExponential(1)}`);
}

// ---------------------------------------------------------------------------
console.log('\nC–D. Free square plate frequency parameters λ = ω a² √(ρh/D), ν = 0.3');
const plate = solvePlate(0.3, 8, 48);
const lam = plate.modes.map((m) => m.lambda);
{
  // C: exactly three rigid-body modes at λ ≈ 0
  const zeros = lam.filter((l) => l < 1e-3).length;
  check('exactly 3 rigid-body modes at λ = 0', zeros === 3, `found ${zeros} near-zero (${lam.slice(0, 3).map((x) => x.toExponential(1)).join(', ')})`);

  // D: first five Leissa (1973) values, reproduced in Huang et al. (2008), Table 1
  const elastic = lam.filter((l) => l > 1e-3);
  const leissa1973 = [13.49, 19.79, 24.43, 35.02, 35.02];
  leissa1973.forEach((y, i) => {
    const g = elastic[i];
    // within 1.2% of the published beam-function value, and not above it by more
    // than rounding (Ritz upper-bound: our larger basis sits at/just below y)
    check(`mode ${i + 1}: λ ≈ ${y}`, approx(g, y, 0.012 * y) && g <= y + 0.05,
      `got ${g.toFixed(3)} (${((g - y) / y * 100).toFixed(2)}%)`);
  });
  // the famous fundamental, stated to the reader as ≈ 13.5
  check('fundamental λ₁ ∈ [13.20, 13.49] (NASA lower bound rounded down; Leissa 1973 upper bound)', elastic[0] >= 13.20 && elastic[0] <= 13.49,
    `λ₁ = ${elastic[0].toFixed(3)}`);
}

// ---------------------------------------------------------------------------
console.log('\nE. Poisson-ratio dependence of normalized frequency parameters');
{
  const f300 = solvePlate(0.300, 8, 48).modes.filter((m) => m.lambda > 1e-3)[0].lambda;
  const f225 = solvePlate(0.225, 8, 48).modes.filter((m) => m.lambda > 1e-3)[0].lambda;
  check('fundamental depends on ν (rises as ν falls)', f225 > f300 + 0.3, `ν=.300→${f300.toFixed(3)}, ν=.225→${f225.toFixed(3)}`);
  check('λ₁(ν=.225) ≈ 14.11 (Leissa Table 4.67)', approx(f225, 14.11, 0.15), `got ${f225.toFixed(3)}`);
}

// ---------------------------------------------------------------------------
console.log('\nF. Sampled nodal features of the lowest plate modes');
{
  const elasticModes = plate.modes.filter((m) => m.lambda > 1e-3);
  const broots = plate.broots;
  const samp = (A, pts) => Math.max(...pts.map(([x, y]) => Math.abs(evalPlate(A, broots, x, y))));
  const along = (A, fn, n = 41) => { let mx = 0; for (let i = 1; i < n; i++) { const t = i / n; const [x, y] = fn(t); mx = Math.max(mx, Math.abs(evalPlate(A, broots, x, y))); } return mx; };
  // peak amplitude anywhere (for scale)
  const peak = (A) => { let mx = 0; for (let i = 0; i <= 20; i++) for (let j = 0; j <= 20; j++) mx = Math.max(mx, Math.abs(evalPlate(A, broots, i / 20, j / 20))); return mx; };

  const m1 = elasticModes[0], p1 = peak(m1.A);
  const onCross1 = along(m1.A, (t) => [0.5, t]); // along the vertical centre-line x=0.5
  check('λ≈13.5 fundamental: sampled vertical centre-line is near zero', onCross1 / p1 < 0.02,
    `|W| on x=½ is ${(onCross1 / p1 * 100).toFixed(2)}% of peak`);

  const m2 = elasticModes[1], p2 = peak(m2.A);
  const onDiag2 = along(m2.A, (t) => [t, t]); // along the main diagonal y=x
  check('λ≈19.7 mode: sampled main diagonal is near zero', onDiag2 / p2 < 0.02,
    `|W| on y=x is ${(onDiag2 / p2 * 100).toFixed(2)}% of peak`);

  const m3 = elasticModes[2], p3 = peak(m3.A);
  // Check the centre amplitude only; this does not establish a closed nodal ring.
  const centre3 = Math.abs(evalPlate(m3.A, broots, 0.5, 0.5));
  check('λ≈24.4 mode: centre amplitude exceeds half the sampled peak', centre3 / p3 > 0.5,
    `centre |W| = ${(centre3 / p3 * 100).toFixed(0)}% of peak`);
  void samp;
}

// ---------------------------------------------------------------------------
console.log('\nG. Membrane (drumhead) baseline — the model a Chladni plate is NOT');
{
  const modes = membraneModes(4);
  // frequency ∝ √(m²+n²); ordering
  check('lowest membrane mode is (1,1), k²=2', modes[0].m === 1 && modes[0].n === 1 && modes[0].k2 === 2);
  // degeneracy (m,n)≡(n,m)
  const pair = modes.filter((x) => (x.m === 2 && x.n === 1) || (x.m === 1 && x.n === 2));
  check('(2,1) and (1,2) are degenerate (same k²=5)', pair.length === 2 && pair[0].k2 === pair[1].k2);
  // a PURE membrane mode has straight nodal lines (zero exactly on x = j/m grid lines)
  const straight = (() => { let mx = 0; for (let i = 1; i < 40; i++) { const y = i / 40; mx = Math.max(mx, Math.abs(evalMembrane(3, 2, 1 / 3, y))); } return mx; })();
  check('pure (3,2) membrane mode: nodal line x=1/3 is exactly straight', straight < 1e-12,
    `|W| on x=1/3 = ${straight.toExponential(1)}`);
  // This is only a finite-value smoke check of a degenerate superposition.
  // It does not establish the geometry of the nodal set.
  const combo = (x, y) => evalMembrane(3, 2, x, y, 1, 1);
  const centre = Math.abs(combo(0.5, 0.5));
  check('degenerate (3,2)+(2,3) superposition: finite centre value',
    Number.isFinite(centre), `centre value ${centre.toExponential(1)}`);
}

// ---------------------------------------------------------------------------
console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass} checks passed, ${fail} failed.\n`);
process.exit(fail === 0 ? 0 : 1);
