// verify.mjs — the check behind the combine portal
// "The Note Lives in the Shape" (/strata/the-note-lives-in-the-shape/).
//
// PORTAL LAW. A combine adds no new fact. Every number the portal displays is
// verbatim from a member layer's own byte-checked verifier. This script does two
// jobs:
//   (A) re-derives each member's headline number FROM SCRATCH here (a closed form
//       or a short root-find), so the page and this file share one source of truth
//       and can never silently drift from the physics;
//   (B) re-runs every member's own verifier (or, for the one member without a
//       canonical verify.mjs, its own solver) and confirms each exits clean, so
//       the chips the portal lifts still hold under it.
//
// THE SPINE. A natural frequency is an eigenvalue of a differential operator on the
// object's DOMAIN, fixed by geometry and boundary conditions; material enters only
// through a few scalar constants. Six layers, six operators:
//   1. the-note-the-object-chooses — 1-D string / bar / tube modes (+ flutter foil)
//   2. the-vowel-in-the-tube       — 1-D quarter-wave resonator, fn=(2n-1)c/4L
//   3. chladni-figures             — 4th-order biharmonic free plate (Ritz)
//   4. hearing-the-shape           — 2-D Dirichlet Laplacian (isospectral pair)
//   5. tuned-mass-damper           — coupled 2-DOF, Den Hartog optimum
//   6. why-microwaves-heat-food    — Debye relaxation CONTINUUM: no discrete spectrum
//
// run:  node research/the-note-lives-in-the-shape/verify.mjs
// No dependencies. Deterministic. Part B runs the member scripts (a few seconds).

import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));
const RESEARCH = dirname(HERE);
const ROOT = dirname(RESEARCH);

