// verify.mjs — "The Equalizer Is the Sculptor", re-derived from scratch.
//
//   node research/the-equalizer-is-the-sculptor/verify.mjs
//
// Independently recomputes every operable number the page states — from the raw
// physics, NOT by trusting data.mjs's computed fields — then asserts data.mjs
// agrees, checks provenance against the three member layers, and drift-checks
// that the built page embeds the canonical JSON byte-for-byte.
//
// The three sources of truth being reproduced:
//   Turing   — Schnakenberg dispersion relation (Murray, Mathematical Biology II §2.4)
//   Ring     — charged-conducting-disk evaporation flux, Deegan et al. 1997
//   Tea leaf — rotating-frame boundary-layer radial force balance (Thomson 1857)

import { readFileSync, existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DATA, JSON_STR } from './data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '../..');
let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; } else { fail++; console.error('  ✗ ' + msg); } };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const section = (s) => console.log('\n' + s);

const T = DATA.movements.find((m) => m.id === 'turing').turing;
const R = DATA.movements.find((m) => m.id === 'ring').ring;
const E = DATA.movements.find((m) => m.id === 'tea').tea;

// ═══════════════════════════════════════════════════════════════════════════
section('[1] TURING — Schnakenberg dispersion, from scratch');
// raw model constants (re-typed here, not imported from data.mjs)
{
  const a = 0.1, b = 0.9, gamma = 14300, d = 40;
  const u = a + b, v = b / (u * u);
  ok(near(u, 1, 1e-12) && near(v, 0.9, 1e-12), 'steady state (u*,v*) = (1, 0.9)');
  ok(near(u, T.steady.u, 1e-6) && near(v, T.steady.v, 1e-6), 'data.mjs steady state matches');
  const fu = -1 + 2 * u * v, fv = u * u, gu = -2 * u * v, gv = -u * u;
  ok(near(fu, 0.8, 1e-12) && near(gv, -1, 1e-12) && near(gu, -1.8, 1e-12), 'reaction Jacobian [[0.8,1],[-1.8,-1]]');

  // reaction-only stability: Tr(γJ)<0, Det>0; complex pair -1430 ± 14228.32 i
  const trR = gamma * (fu + gv), detR = gamma * gamma * (fu * gv - fv * gu);
  const im = Math.sqrt(Math.abs(trR * trR - 4 * detR)) / 2, re = trR / 2;
  ok(trR < 0 && detR > 0, 'no-diffusion flat state is STABLE (Tr<0, Det>0)');
  ok(near(re, -1430, 0.5) && near(im, 14228.32, 0.05), 'reaction eigenvalues −1430 ± 14228.32 i');
  ok(near(re, T.reactionStable.eigRe, 0.5) && near(im, T.reactionStable.eigIm, 0.05), 'data.mjs eigenvalues match');

  // critical ratio d_c: (d fu + gv)^2 = 4 d Det(J)
  const detJ = fu * gv - fv * gu;
  const A = fu * fu, B = 2 * fu * gv - 4 * detJ, Cc = gv * gv;
  const dc = (-B + Math.sqrt(B * B - 4 * A * Cc)) / (2 * A);
  ok(near(dc, 8.5676, 1e-3), 'critical diffusion ratio d_c = 8.5676');
  ok(near(dc, T.dc, 1e-3), 'data.mjs d_c matches');

  // dispersion: maximise λ_+(k²); band where λ>0
  const lamPlus = (k2, dd) => {
    const A11 = gamma * fu - k2, A22 = gamma * gv - dd * k2;
    const tr = A11 + A22, det = A11 * A22 - gamma * gamma * fv * gu;
    const rad = tr * tr - 4 * det;
    return (tr + (rad > 0 ? Math.sqrt(rad) : 0)) / 2;
  };
  const kc2 = gamma * (d * fu + gv) / (2 * d), top = 4 * kc2, N = 500000;
  let kStar2 = 0, lamStar = -Infinity, lo = Infinity, hi = -Infinity;
  for (let i = 1; i <= N; i++) { const k2 = top * i / N; const l = lamPlus(k2, d);
    if (l > lamStar) { lamStar = l; kStar2 = k2; }
    if (l > 0) { if (k2 < lo) lo = k2; if (k2 > hi) hi = k2; } }
  const kStar = Math.sqrt(kStar2), wl = 2 * Math.PI / kStar;
  ok(near(kStar, 50.29, 0.05), 'fastest-growing mode k* ≈ 50.29');
  ok(near(wl, 0.12494, 1e-3), 'predicted wavelength 2π/k* ≈ 0.1249');
  ok(Math.round(1 / wl) === 8, '≈ 8 features across the unit domain');
  ok(near(Math.sqrt(lo), 21.96, 0.1) && near(Math.sqrt(hi), 102.96, 0.2), 'unstable band k ∈ [21.96, 102.96]');
  ok(near(kStar, T.kStar, 0.05) && Math.round(1 / wl) === T.featuresAcross, 'data.mjs k*/features match');
  ok(near(Math.sqrt(lo), T.band.lo, 0.1) && near(Math.sqrt(hi), T.band.hi, 0.2), 'data.mjs band matches');

  // control d = 1 → max growth ≤ 0 (dead flat)
  let ctrl = -Infinity;
  for (let i = 0; i <= N; i++) { const l = lamPlus(top * i / N, 1); if (l > ctrl) ctrl = l; }
  ok(ctrl <= 1e-6 && near(ctrl, -1430, 1), 'control d=1: max growth = −1430 (stable, no pattern)');
  ok(near(ctrl, T.control.d1MaxGrowth, 1), 'data.mjs control matches');
}

