// verify.mjs: checks for /strata/the-bend-that-doesnt-jolt/.
// Run: node research/the-bend-that-doesnt-jolt/verify.mjs
//
// It imports the page's own engine (public/strata/the-bend-that-doesnt-jolt/engine.mjs),
// not a copy, and holds every number the page states against something that was not
// computed the same way: 30-digit mpmath values (reference-mpmath.txt, typed in below),
// brute-force quadrature, a pendulum integrated step by step against its closed form,
// a rider's acceleration measured by differentiating position twice, and light summed
// wavelet by wavelet with exact path lengths. No network needed.
//
// ENGINE=<path> points it at another engine file; mutate.mjs uses that to check that
// a broken engine makes this fail.

import { pathToFileURL } from 'node:url';
import * as PageEngine from '../../public/strata/the-bend-that-doesnt-jolt/engine.mjs';

const E = process.env.ENGINE ? await import(pathToFileURL(process.env.ENGINE).href) : PageEngine;

let pass = 0, fail = 0;
const lines = [];
function ok(name, cond, detail = '') {
  cond ? pass++ : fail++;
  lines.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`);
}
const head = (t) => lines.push('', `-- ${t}`);
const fx = (v, d = 4) => Number(v).toFixed(d);

// 10-point Gauss-Legendre on [a, b], composite over n panels.
const GLX = [0.1488743389816312, 0.4333953941292472, 0.6794095682990244, 0.8650633666889845, 0.9739065285171717];
const GLW = [0.2955242247147529, 0.2692667193099963, 0.2190863625159820, 0.1494513491505806, 0.0666713443086881];
function quad(f, a, b, n) {
  const h = (b - a) / n; let sum = 0;
  for (let i = 0; i < n; i++) {
    const m = a + (i + 0.5) * h, r = h / 2;
    for (let j = 0; j < 5; j++) sum += GLW[j] * r * (f(m + r * GLX[j]) + f(m - r * GLX[j]));
  }
  return sum;
}

// ---------------------------------------------------------------------------
head('1. The Fresnel integrals that draw the curve');
{
  // mpmath 1.4.1 at 30 digits (reference.py -> reference-mpmath.txt)
  const REF = [
    [0.25, 0.24975915035654318346, 0.0081756002357777557781],
    [0.5, 0.49234422587144639288, 0.064732432859999277611],
    [1, 0.77989340037682282947, 0.43825914739035476608],
    [1.5, 0.44526117603982153506, 0.69750496008209301308],
    [2, 0.4882534060753407545, 0.3434156783636982422],
    [2.5, 0.45741300964177704525, 0.61918175581959293611],
    [3, 0.60572078929768562956, 0.4963129989673750361],
    [3.4, 0.43849170336380294753, 0.4296494644439268644],
    [3.5, 0.53257243502800084533, 0.4152480119724375239],
    [3.6, 0.58795325967341559303, 0.492309489111001503],
    [4, 0.49842603303817761553, 0.42051575424692842445],
    [5, 0.5636311887040122311, 0.49919138191711688675],
    [7, 0.54546709254696981033, 0.49970478945344677587],
    [10, 0.49989869420551572361, 0.4681699785848822404],
    [20, 0.49998733497234438819, 0.48408453592595389271],
  ];
  let worst = 0, at = 0;
  for (const [z, c, s] of REF) {
    const [c1, s1] = E.fresnel(z);
    const e = Math.max(Math.abs(c1 - c), Math.abs(s1 - s));
    if (e > worst) { worst = e; at = z; }
  }
  ok('C(z), S(z) agree with 30-digit mpmath at 15 points from 0.25 to 20', worst < 2e-9, `worst |error| ${worst.toExponential(2)} at z = ${at}`);

  let worstQ = 0, atQ = 0;
  for (let z = -8; z <= 8.0001; z += 0.05) {
    const n = Math.max(4, Math.ceil(Math.abs(z) * Math.abs(z) * 4));
    const cq = quad((t) => Math.cos(Math.PI * t * t / 2), 0, z, n);
    const sq = quad((t) => Math.sin(Math.PI * t * t / 2), 0, z, n);
    const [c1, s1] = E.fresnel(z);
    const e = Math.max(Math.abs(c1 - cq), Math.abs(s1 - sq));
    if (e > worstQ) { worstQ = e; atQ = z; }
  }
  ok('and agree with brute-force Gauss-Legendre quadrature on 321 points from -8 to 8', worstQ < 5e-9, `worst |error| ${worstQ.toExponential(2)} at z = ${fx(atQ, 2)}`);

  const [cInf, sInf] = E.fresnel(1e4);
  ok('both tend to 1/2 (the eye of the spiral sits at (1/2, 1/2))', Math.abs(cInf - 0.5) < 1e-4 && Math.abs(sInf - 0.5) < 1e-4, `C(10^4) = ${fx(cInf, 6)}, S(10^4) = ${fx(sInf, 6)}`);

  // the two halves of the implementation meet cleanly at the switch z = 3.5
  const a = E.fresnelSeries(3.5), b = E.fresnelAsymptotic(3.5);
  ok('the power series and the asymptotic form agree where the engine switches between them', Math.abs(a[0] - b[0]) < 2e-9 && Math.abs(a[1] - b[1]) < 2e-9,
    `|ΔC| ${Math.abs(a[0] - b[0]).toExponential(1)}, |ΔS| ${Math.abs(a[1] - b[1]).toExponential(1)}`);
}

// ---------------------------------------------------------------------------
head('2. What the curve is: curvature grows in proportion to length');
{
  const A = 40;
  let worst = 0;
  for (let s = 5; s <= 120; s += 5) {
    const h = 1e-2;
    const p0 = E.spiralPoint(s - h, A), p1 = E.spiralPoint(s, A), p2 = E.spiralPoint(s + h, A);
    // curvature of three points: 2·cross / (|a||b||c|)
    const ax = p1[0] - p0[0], ay = p1[1] - p0[1], bx = p2[0] - p1[0], by = p2[1] - p1[1];
    const cx = p2[0] - p0[0], cy = p2[1] - p0[1];
    const k = 2 * (ax * by - ay * bx) / (Math.hypot(ax, ay) * Math.hypot(bx, by) * Math.hypot(cx, cy));
    worst = Math.max(worst, Math.abs(k - s / (A * A)) / (s / (A * A)));
    // and the points are one unit of arclength per unit of s
  }
  ok('curvature measured off the drawn points equals s/A² along the whole arm', worst < 1e-5, `worst relative error ${worst.toExponential(2)} (A = 40 m, s = 5..120 m)`);

  let worstLen = 0;
  for (let s = 0; s < 200; s += 10) {
    const p = E.spiralPoint(s, A), q = E.spiralPoint(s + 0.01, A);
    worstLen = Math.max(worstLen, Math.abs(Math.hypot(q[0] - p[0], q[1] - p[1]) - 0.01) / 0.01);
  }
  ok('the parameter is arclength (a step of 1 cm along s moves the point 1 cm)', worstLen < 1e-6, `worst ${worstLen.toExponential(2)}`);
}

// ---------------------------------------------------------------------------
head('3. The ride: a car at constant speed');
{
  const v = 25, R = 250, Ls = 25;
  const tr = E.makeTrack({ R, Ls });
  const S = E.rideSummary(tr, v);
  ok('on the arc the car accelerates sideways at v²/R', Math.abs(S.aArc - 2.5) < 1e-12, `v = 25 m/s, R = 250 m: ${fx(S.aArc, 3)} m/s² = ${fx(S.aArcG, 3)} g`);

  // measure jerk by finite differences of a(t) sampled along the drive
  const dt = 0.001;
  const js = [];
  for (let t = 0; t < tr.total / v; t += dt) {
    const a0 = E.ride(tr, v, t * v).a, a1 = E.ride(tr, v, (t + dt) * v).a;
    js.push([t, (a1 - a0) / dt]);
  }
  const onSpiral = js.filter(([t]) => t * v > tr.edges[1] + 0.1 && (t + dt) * v < tr.edges[2] - 0.1).map(([, j]) => j);
  const spread = Math.max(...onSpiral) - Math.min(...onSpiral);
  ok('on the spiral the jerk, measured as Δa/Δt along the drive, is constant', spread < 1e-6, `${onSpiral.length} samples, all ${fx(onSpiral[0], 4)} m/s³ (spread ${spread.toExponential(1)})`);
  ok('and equals v³/(R·Ls), the engine\'s stated value', Math.abs(onSpiral[0] - S.jerk) < 1e-6, `v³/(R·Ls) = ${fx(S.jerk, 4)} m/s³`);
  const offSpiral = js.filter(([t]) => (t * v < tr.edges[1] - 0.1) || (t * v > tr.edges[2] + 0.1 && (t + dt) * v < tr.edges[3] - 0.1)).map(([, j]) => Math.abs(j));
  ok('on the straight and on the arc the jerk is zero', Math.max(...offSpiral) < 1e-9);

  const tr0 = E.makeTrack({ R, Ls: 0 });
  const before = E.ride(tr0, v, tr0.edges[1] - 1e-6).a, after = E.ride(tr0, v, tr0.edges[1] + 1e-6).a;
  ok('with no spiral, sideways acceleration jumps from 0 to v²/R in no distance at all', before === 0 && Math.abs(after - 2.5) < 1e-12, `${before} -> ${after} m/s² across 2 µm of track`);

  // the track's spiral is the Euler spiral with A² = R·Ls
  const pts = E.trackPoints(tr, 0.05);
  const A = Math.sqrt(R * Ls);
  const h = tr.total / (pts.length - 1);
  let worst = 0, count = 0;
  pts.forEach(([x, y], i) => {
    const s = i * h - tr.edges[1];
    if (s < 0 || s > Ls) return;
    const [sx, sy] = E.spiralPoint(s, A);
    worst = Math.max(worst, Math.hypot(x - (tr.edges[1] + sx), y - sy)); count++;
  });
  ok('the entry spiral of the integrated track lies on the Euler spiral with A² = R·Ls', worst < 1e-4, `worst gap ${(worst * 1e6).toFixed(3)} µm at ${count} points over 25 m`);
  const endHeading = pts[pts.length - 1][2];
  ok('the whole bend turns through exactly the right angle', Math.abs(endHeading - Math.PI / 2) < 1e-9, `${fx(endHeading * 180 / Math.PI, 9)}°`);
  {
    // the arc's centre sits R + shift from the line of the straight
    const iArc = Math.round((tr.edges[2] + 1) / h);
    const [, y, th] = pts[iArc];
    const shift = y + R * Math.cos(th) - R;
    const approx = Ls * Ls / (24 * R);
    ok('a spiral moves the circle inward by about Ls²/(24R), the surveyors\' "shift"', Math.abs(shift - approx) / approx < 0.01, `measured ${fx(shift * 1000, 2)} mm, Ls²/(24R) = ${fx(approx * 1000, 2)} mm`);
  }
}

// ---------------------------------------------------------------------------
head('4. The pendulum hanging in the car');
{
  const v = 25, R = 250;
  const ell = 0.25;
  const w = Math.sqrt(E.G / ell);
  const period = 2 * Math.PI / w;
  const aG = (v * v / R) / E.G;
  const resid = (Ls) => {
    const tr = E.makeTrack({ R, Ls });
    const { samples } = E.pendulum(tr, v, { ell, zeta: 0, dt: 1 / 2000, tail: 0 });
    // swing about the rest angle a/g while on the arc, after the entry spiral has ended
    const t0 = tr.edges[2] / v + 0.05, t1 = tr.edges[3] / v - 0.05;
    let lo = Infinity, hi = -Infinity;
    for (const [t, p] of samples) if (t > t0 && t < t1) { lo = Math.min(lo, p); hi = Math.max(hi, p); }
    return { swing: (hi - lo) / 2, peak: hi, T: Ls / v, spanPeriods: (t1 - t0) / period };
  };
  const step = resid(0);
  ok('a hard entry (no spiral) swings the pendulum out to twice its resting angle', Math.abs(step.peak / aG - 2) < 0.005, `peak ${fx(step.peak / aG, 4)} × a/g (undamped, integrated)`);
  ok('and leaves it swinging by the full resting angle either side', Math.abs(step.swing / aG - 1) < 0.005, `${fx(step.swing / aG, 4)} × a/g`);

  let worst = 0; const rows = [];
  for (const Ls of [5, 10, 15, 20, 30, 40, 50, 75, 100]) {
    const r = resid(Ls);
    const cf = E.residualSwing(aG, w, r.T);
    worst = Math.max(worst, Math.abs(r.swing - cf) / aG);
    rows.push(`${Ls}m:${fx(r.swing / aG, 3)}/${fx(cf / aG, 3)}`);
  }
  ok('for a spiral of any length the swing left over matches (a/g)|sin(ωT/2)/(ωT/2)|', worst < 0.005, `integrated/closed form: ${rows.join(' ')}`);

  const LsZero = v * period; // spiral takes exactly one period
  const z = resid(LsZero);
  ok('a spiral that takes exactly one pendulum period leaves it perfectly still', z.swing / aG < 0.002, `Ls = ${fx(LsZero, 2)} m (${fx(period, 4)} s at 25 m/s), swing ${fx(z.swing / aG, 5)} × a/g`);

  // The factor of two is not an artefact of the small-angle model. Full equation for a rigid
  // pendulum whose pivot is suddenly given a steady sideways acceleration a:
  //   ℓφ'' = −g sin φ + a cos φ.  From rest at φ = 0 it must swing to exactly 2·atan(a/g).
  {
    const a = v * v / R;
    let p = 0, q = 0, peak = 0; const dt = 1e-4;
    const f = (pp) => (-E.G * Math.sin(pp) + a * Math.cos(pp)) / ell;
    for (let i = 0; i < 20000; i++) {
      const k1p = q, k1q = f(p), k2p = q + dt / 2 * k1q, k2q = f(p + dt / 2 * k1p);
      const k3p = q + dt / 2 * k2q, k3q = f(p + dt / 2 * k2p), k4p = q + dt * k3q, k4q = f(p + dt * k3p);
      p += dt / 6 * (k1p + 2 * k2p + 2 * k3p + k4p); q += dt / 6 * (k1q + 2 * k2q + 2 * k3q + k4q);
      peak = Math.max(peak, p);
    }
    const exact = 2 * Math.atan(a / E.G);
    ok('the full, large-angle pendulum also swings to exactly twice its resting angle', Math.abs(peak - exact) < 1e-6, `peak ${fx(peak * 180 / Math.PI, 5)}°, 2·atan(a/g) = ${fx(exact * 180 / Math.PI, 5)}° (resting angle ${fx(Math.atan(a / E.G) * 180 / Math.PI, 2)}°, small-angle model ${fx(a / E.G * 180 / Math.PI, 2)}°)`);
  }
  {
    // past the first zero (ωT = 2π) the left-over swing never again exceeds max |sin x / x| for x ≥ π
    let m = 0, at = 0;
    for (let x = Math.PI; x < 200; x += 1e-4) { const y = Math.abs(Math.sin(x) / x); if (y > m) { m = y; at = x; } }
    ok('once the spiral lasts longer than one swing, the left-over swing never exceeds 22% of the resting angle', m < 0.2173 && m > 0.2171, `largest later lobe ${fx(m, 4)} at ωT/2 = ${fx(at, 3)}`);
  }
}

// ---------------------------------------------------------------------------
head('5. The loop');
{
  // circle: gTop + 6 g at the bottom, whatever the size
  let worst = 0; const seen = [];
  for (const H of [5, 30, 100]) for (const gTop of [0, 0.5, 1]) {
    const l = E.loop({ alpha: 0, H, gTop });
    worst = Math.max(worst, Math.abs(l.entryFelt - (gTop + 6)));
    seen.push(fx(l.entryFelt, 3));
  }
  ok('a circular loop gives the rider gTop + 6 g on entry, for heights 5, 30 and 100 m', worst < 1e-6, `felt at entry: ${seen.join(', ')}`);

  for (const alpha of [0, 0.5, 1]) {
    const l = E.loop({ alpha, H: 30, gTop: 0.5 });
    const top = l.half[l.half.length - 1];
    ok(`α = ${alpha}: the half-loop ends upside down at the stated height`, Math.abs(top.th - Math.PI) < 1e-12 && Math.abs(top.y - 30) < 1e-9, `heading ${fx(top.th * 180 / Math.PI, 6)}°, height ${fx(top.y, 6)} m`);
    ok(`α = ${alpha}: the rider feels the requested 0.5 g at the top`, Math.abs(top.felt - 0.5) < 1e-9, fx(top.felt, 9));
  }

  // Independent: ride the curve in time and differentiate position twice. The engine's
  // points are timed (dt = ds / v), resampled on a uniform clock by cubic Hermite
  // interpolation (position and velocity both known at every point), and the felt g is
  // (acceleration − gravity) along the inward normal: no use of v²κ anywhere.
  for (const alpha of [0, 0.6, 1]) {
    const l = E.loop({ alpha, H: 30, gTop: 0.5 });
    const P = l.half;
    const t = [0];
    for (let i = 1; i < P.length; i++) t.push(t[i - 1] + (P[i].s - P[i - 1].s) * 0.5 * (1 / P[i].v + 1 / P[i - 1].v));
    const find = (tt) => { let lo = 0, hi = t.length - 1; while (hi - lo > 1) { const m = (lo + hi) >> 1; if (t[m] <= tt) lo = m; else hi = m; } return lo; };
    const pos = (tt) => {
      const i = find(tt), j = i + 1, h = t[j] - t[i], u = (tt - t[i]) / h;
      const h00 = 2 * u ** 3 - 3 * u ** 2 + 1, h10 = u ** 3 - 2 * u ** 2 + u, h01 = -2 * u ** 3 + 3 * u ** 2, h11 = u ** 3 - u ** 2;
      const vx = (p) => p.v * Math.cos(p.th), vy = (p) => p.v * Math.sin(p.th);
      return [h00 * P[i].x + h10 * h * vx(P[i]) + h01 * P[j].x + h11 * h * vx(P[j]),
              h00 * P[i].y + h10 * h * vy(P[i]) + h01 * P[j].y + h11 * h * vy(P[j])];
    };
    const dtU = 0.01, T = t[t.length - 1];
    let worstF = 0, peakMeasured = -Infinity, peakEngine = -Infinity;
    for (let tt = 2 * dtU; tt < T - 2 * dtU; tt += dtU) {
      const a = pos(tt - dtU), b = pos(tt), c = pos(tt + dtU);
      const ax = (a[0] - 2 * b[0] + c[0]) / (dtU * dtU), ay = (a[1] - 2 * b[1] + c[1]) / (dtU * dtU);
      const vxx = (c[0] - a[0]) / (2 * dtU), vyy = (c[1] - a[1]) / (2 * dtU);
      const sp = Math.hypot(vxx, vyy), nx = -vyy / sp, ny = vxx / sp; // inward normal, from the motion
      const felt = (ax * nx + (ay + E.G) * ny) / E.G;
      const i = find(tt), f = (tt - t[i]) / (t[i + 1] - t[i]);
      const eng = P[i].felt + f * (P[i + 1].felt - P[i].felt);
      worstF = Math.max(worstF, Math.abs(felt - eng));
      peakMeasured = Math.max(peakMeasured, felt); peakEngine = Math.max(peakEngine, eng);
    }
    ok(`α = ${alpha}: g felt, measured by differentiating the ride's position twice, matches the engine`, worstF < 0.005, `worst gap ${fx(worstF, 4)} g; highest ${fx(peakMeasured, 3)} measured vs ${fx(peakEngine, 3)} engine`);
  }

  const c = E.loop({ alpha: 0, H: 30, gTop: 0.5 }), k = E.loop({ alpha: 1, H: 30, gTop: 0.5 });
  ok('a clothoid loop of the same height and the same top feel starts at 1 g, because its curvature starts at zero', Math.abs(k.entryFelt - 1) < 1e-12, fx(k.entryFelt, 6));
  ok('and its hardest moment is well under the circle\'s', k.peakFelt < c.peakFelt - 2, `peak ${fx(k.peakFelt, 2)} g (at ${fx(k.peakHeight, 1)} m, heading ${fx(k.peakHeading * 180 / Math.PI, 0)}°) against the circle's ${fx(c.peakFelt, 2)} g at the bottom`);
  ok('and it needs less speed at the bottom to get round', k.vBottom < c.vBottom, `${fx(k.vBottom, 2)} m/s against ${fx(c.vBottom, 2)} m/s`);
}

