// verify.mjs — from-scratch checks for the portal "The Chain Obeys Snell's Law".
// Run: node research/the-chain-obeys-snells-law/verify.mjs
//
// The single claim under test: the catenary, the brachistochrone, and the path
// of light are stationary curves of ONE functional J[y]=∫f(y)√(1+y'^2)dx, and
// because that integrand has no explicit x, they share ONE conserved quantity —
// the Beltrami first integral f(y)/√(1+y'^2) = f(y)·sinθ — which is Snell's law
// n·sinθ=const with f in the role of the refractive index. Everything below is
// recomputed; nothing is asserted that isn't measured here.

import {
  F, beltrami, sinThetaFromYp, action, actionGrad, relax, march,
  catenarySym, cycloidTo, onUniformX, bernoulliRay,
} from './engine.mjs';

let pass = 0, fail = 0;
const log = [];
function ok(name, cond, detail = '') {
  (cond ? pass++ : fail++);
  log.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  —  ' + detail : ''}`);
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const maxAbs = (arr) => arr.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
const std = (arr) => {
  const m = arr.reduce((s, v) => s + v, 0) / arr.length;
  return Math.sqrt(arr.reduce((s, v) => s + (v - m) * (v - m), 0) / arr.length);
};

// ---------------------------------------------------------------------------
// 1. The Beltrami identity is an exact algebraic identity:
//    L − y'·∂L/∂y'  ==  f(y)/√(1+y'^2),  for L = f(y)√(1+y'^2).
{
  const fs = [(y) => y, (y) => 1 / Math.sqrt(y), (y) => 1.3 + 0.2 * y, (y) => y * y + 1];
  let worst = 0;
  for (const f of fs) {
    for (let t = 0; t < 200; t++) {
      const y = 0.2 + 3 * Math.abs(Math.sin(t * 1.7));
      const yp = Math.tan((t % 50) / 50 * 1.4 - 0.7);
      const L = f(y) * Math.sqrt(1 + yp * yp);
      // analytic ∂L/∂y'
      const dLdyp = f(y) * yp / Math.sqrt(1 + yp * yp);
      const lhs = L - yp * dLdyp;
      const rhs = f(y) / Math.sqrt(1 + yp * yp);
      worst = Math.max(worst, Math.abs(lhs - rhs));
      // and check the analytic derivative against a finite difference
      const h = 1e-7;
      const fd = (f(y) * Math.sqrt(1 + (yp + h) ** 2) - f(y) * Math.sqrt(1 + (yp - h) ** 2)) / (2 * h);
      worst = Math.max(worst, Math.abs(fd - dLdyp));
    }
  }
  ok('Beltrami identity exact: L − y′L_y′ = f/√(1+y′²)', worst < 1e-6, `max resid ${worst.toExponential(2)}`);
}

// 2. sinθ = 1/√(1+y'^2) really is the sine of the angle from the vertical.
{
  let worst = 0;
  for (let k = 0; k < 100; k++) {
    const yp = -3 + 6 * k / 99;                 // slope dy/dx
    const alpha = Math.atan(yp);                // angle of tangent above horizontal
    const theta = Math.PI / 2 - alpha;          // angle from the vertical
    worst = Math.max(worst, Math.abs(Math.sin(theta) - sinThetaFromYp(yp)));
  }
  ok('sinθ (from vertical) = 1/√(1+y′²)', worst < 1e-12, `max resid ${worst.toExponential(2)}`);
}

// ---------------------------------------------------------------------------
// 3. CHAIN. The catenary y = a cosh(x/a) holds its Beltrami constant: y·sinθ = a
//    everywhere (the chain "refracts" with index = its own height).
{
  const X = 1.2, yEnd = 1.9;
  const cat = catenarySym(X, yEnd, 600);
  const vals = [];
  for (let i = 1; i < cat.xs.length - 1; i++) {
    const x = cat.xs[i];
    const yp = Math.sinh(x / cat.a);            // analytic slope of a cosh(x/a)
    vals.push(beltrami(cat.ys[i], yp, F.chain));
  }
  ok('chain: y·sinθ constant along the catenary',
     std(vals) / Math.abs(vals[0]) < 1e-9 && approx(vals[0], cat.a, 1e-6 * cat.a),
     `value ${vals[0].toFixed(6)} = a (${cat.a.toFixed(6)}), rel.std ${(std(vals) / vals[0]).toExponential(2)}`);

  // and the catenary really solves its Euler–Lagrange ODE  y·y'' = 1 + y'^2.
  let worst = 0;
  for (let i = 1; i < cat.xs.length - 1; i++) {
    const x = cat.xs[i];
    const y = cat.a * Math.cosh(x / cat.a);
    const yp = Math.sinh(x / cat.a);
    const ypp = Math.cosh(x / cat.a) / cat.a;
    worst = Math.max(worst, Math.abs(y * ypp - (1 + yp * yp)));
  }
  ok('chain: catenary satisfies Euler–Lagrange  y·y″ = 1 + y′²', worst < 1e-9, `max resid ${worst.toExponential(2)}`);
}

// 4. BEAD. The cycloid holds y(1+y'^2) = 2r, and its Snell invariant sinθ/v is
//    constant (v = √(2y), g=1).
{
  const X = 1.0, Y = 0.8;
  const cyc = cycloidTo(X, Y, 2000);
  const fi = [], snell = [];
  for (let i = 1; i < cyc.phis.length; i++) {
    const phi = cyc.phis[i];
    const yp = Math.sin(phi) / (1 - Math.cos(phi));     // dy/dx on the cycloid
    const y = cyc.r * (1 - Math.cos(phi));
    fi.push(y * (1 + yp * yp));                          // should be 2r
    snell.push(beltrami(y, yp, F.bead));                 // sinθ/v
  }
  ok('bead: y(1+y′²) = 2r constant along the cycloid',
     std(fi) / (2 * cyc.r) < 1e-7 && approx(fi[0], 2 * cyc.r, 1e-5 * cyc.r),
     `value ${fi[0].toFixed(6)} = 2r (${(2 * cyc.r).toFixed(6)})`);
  ok('bead: Snell invariant sinθ/v constant along the cycloid',
     std(snell) / snell[0] < 1e-7,
     `value ${snell[0].toFixed(6)}, rel.std ${(std(snell) / snell[0]).toExponential(2)}`);
}

// 5. THE HISTORICAL HINGE — Bernoulli's 1697 light model. Slice the fall into
//    thin layers, refract a ray by Snell's law sinθ/v=const; as layers→∞ the
//    broken ray converges to the cycloid the brachistochrone race finds.
{
  const X = 1.0, Y = 0.8;
  const cyc = cycloidTo(X, Y, 4000);
  function rayErr(L) {
    const ray = bernoulliRay(X, Y, L);
    // compare ray (sampled at its y's) to the cycloid at the same depths
    let worst = 0;
    for (let i = 1; i < ray.ys.length; i++) {
      const y = ray.ys[i];
      // find cycloid x at this depth y by interpolation in phi
      // (cycloid y is monotone in phi on [0,phiEnd] for phiEnd<=2π up to bottom)
      let lo = 0, hi = cyc.phiEnd;
      for (let k = 0; k < 60; k++) {
        const mid = 0.5 * (lo + hi);
        const ym = cyc.r * (1 - Math.cos(mid));
        if (ym < y) lo = mid; else hi = mid;
      }
      const phi = 0.5 * (lo + hi);
      const cx = cyc.r * (phi - Math.sin(phi));
      worst = Math.max(worst, Math.abs(ray.xs[i] - cx));
    }
    return { worst, landErr: Math.abs(ray.xs[ray.xs.length - 1] - X), p: ray.p };
  }
  const coarse = rayErr(20), fine = rayErr(4000);
  ok('bead: Bernoulli broken ray lands on target (4000 layers)', fine.landErr < 2e-3, `Δx_end ${fine.landErr.toExponential(2)}`);
  ok('bead: broken ray → cycloid as layers thin (err shrinks)',
     fine.worst < coarse.worst && fine.worst < 5e-3,
     `max|Δx| 20→${coarse.worst.toFixed(4)},  4000→${fine.worst.toExponential(2)}`);
  // p is the same Snell invariant as the cycloid's Beltrami value.
  const yMid = 0.4, ypMid = Math.sqrt(Math.max((2 * cyc.r) / yMid - 1, 0));
  ok('bead: ray invariant p = cycloid Beltrami value', approx(fine.p, beltrami(yMid, ypMid, F.bead), 1e-6),
     `p ${fine.p.toFixed(6)} vs sinθ/v ${beltrami(yMid, ypMid, F.bead).toFixed(6)}`);
}

// ---------------------------------------------------------------------------
// 6. THE ONE ENGINE. A single routine, march(), integrates the SHARED first
//    integral f(y)·sinθ = C in arc length. It never learns which world it is in;
//    only f and C change. It reproduces all three closed forms.

// 6a. chain (f = y): march from the left endpoint down through the vertex (one
//     turning point) and back up; compare to a·cosh(x/a), where the invariant
//     C = a is literally the vertex height.
{
  const X = 1.2, yEnd = 1.9;
  const { a } = catenarySym(X, yEnd, 4000);
  // march the left half down to the vertex (stops there), then mirror by symmetry.
  const half = march(F.chain, -X, yEnd, -1, a, { ds: 1e-4, turns: 0 });
  const xv = half.xs[half.xs.length - 1];
  const fx = half.xs.slice(), fy = half.ys.slice();
  for (let i = half.xs.length - 2; i >= 0; i--) { fx.push(2 * xv - half.xs[i]); fy.push(half.ys[i]); }
  let worst = 0;
  for (let i = 0; i < fx.length; i++) worst = Math.max(worst, Math.abs(fy[i] - a * Math.cosh(fx[i] / a)));
  const spanOK = Math.abs(xv) < 3e-3 && Math.abs(fx[fx.length - 1] - X) < 3e-3;
  ok('engine: march(f=y) draws the full catenary  (vertex at x=0, C = vertex height a)',
     worst < 1e-3 && spanOK,
     `a ${a.toFixed(5)}, vertex x=${xv.toFixed(4)}, ends x=${fx[fx.length - 1].toFixed(4)} (want ${X}), max|Δy| vs cosh ${worst.toExponential(2)}`);
}

// 6b. bead (f = 1/√(2y)): march from the cusp downward; compare to the cycloid.
{
  const X = 1.0, Y = 0.7;
  const cyc = cycloidTo(X, Y, 4000);
  const C = 1 / (2 * Math.sqrt(cyc.r));            // = sinθ/v invariant
  const m = march(F.bead, 0, 1e-6, +1, C, { ds: 5e-5, yStop: Y, turns: 0 });
  let worst = 0;
  for (let i = 1; i < m.ys.length; i++) {
    const y = m.ys[i];
    let lo = 0, hi = cyc.phiEnd;
    for (let k = 0; k < 60; k++) { const mid = 0.5 * (lo + hi); (cyc.r * (1 - Math.cos(mid)) < y) ? (lo = mid) : (hi = mid); }
    const phi = 0.5 * (lo + hi);
    worst = Math.max(worst, Math.abs(m.xs[i] - cyc.r * (phi - Math.sin(phi))));
  }
  const landErr = Math.abs(m.xs[m.xs.length - 1] - X);
  ok('engine: march(f=1/√(2y)) draws the brachistochrone (cycloid)',
     worst < 5e-3 && landErr < 5e-3, `max|Δx| vs cycloid ${worst.toExponential(2)}, lands Δx ${landErr.toExponential(2)}`);
}

// 6c. light (f = n0 + k y): march the same routine; compare to an independent
//     Snell-ODE integration (dy/dx = √(n²−C²)/C).
{
  const f = F.light(1.0, 0.6), yL = 0.4, yR = 1.6, C = 0.9;
  const m = march(f, 0, yL, +1, C, { ds: 5e-5, yStop: yR, turns: 0 });
  const Xend = m.xs[m.xs.length - 1];
  const M = 20000, dx = Xend / M; let y = yL;
  for (let i = 0; i < M; i++) { const n = f(y); y += Math.sqrt(Math.max(n * n - C * C, 0)) / C * dx; }
  ok('engine: march(f=n) draws the light ray (matches Snell-ODE)',
     Math.abs(y - m.ys[m.ys.length - 1]) < 1e-3, `Δy_end vs ODE ${Math.abs(y - m.ys[m.ys.length - 1]).toExponential(2)}`);
}

// ---------------------------------------------------------------------------
// 6′. INDEPENDENT MINIMALITY. The curves are not just stationary — they are
//     minima. Gradient descent on the discrete action, from a generic start,
//     relaxes to the catenary and the light ray (the bead's vertical-tangent
//     cusp + 1/√y singularity defeat a uniform-x grid, so it is checked above
//     via the marcher and Bernoulli's ray instead — stated, not hidden).
{
  // chain: relax a flat start to the catenary.
  const X = 1.2, yEnd = 1.9, N = 81;
  const cat = catenarySym(X, yEnd, 4000);
  const xs = [], straight = [];
  for (let i = 0; i < N; i++) { const x = -X + 2 * X * i / (N - 1); xs.push(x); straight.push(yEnd); }
  const relaxed = relax(xs, straight, F.chain, { steps: 60000, floor: 1e-3 });
  const errC = xs.map((x, i) => relaxed.ys[i] - cat.a * Math.cosh(x / cat.a));
  ok('minimality: gradient descent relaxes to the catenary',
     maxAbs(errC) < 0.01 * yEnd, `max|Δy| ${maxAbs(errC).toFixed(5)} (${(100 * maxAbs(errC) / yEnd).toFixed(2)}% of height)`);

  // and the relaxed curve is a genuine minimum: random endpoint-pinned bumps
  // only increase the action.
  let allUp = true, trials = 0;
  for (let t = 0; t < 40; t++) {
    const pert = relaxed.ys.slice();
    for (let i = 1; i < N - 1; i++) pert[i] += 0.02 * yEnd * Math.sin((i * (t + 1) * 2.399));
    if (action(xs, pert, F.chain) <= relaxed.J) allUp = false;
    trials++;
  }
  ok('minimality: every perturbation of the catenary raises the action', allUp, `${trials}/${trials} perturbations increased J`);

  // light: relax to the ray and confirm Snell holds along it + matches the ODE.
  const f = F.light(1.0, 0.6), yLo = 0.4, yHi = 1.6, XL = 1.4, NN = 81;
  const lxs = [], lstart = [];
  for (let i = 0; i < NN; i++) { const tt = i / (NN - 1); lxs.push(XL * tt); lstart.push(yLo + (yHi - yLo) * tt); }
  const lr = relax(lxs, lstart, f, { steps: 80000, floor: 1e-3 });
  const inv = [];
  for (let i = 1; i < NN - 1; i++) inv.push(beltrami(lr.ys[i], (lr.ys[i + 1] - lr.ys[i - 1]) / (lxs[i + 1] - lxs[i - 1]), f));
  ok('minimality: relaxed light ray holds n(y)·sinθ constant (Snell)',
     std(inv) / Math.abs(inv[Math.floor(inv.length / 2)]) < 0.02,
     `rel.std ${(std(inv) / inv[Math.floor(inv.length / 2)]).toExponential(2)}`);
}

// ---------------------------------------------------------------------------
// 7. The three shapes are GENUINELY DIFFERENT — the unification is of the law,
//    not of the curves. Sample all three normalized to the unit box and show
//    pairwise max separation is large.
{
  const N = 81, norm = (xs, ys) => {
    const x0 = xs[0], x1 = xs[xs.length - 1];
    const ymin = Math.min(...ys), ymax = Math.max(...ys);
    return ys.map((y, i) => (y - ymin) / (ymax - ymin || 1));
  };
  const X = 1.0;
  const cat = catenarySym(0.5, 1.4, 4000);
  const catN = norm(cat.xs, cat.ys);                                   // symmetric, U-shaped
  const cyc = cycloidTo(1.0, 0.55, 4000); const cycU = onUniformX(cyc.xs, cyc.ys, 1.0, N);
  const cycN = norm(cycU.xs, cycU.ys);
  const lite = []; for (let i = 0; i < N; i++) lite.push(0.4 + 1.2 * (i / (N - 1)) ** 1.0); // a near-straight ray for contrast
  // resample catenary to N
  const catR = []; for (let i = 0; i < N; i++) { const t = i / (N - 1); const idx = Math.round(t * (catN.length - 1)); catR.push(catN[idx]); }
  let dCB = 0, dCL = 0, dBL = 0;
  for (let i = 0; i < N; i++) {
    dCB = Math.max(dCB, Math.abs(catR[i] - cycN[i]));
    dCL = Math.max(dCL, Math.abs(catR[i] - (lite[i] - 0.4) / 1.2));
    dBL = Math.max(dBL, Math.abs(cycN[i] - (lite[i] - 0.4) / 1.2));
  }
  ok('the three curves are genuinely distinct shapes', dCB > 0.1 && dBL > 0.1,
     `max separation chain~bead ${dCB.toFixed(2)}, bead~ray ${dBL.toFixed(2)}`);
}

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