// ═══════════════════════════════════════════════════════════════════════════
section('[2] COFFEE RING — charged-disk evaporation, from scratch');
{
  const cum = (x) => 1 - Math.sqrt(1 - x * x);
  const lambda = (deg) => { const t = deg * Math.PI / 180; return (Math.PI - 2 * t) / (2 * Math.PI - 2 * t); };
  const flux = (x) => Math.pow(1 - x * x, -0.5);
  ok(near(lambda(0), 0.5, 1e-9), 'λ(0°) = 0.5 (flat disk)');
  ok(near(lambda(40), 5 / 14, 1e-9), 'λ(40°) = 5/14 = 0.3571');
  ok(near(lambda(90), 0, 1e-9), 'λ(90°) = 0 — flux uniform, no ring');
  ok(near(lambda(120), -0.5, 1e-9), 'λ(120°) = −0.5 — deposit inverts to a centre spot');
  ok(near(lambda(0), R.lambda.d0, 1e-6) && near(lambda(90), R.lambda.d90, 1e-6) && near(lambda(120), R.lambda.d120, 1e-6), 'data.mjs λ(θ) values match');

  const outer10 = (1 - cum(0.9)) * 100;                 // outer tenth of the radius
  ok(near(outer10, 43.6, 0.1), 'outer 10% of the radius sheds 43.6% of the vapour (√0.19)');
  ok(near(outer10, R.outer10pctRadius, 0.1), 'data.mjs edge fraction matches');
  ok(near((1 - cum(Math.sqrt(0.75))) * 100, 50, 1e-6), 'outer quarter of the AREA sheds exactly 50%');
  ok(near(cum(0.5) * 100, 13.4, 0.1), 'inner half of the area sheds only 13.4%');
  ok(near(flux(0.99), 7.09, 0.01), 'rim flux ×7.09 vs centre at r = 0.99R');
  ok(near(flux(0.99), R.rimEnhancement, 0.01), 'data.mjs rim enhancement matches');

  // integrable singularity: ∫₀¹ r(1−r²)^(−1/2) dr = 1 (finite total)
  let I = 0; const M = 4000000;
  for (let i = 0; i < M; i++) { const x = (i + 0.5) / M; I += (x * flux(x)) / M; }
  ok(near(I, 1, 2e-3), '∫₀¹ r(1−r²)^(−1/2) dr = 1 — rim diverges yet total is finite');
  ok(R.capacitanceCoeff === 8, 'charged-disk capacitance coefficient C = 8 ε₀R (diameter law)');
}