// ---------------------------------------------------------------------------
head('6. Light past a straight edge, read off the same spiral');
{
  ok('at the geometric edge of the shadow the light is exactly a quarter of its full strength', Math.abs(E.knifeEdge(0) - 0.25) < 1e-15, fx(E.knifeEdge(0), 12));
  const ex = E.knifeEdgeExtrema(4);
  // mpmath findroot values (reference-mpmath.txt)
  const REF = [[1.21719825074, 1.3704429197], [1.87251906244, 0.778251047026], [2.34448538242, 1.19927120345], [2.73900808064, 0.843161897416]];
  let worst = 0;
  ex.forEach((e, i) => { if (!REF[i]) return; worst = Math.max(worst, Math.abs(e.w - REF[i][0]), Math.abs(e.I - REF[i][1])); });
  ok('the first bright fringe is 1.370 times the unobstructed light, and the next three extrema agree with mpmath', ex.length === 4 && ex[0].kind === 'max' && worst < 1e-6,
    ex.map((e) => `${e.kind} ${fx(e.I, 4)} at w=${fx(e.w, 4)}`).join('; '));

  // Fresnel's own table, computed by hand around 1818: "Table of maxima and minima for
  // exterior fringes and of the corresponding intensities", in Crew (ed.), The Wave Theory
  // of Light (1900), p. 124. His intensities are on a scale where the unobstructed light is
  // 2 ("add to each 1/2, and finally take the sum of their squares").
  const FRESNEL = [['max', 1.2172, 2.7413], ['min', 1.8726, 1.5570], ['max', 2.3449, 2.3990]];
  let worstV = 0, worstI = 0; const fr = [];
  FRESNEL.forEach(([kind, v, I2], i) => {
    const e = ex[i]; if (!e || e.kind !== kind) { worstV = Infinity; return; }
    worstV = Math.max(worstV, Math.abs(e.w - v)); worstI = Math.max(worstI, Math.abs(2 * e.I - I2));
    fr.push(`${kind} v ${v}/${fx(e.w, 4)}, I ${I2}/${fx(2 * e.I, 4)}`);
  });
  ok('and agree with the table Fresnel computed by hand, to within his last digit or so', worstV < 5e-4 && worstI < 6e-4, `Fresnel/engine: ${fr.join('; ')}`);

  // Cornu construction: half the squared chord from the spiral point at -w to the eye (1/2, 1/2)
  let worstC = 0;
  for (let w = -4; w <= 6; w += 0.1) {
    const [c, s] = E.fresnel(-w);
    const chord2 = (0.5 - c) ** 2 + (0.5 - s) ** 2;
    worstC = Math.max(worstC, Math.abs(chord2 / 2 - E.knifeEdge(w)));
  }
  ok('the intensity is half the squared chord of the Cornu spiral, point by point', worstC < 1e-12, `worst ${worstC.toExponential(1)}`);

  // Independent: Huygens with exact path lengths, no Fresnel approximation.
  // A plane wave hits a half-plane edge at y = 0; the open side is y > 0 out to Y, tapered
  // smoothly to zero past Y1 so the far end does not add fringes of its own. The 2D
  // (line-source) wavelet from y reaching the screen point x at distance z has amplitude
  // ∝ r^(-1/2) e^{ikr} (1 + cos χ)/2. Normalised by the same sum with the edge removed.
  const lambda = 0.5e-6, z = 1.0, kw = 2 * Math.PI / lambda;
  const Y1 = 0.012, Y2 = 0.018, dy = lambda / 12;
  const huygens = (x, yStart) => {
    let re = 0, im = 0;
    for (let y = yStart; y < Y2; y += dy) {
      const taper = y < Y1 ? (y > -Y1 ? 1 : 0.5 * (1 - Math.cos(Math.PI * (y + Y2) / (Y2 - Y1)))) : 0.5 * (1 + Math.cos(Math.PI * (y - Y1) / (Y2 - Y1)));
      if (y < -Y2) continue;
      const r = Math.hypot(z, x - y);
      const amp = taper / Math.sqrt(r) * (1 + z / r) / 2;
      re += amp * Math.cos(kw * r); im += amp * Math.sin(kw * r);
    }
    return re * re + im * im;
  };
  const I0 = huygens(0, -Y2);
  const scale = E.fresnelScale(lambda, z);
  let worstH = 0; const row = [];
  for (const w of [-1.5, -0.5, 0, 0.5, 1.2172, 1.8725, 2.5, 3.5]) {
    const x = w * scale;
    // the open side is y > 0, so a screen point at x > 0 is in the light
    const Ih = huygens(x, 0) / I0;
    const Ie = E.knifeEdge(w);
    worstH = Math.max(worstH, Math.abs(Ih - Ie));
    row.push(`w=${w}: ${fx(Ih, 3)}/${fx(Ie, 3)}`);
  }
  ok('a brute-force Huygens sum with exact path lengths reproduces the fringes (λ = 0.5 µm, z = 1 m)', worstH < 0.01, `${Math.round(Y2 / dy).toLocaleString('en')} wavelets per lit point; worst gap ${fx(worstH, 4)}; Huygens/engine: ${row.join('  ')}`);
}

console.log(lines.join('\n'));
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