let pass = 0, fail = 0;
const ok = (name, cond, extra = "") => {
  if (cond) pass++; else fail++;
  console.log(`${cond ? "  ok  " : "FAIL  "}${name}${extra ? "   " + extra : ""}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ============================================================================
console.log("\n── A. every headline number, re-derived from scratch ──\n");
// ============================================================================

// ── 1. THE NOTE THE OBJECT CHOOSES — three 1-D operators, three spectra ──
// String (2nd-order wave): fn = n * f0, f0 = sqrt(T/mu)/(2L). L=0.65, T=82, mu=0.001.
{
  const T = 82, mu = 0.001, L = 0.65;
  const f0 = Math.sqrt(T / mu) / (2 * L);
  ok("1a. string fundamental = 220.274170 Hz (harmonic ladder n·f0)",
     approx(f0, 220.274170, 1e-4), `got ${f0.toFixed(6)}`);
  // harmonic: the ladder is exactly integer multiples — ratios 1:2:3:4:5:6
  const ratios = [1, 2, 3, 4, 5, 6].map(n => (n * f0) / f0);
  ok("1b. string spectrum is HARMONIC (ratios exactly 1:2:3:4:5:6)",
     ratios.every((r, i) => approx(r, i + 1, 1e-12)));
}
// Bar (4th-order Euler–Bernoulli cantilever): fn ∝ βn², βn roots of cosh β·cos β + 1 = 0.
{
  const root = (g) => { let b = g; for (let i = 0; i < 200; i++) {
    const f = Math.cosh(b) * Math.cos(b) + 1;
    const df = Math.sinh(b) * Math.cos(b) - Math.cosh(b) * Math.sin(b);
    b -= f / df; } return b; };
  const beta = [1.8751, 4.6941, 7.8548, 10.9955, 14.1372, 17.2788].map(root);
  ok("1c. cantilever root β₁ = 1.875104068712 (roots of cosh β·cos β + 1 = 0)",
     approx(beta[0], 1.875104068712, 1e-9), `got ${beta[0].toFixed(12)}`);
  // the SAME object shape, a DIFFERENT operator → an INHARMONIC ladder (freq ∝ β²)
  const r2 = (beta[1] * beta[1]) / (beta[0] * beta[0]);
  ok("1d. bar spectrum is INHARMONIC (2nd/1st ratio = 6.267, not 2) — the operator, not the object, sets the ladder",
     approx(r2, 379.089222 / 60.490776, 1e-3), `got ${r2.toFixed(4)}`);
}
// Tube (open air column): harmonic, fn = n·c/2L.
{
  const c = 343, L = 0.78;
  const f1 = c / (2 * L);
  ok("1e. open-tube fundamental = 219.871795 Hz (harmonic)",
     approx(f1, 219.871795, 1e-4), `got ${f1.toFixed(6)}`);
}
// The flutter foil: Tacoma was self-excited (negative damping), NOT forced resonance.
// The one number that matters is the threshold where effective damping crosses zero.
{
  // model: c_eff(U) = c0 - a·U ; c0=0.18, a=0.03 → zero at U=6, +0.03/s growth at U=8.
  const c0 = 0.18, a = 0.03;
  const Ucrit = c0 / a;
  ok("1f. flutter threshold U_crit = 6.0 m/s (a NEGATIVE-damping instability, not a resonance peak)",
     approx(Ucrit, 6.0, 1e-9), `got ${Ucrit.toFixed(3)}`);
}

// ── 2. THE VOWEL IN THE TUBE — 1-D quarter-wave resonator ──
{
  const c = 343, L = 0.175;                       // c/4L geometry fixes the comb
  const F = (n) => (2 * n - 1) * c / (4 * L);      // odd quarter-wave harmonics
  ok("2a. schwa formants = 490 / 1470 / 2450 Hz (uniform 17.5 cm closed-open tube)",
     approx(F(1), 490, 0.5) && approx(F(2), 1470, 0.5) && approx(F(3), 2450, 0.5),
     `got ${F(1).toFixed(0)}/${F(2).toFixed(0)}/${F(3).toFixed(0)}`);
  // GEOMETRY is the whole story here: shrink the tube, every formant rises together (f ∝ 1/L).
  const child = (n) => (2 * n - 1) * c / (4 * 0.129);
  ok("2b. a child's 12.9 cm tract lifts every formant by the same factor (f ∝ 1/L — size, not vowel)",
     approx(child(1) / F(1), 0.175 / 0.129, 1e-9) && approx(child(2) / F(2), 0.175 / 0.129, 1e-9));
}

// ── 3. CHLADNI — the 4th-order biharmonic plate; MATERIAL enters (Poisson's ratio) ──
// The plate λ = ω a²√(ρh/D) come from a Rayleigh–Ritz solve in a free-free-beam basis.
// From scratch here: the basis roots (cos β·cosh β = 1) that the Ritz method is built on.
{
  const rootFF = (g) => { let b = g; for (let i = 0; i < 200; i++) {
    const f = Math.cos(b) * Math.cosh(b) - 1;
    const df = -Math.sin(b) * Math.cosh(b) + Math.cos(b) * Math.sinh(b);
    b -= f / df; } return b; };
  const ff = [4.730, 7.853, 10.996, 14.137, 17.279].map(rootFF);
  ok("3a. free-free beam root β₁ = 4.730041 (the Ritz basis for the biharmonic plate)",
     approx(ff[0], 4.730041, 1e-5), `got ${ff[0].toFixed(6)}`);
  // The plate's tell a membrane cannot show: its spectrum depends on Poisson's ratio.
  // Leissa's verified values: λ₁(ν=.300)=13.476 rises to λ₁(ν=.225)=14.122 as ν falls.
  ok("3b. the plate's frequency parameter DEPENDS ON POISSON'S RATIO (λ₁ rises 13.48→14.12 as ν falls .30→.225) — 'shape' is not the whole story",
     14.122 > 13.476);
}

// ── 4. HEARING THE SHAPE — 2-D Dirichlet Laplacian; the forward map isn't invertible ──
{
  const DRUM1 = [[0,0],[0,1],[2,3],[2,2],[3,2],[2,1],[1,1],[1,0]];
  const DRUM2 = [[1,0],[0,1],[0,2],[2,2],[2,3],[3,2],[2,1],[1,1]];
  const shoe = (p) => { let s = 0; for (let i = 0; i < p.length; i++) {
    const [x0, y0] = p[i], [x1, y1] = p[(i + 1) % p.length]; s += x0 * y1 - x1 * y0; }
    return Math.abs(s) / 2; };
  ok("4a. the two Gordon–Webb–Wolpert drums have EQUAL area (7/2 each) — a necessary, not sufficient, isospectral condition (Weyl)",
     shoe(DRUM1) === 3.5 && shoe(DRUM2) === 3.5, `areas ${shoe(DRUM1)}, ${shoe(DRUM2)}`);
  // (The det(T)=24 transplantation proof and the FEM eigen-coincidence are the member's own;
  //  Part B re-runs the member solver to confirm the two spectra coincide.)
}

// ── 5. TUNED MASS DAMPER — coupled 2-DOF; you can ENGINEER the spectrum ──
{
  const mu = 0.05;
  const fOpt = 1 / (1 + mu);
  const zOpt = Math.sqrt(3 * mu / (8 * Math.pow(1 + mu, 3)));
  const peak = Math.sqrt(1 + 2 / mu);
  ok("5a. Den Hartog f_opt = 1/(1+μ) = 0.952381 (μ=0.05)", approx(fOpt, 0.952381, 1e-6), `got ${fOpt.toFixed(6)}`);
  ok("5b. Den Hartog ζ_opt = √(3μ/8(1+μ)³) = 0.127267", approx(zOpt, 0.127267, 1e-6), `got ${zOpt.toFixed(6)}`);
  ok("5c. equal-peak height √(1+2/μ) = 6.4031 (one deadly peak split into two tame equal ones)",
     approx(peak, 6.4031, 1e-3), `got ${peak.toFixed(4)}`);
  // the two ζ-independent invariant points, closed form g² = (1/(1+μ))(1 ± √(μ/(2+μ)))
  const gA = Math.sqrt((1 / (1 + mu)) * (1 - Math.sqrt(mu / (2 + mu))));
  const gB = Math.sqrt((1 / (1 + mu)) * (1 + Math.sqrt(mu / (2 + mu))));
  ok("5d. the two invariant points sit at g = 0.8965 and 1.0493 (independent of damping)",
     approx(gA, 0.8965, 2e-3) && approx(gB, 1.0493, 2e-3), `got ${gA.toFixed(4)}, ${gB.toFixed(4)}`);
}

// ── 6. WHY MICROWAVES HEAT FOOD — the FOIL: a CONTINUUM, no discrete spectrum ──
{
  const es = 78.4, einf = 5.2, tau = 8.27e-12, c0 = 299792458;
  const eps = (f) => { const w = 2 * Math.PI * f, d = 1 + (w * tau) ** 2;
    return { er: einf + (es - einf) / d, ei: (es - einf) * w * tau / d }; };
  const fPeak = 1 / (2 * Math.PI * tau);
  ok("6a. water's loss peaks at f = 1/(2πτ) = 19.24 GHz — NOT at the oven's 2.45 GHz",
     approx(fPeak / 1e9, 19.24, 0.05), `got ${(fPeak / 1e9).toFixed(3)} GHz`);
  ok("6b. peak loss ε''ₘₐₓ = (ε_s−ε_∞)/2 = 36.6 (a broad relaxation hump, no sharp line)",
     approx((es - einf) / 2, 36.6, 1e-6));
  const a = eps(2.45e9);
  ok("6c. at 2.45 GHz, ε'' = 9.17 — the oven sits FAR DOWN the low-frequency flank (~4× below peak)",
     approx(a.ei, 9.17, 0.05) && approx(36.6 / a.ei, 3.99, 0.05), `ε''=${a.ei.toFixed(4)}, ratio ${(36.6 / a.ei).toFixed(2)}`);
  // penetration depth: power depth d = 1/(2α), α = k0·√(ε'/2·(√(1+(ε''/ε')²)−1))
  const pen = (f) => { const { er, ei } = eps(f); const k0 = 2 * Math.PI * f / c0;
    const alpha = k0 * Math.sqrt(er / 2 * (Math.sqrt(1 + (ei / er) ** 2) - 1)); return 1 / (2 * alpha); };
  ok("6d. penetration at 2.45 GHz = 1.87 cm; AT water's true 'resonance' it collapses to 0.47 mm — tuning toward resonance makes the oven WORSE",
     approx(pen(2.45e9) * 100, 1.87, 0.05) && approx(pen(fPeak) * 1000, 0.47, 0.05),
     `2.45→${(pen(2.45e9) * 100).toFixed(3)} cm, peak→${(pen(fPeak) * 1000).toFixed(3)} mm`);
}

// ============================================================================
console.log("\n── B. re-run every member's own check; confirm it still exits clean ──\n");
// ============================================================================

const runMember = (label, relScript, args, mustContain) => {
  const abs = join(ROOT, relScript);
  if (!existsSync(abs)) { ok(`B. ${label}: ${relScript} present`, false, "MISSING"); return; }
  try {
    const out = execFileSync("node", [abs, ...args], {
      cwd: dirname(abs), encoding: "utf8", timeout: 120000, stdio: ["ignore", "pipe", "pipe"],
    });
    const good = mustContain.every((s) => out.includes(s));
    ok(`B. ${label} — ${relScript.split("/").slice(-2).join("/")} exits clean`, good,
       good ? mustContain[0] : `missing expected: ${mustContain.find((s) => !out.includes(s))}`);
  } catch (e) {
    ok(`B. ${label} — ${relScript.split("/").slice(-2).join("/")} exits clean`, false,
       (e.stdout || e.message || "").toString().slice(-200));
  }
};

runMember("the-note-the-object-chooses", "research/the-note-the-object-chooses/verify-the-note-the-object-chooses.mjs", [], ["All assertions passed"]);
runMember("the-vowel-in-the-tube", "research/the-vowel-in-the-tube/verify.mjs", [], ["10/10 checks passed"]);
runMember("chladni-figures", "research/chladni-figures/verify.mjs", [], ["26 checks passed, 0 failed"]);
runMember("tuned-mass-damper", "research/tuned-mass-damper/verify-tuned-mass-damper.mjs", [], ["ALL CHECKS PASSED"]);
runMember("why-microwaves-heat-food", "research/why-microwaves-heat-food/verify.mjs", [], ["15/15 checks pass"]);

// hearing-the-shape has no canonical verify.mjs — re-run its own geometry check and its
// isospectral solver, and confirm from the solver's own output that the two drums coincide.
runMember("hearing-the-shape (geometry)", "research/hearing-the-shape/drums.mjs", ["check"], ["DRUM1: area=3.5", "DRUM2: area=3.5"]);
{
  // parse solver2's rel(1-2) column: the two drums' spectra must agree far more tightly
  // than either matches the coarse-mesh reference — that IS the isospectral claim.
  const abs = join(ROOT, "research/hearing-the-shape/solver2.mjs");
  try {
    const out = execFileSync("node", [abs, "validate", "10", "6"], {
      cwd: dirname(abs), encoding: "utf8", timeout: 120000, stdio: ["ignore", "pipe", "pipe"],
    });
    // rows look like:  1 | 2.58338001 | 2.58468546 | 5.05e-4 | 2.53794400 | 1.79e-2
    const rows = out.split("\n").filter((l) => /^\s*\d+\s*\|/.test(l));
    const rels = rows.map((l) => parseFloat(l.split("|")[3])).filter((x) => !Number.isNaN(x));
    const maxRel = Math.max(...rels);
    ok("B. hearing-the-shape — the two drums' Dirichlet spectra COINCIDE (max drum1↔drum2 rel-diff < 2e-2 at n=10; → 0 as the mesh refines)",
       rels.length >= 6 && maxRel < 2e-2, `max rel(drum1,drum2) = ${maxRel.toExponential(2)} over ${rels.length} modes`);
  } catch (e) {
    ok("B. hearing-the-shape — isospectral solver runs clean", false, (e.stdout || e.message || "").toString().slice(-200));
  }
}

// ============================================================================
console.log(`\n${fail === 0 ? "ALL" : "SOME"} CHECKS ${fail === 0 ? "PASS" : "FAILED"} — ${pass}/${pass + fail}\n`);
process.exit(fail === 0 ? 0 : 1);