// ═══════════════════════════════════════════════════════════════════════════
section('[3] TEA LEAF — rotating boundary-layer force balance, from scratch');
{
  const DELTA = 0.12, rr = 0.6;
  const f = (z) => 1 - Math.exp(-z / DELTA) * Math.cos(z / DELTA);
  const aR = (z) => rr * (f(z) * f(z) - 1);
  ok(near(f(0), 0, 1e-12), 'swirl vanishes at the no-slip floor, f(0)=0');
  ok(aR(0) < -0.3 && near(aR(0), -0.6, 1e-6), 'net radial force at floor is strongly INWARD (−0.6)');
  ok(Math.abs(aR(1)) < 0.05, 'net radial force in the bulk is ~balanced');
  ok(near(aR(0), E.floorForce, 1e-3) && near(aR(1), E.bulkForce, 1e-3), 'data.mjs floor/bulk force match');
  // equalize the boundary layer (f=1 everywhere) → force closes to zero
  ok(near(0.6 * (1 * 1 - 1), 0, 1e-12), 'no floor drag (f=1) → a_r = 0, the pump stops');

  // real teacup Ekman scalings
  const nu = 1e-6, H = 0.05, OM = 6;
  const delta = Math.sqrt(nu / OM) * 1000;              // mm
  const spin = H / Math.sqrt(nu * OM), visc = (H * H) / nu;
  ok(near(delta, 0.41, 0.01), 'Ekman-layer thickness δ = √(ν/Ω) = 0.41 mm (sub-millimetre)');
  ok(near(spin, 20, 1) && Math.round(spin) === E.spinUpS, 'spin-up time H/√(νΩ) ≈ 20 s');
  ok(Math.round(visc) === E.viscousS && visc > 10 * spin, 'Ekman pumping (20 s) ≪ viscous time (2500 s)');
  ok(near(delta, E.ekmanDeltaMm, 0.01), 'data.mjs Ekman thickness matches');
}

// ═══════════════════════════════════════════════════════════════════════════
section('[4] PROVENANCE — the members exist and carry these numbers');
{
  const strata = join(ROOT, 'src/content/strata');
  for (const m of DATA.members) ok(existsSync(join(strata, m.slug + '.md')), `member on the ground: ${m.slug}.md`);
  for (const o of DATA.overlaps) ok(existsSync(join(strata, o.slug + '.md')), `disclosed portal exists: ${o.slug}.md`);

  // cross-check against the members' own verifiers / data (reuse, don't re-invent)
  const teaV = readFileSync(join(ROOT, 'research/tea-leaf-paradox/verify.mjs'), 'utf8');
  ok(teaV.includes('f * f - 1') || teaV.includes('f(z)') , 'tea-leaf verifier uses the same swirl-force law');
  ok(teaV.includes('sqrt(nu / Om') || teaV.includes('nu / Om'), 'tea-leaf verifier computes the Ekman thickness');
  const ringData = JSON.parse(readFileSync(join(ROOT, 'research/the-coffee-ring/data.json'), 'utf8'));
  ok(near(ringData.edgeFraction_outer10pctRadius, 43.6, 0.1), 'coffee-ring data.json confirms the 43.6% edge fraction');
  ok(near(ringData.contactAngleExponent.λ_90deg, 0, 1e-9), 'coffee-ring data.json confirms λ(90°)=0');
  ok(ringData.disk.capacitanceExactCoeff === 8, 'coffee-ring data.json confirms the exact "8" capacitance law');
  const turOut = readFileSync(join(ROOT, 'research/turing-patterns/verify-output.txt'), 'utf8');
  ok(turOut.includes('8.5676') || turOut.includes('d_c = 8.57'), 'turing verifier output confirms d_c = 8.5676');
  ok(turOut.includes('50.28') || turOut.includes('50.2894'), 'turing verifier output confirms k* = 50.29');
}

// ═══════════════════════════════════════════════════════════════════════════
section('[5] DRIFT — the built page carries the canonical data');
{
  const built = join(ROOT, 'public/strata', DATA.meta.slug, 'index.html');
  if (existsSync(built)) {
    const html = readFileSync(built, 'utf8');
    ok(html.includes(JSON_STR), 'built page embeds the canonical DATA byte-for-byte (no drift)');
    ok(html.includes('rel="canonical" href="https://artwaste.land/strata/' + DATA.meta.slug + '/"'), 'canonical URL present');
    ok(html.includes('/media/home-banner.js'), 'home banner present (design-system chrome)');
    ok(html.includes('d_c = ' + T.dcRounded) || html.includes('8.57'), 'page states the Turing threshold');
    ok(html.includes(String(R.outer10pctRadius) + '%'), 'page states the coffee-ring edge fraction');
    ok(html.includes(String(E.ekmanDeltaMm) + ' mm'), 'page states the Ekman thickness');
  } else {
    console.log('  · built page not present yet (run build-page.mjs) — drift check skipped');
  }
}

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