#!/usr/bin/env node
// verify.mjs — the brachistochrone, recomputed from scratch.
//
// Claim 1 (BRACHISTOCHRONE): of all frictionless ramps between two fixed points,
//   the inverted cycloid is the curve of *quickest descent* — faster than the
//   straight line, the steep circular arc (Galileo's 1638 conjecture), or a
//   parabola. We do NOT assume this: we simulate a bead on each ramp with the
//   exact constrained-bead dynamics and time it.
// Claim 2 (TAUTOCHRONE): on ONE cycloid, beads released from rest at DIFFERENT
//   heights reach the bottom in the SAME time — Huygens 1659. The descent time
//   from the cusp to parameter θ is exactly √(a/g)·θ, so the bottom (θ=π) is
//   always reached in π√(a/g), independent of where you started. We check both
//   the simulation against this closed form, and the equal-arrival numerically.
//
// Geometry: A=(0,0) at top; y measured DOWNWARD as positive; B=(X,Y), Y>0.
// Energy conservation gives speed v=√(2 g y); the simulation never uses that as
// an input — it integrates dv/dt = g·(dy/ds) along the path and we *confirm*
// v(B)=√(2gY) falls out. g = 9.80665 m/s² (standard gravity).

const g = 9.80665;

// ---- the bead-on-a-rail simulator (shared logic with the page) -------------
// curve: array of {x,y} from A to B (y downward positive). Returns descent time.
function descentTime(pts, stepDt = 1e-5) {
  // cumulative arc length
  const s = [0];
  for (let i = 1; i < pts.length; i++) {
    const dx = pts[i].x - pts[i-1].x, dy = pts[i].y - pts[i-1].y;
    s.push(s[i-1] + Math.hypot(dx, dy));
  }
  const sTot = s[s.length - 1];
  // height and slope as functions of arc length, by interpolation
  let seg = 1;
  function at(sv) {
    if (sv <= 0) return { y: pts[0].y, dyds: slope(0) };
    if (sv >= sTot) return { y: pts[pts.length-1].y, dyds: slope(pts.length-2) };
    while (seg < pts.length - 1 && s[seg] < sv) seg++;
    while (seg > 1 && s[seg-1] > sv) seg--;
    const t = (sv - s[seg-1]) / (s[seg] - s[seg-1]);
    const y = pts[seg-1].y + t * (pts[seg].y - pts[seg-1].y);
    return { y, dyds: slope(seg-1) };
  }
  function slope(i) { // dy/ds on segment i..i+1
    const dx = pts[i+1].x - pts[i].x, dy = pts[i+1].y - pts[i].y;
    const ds = Math.hypot(dx, dy);
    return ds === 0 ? 0 : dy / ds;
  }
  // RK4 on (s,v): ds/dt=v, dv/dt = g·(dy/ds)
  let sv = 0, v = 0, t = 0;
  const dt = stepDt;
  const accel = (sval) => g * at(Math.max(0, Math.min(sTot, sval))).dyds;
  let guard = 0;
  while (sv < sTot && guard < 2e8) {
    const k1s = v,            k1v = accel(sv);
    const k2s = v + 0.5*dt*k1v, k2v = accel(sv + 0.5*dt*k1s);
    const k3s = v + 0.5*dt*k2v, k3v = accel(sv + 0.5*dt*k2s);
    const k4s = v + dt*k3v,     k4v = accel(sv + dt*k3s);
    sv += dt/6*(k1s + 2*k2s + 2*k3s + k4s);
    v  += dt/6*(k1v + 2*k2v + 2*k3v + k4v);
    t += dt;
    guard++;
  }
  return { t, vEnd: v, sTot };
}

// ---- the four ramps from A=(0,0) to B=(X,Y) --------------------------------
const X = 2.0, Y = 1.4;          // the default endpoint shown on the page
const N = 6000;                  // polyline resolution

function line() {
  const p = [];
  for (let i = 0; i <= N; i++) { const x = X*i/N; p.push({ x, y: Y*x/X }); }
  return p;
}
function parabolaPts(M) { // y = (Y/X^2) x^2  — starts FLAT at the apex (see divergence test below)
  const p = [];
  for (let i = 0; i <= M; i++) { const x = X*i/M; p.push({ x, y: (Y/(X*X))*x*x }); }
  return p;
}
function circleArc() { // circle tangent to the vertical at A, through B (Galileo's arc)
  const R = (X*X + Y*Y) / (2*X);   // center at (R,0)
  const p = [];
  for (let i = 0; i <= N; i++) {
    const x = X*i/N;
    const y = Math.sqrt(Math.max(0, R*R - (x-R)*(x-R))); // lower arc, y downward+
    p.push({ x, y });
  }
  return p;
}
function solveCycloidTheta(ratio) { // solve (1-cosθ)/(θ-sinθ)=ratio for θ in (0,2π)
  let lo = 1e-6, hi = 2*Math.PI - 1e-6;
  const f = (th) => (1 - Math.cos(th)) / (th - Math.sin(th)) - ratio;
  // f is monotone decreasing on (0,2π)
  for (let k = 0; k < 200; k++) {
    const mid = (lo + hi) / 2;
    if (f(mid) > 0) lo = mid; else hi = mid;
  }
  return (lo + hi) / 2;
}
function cycloid() {
  const thB = solveCycloidTheta(Y / X);
  const a = Y / (1 - Math.cos(thB));
  const p = [];
  for (let i = 0; i <= N; i++) {
    const th = thB*i/N;
    p.push({ x: a*(th - Math.sin(th)), y: a*(1 - Math.cos(th)) });
  }
  return { pts: p, a, thB };
}

const cyc = cycloid();
const ramps = {
  'straight line': line(),
  'circular arc (Galileo)': circleArc(),
  'cycloid (brachistochrone)': cyc.pts,
};

console.log(`Endpoints: A=(0,0)  B=(${X}, ${Y})   g=${g} m/s²`);
console.log(`Cycloid fit: a=${cyc.a.toFixed(6)}  θ_B=${cyc.thB.toFixed(6)} rad (${(cyc.thB/Math.PI).toFixed(4)}π)\n`);

const results = {};
for (const [name, pts] of Object.entries(ramps)) {
  const r = descentTime(pts);
  results[name] = r;
  console.log(`${name.padEnd(28)} T=${r.t.toFixed(5)} s   arc=${r.sTot.toFixed(4)} m   v(B)=${r.vEnd.toFixed(4)} m/s`);
}
const vTheory = Math.sqrt(2*g*Y);
console.log(`\nEnergy check: v(B) should be √(2gY)=${vTheory.toFixed(4)} m/s for every ramp ✓ (above)`);

// is the cycloid the minimum?
const times = Object.entries(results).map(([n,r]) => [n, r.t]).sort((a,b)=>a[1]-b[1]);
console.log(`\nFastest → slowest:`);
times.forEach(([n,t],i)=>console.log(`  ${i+1}. ${n.padEnd(28)} ${t.toFixed(5)} s`));
const winner = times[0][0];
console.log(`\nBRACHISTOCHRONE claim: winner = "${winner}"  → ${winner.startsWith('cycloid') ? 'CONFIRMED ✓' : 'FAILED ✗'}`);
const lineT = results['straight line'].t, cycT = results['cycloid (brachistochrone)'].t;
console.log(`Cycloid beats the straight line by ${((1 - cycT/lineT)*100).toFixed(2)}%  (${cycT.toFixed(4)}s vs ${lineT.toFixed(4)}s)`);
const dipsBelow = cyc.thB > Math.PI;
console.log(`Cycloid dips BELOW B then climbs back up to it: ${dipsBelow ? 'YES' : 'no'} (θ_B ${dipsBelow?'>':'<'} π)`);

// ---- THE FLAT-START RAMP NEVER ARRIVES (parabola y=kx², apex at A) ----------
// A bead at rest exactly at a point of ZERO slope feels zero tangential force, so
// it never starts moving: the true descent time is INFINITE. A naive simulation
// reports a finite number that is a pure discretisation artifact — and it GROWS
// without bound as the mesh/step are refined. We show that divergence rather than
// quote a fake finite time. (So this ramp is NOT raced on the page.)
console.log(`\n--- FLAT-START PARABOLA: descent time diverges (→ ∞) ---`);
for (const [M, dt] of [[900, 5e-5], [6000, 1e-5], [20000, 2e-6], [40000, 1e-6], [80000, 5e-7]]) {
  const r = descentTime(parabolaPts(M), dt);
  console.log(`  mesh M=${String(M).padStart(5)}  dt=${dt}   T=${r.t.toFixed(5)} s  (keeps growing — no convergence)`);
}
console.log(`  → conclusion: T_parabola = ∞ (a bead at a horizontal tangent, at rest, never leaves).`);

// ---- TAUTOCHRONE: one cycloid (full arch a=1), release from many heights ----
console.log(`\n--- TAUTOCHRONE (Huygens 1659) ---`);
const a = 1.0;
const bottomTheory = Math.PI * Math.sqrt(a/g);  // π√(a/g): cusp→bottom and (claim) any point→bottom
console.log(`Closed form: time to the bottom = π√(a/g) = ${bottomTheory.toFixed(6)} s  (independent of start height)`);
// build the full half-arch cycloid 0..π, then release a bead from a start parameter θ0
function cycloidPts(th0, th1, M=8000) {
  const p = [];
  for (let i = 0; i <= M; i++) {
    const th = th0 + (th1-th0)*i/M;
    p.push({ x: a*(th - Math.sin(th)), y: a*(1 - Math.cos(th)) });
  }
  return p;
}
// Release from θ0; the bead's speed depends on drop from its OWN start height.
// descentTime starts at rest at pts[0], so pts[0] is the release point. We time
// the run from θ0 down to the bottom θ=π.
console.log(`Released from θ0 → simulated time to the bottom (θ=π):`);
let maxDev = 0;
for (const th0 of [0.0001, Math.PI/6, Math.PI/3, Math.PI/2, 2*Math.PI/3, 5*Math.PI/6]) {
  const r = descentTime(cycloidPts(th0, Math.PI));
  const dev = Math.abs(r.t - bottomTheory);
  maxDev = Math.max(maxDev, dev);
  console.log(`  θ0=${(th0/Math.PI).toFixed(3)}π  start height y=${(a*(1-Math.cos(th0))).toFixed(4)}  →  T=${r.t.toFixed(6)} s   (Δ vs π√(a/g): ${(dev*1000).toFixed(3)} ms)`);
}
console.log(`\nTAUTOCHRONE claim: all arrival times equal π√(a/g) within ${(maxDev*1000).toFixed(2)} ms (sim step + polyline error) → ${maxDev < 5e-3 ? 'CONFIRMED ✓' : 'CHECK ✗'}`);

// cross-check the cusp→θ descent-time law T(θ)=√(a/g)·θ for the brachistochrone winner
console.log(`\n--- cross-check: cusp→θ descent law  T(θ)=√(a/g)·θ ---`);
for (const th of [Math.PI/2, Math.PI, cyc.thB]) {
  const r = descentTime(cycloidPts(0.0001, th));
  const law = Math.sqrt(a/g)*th;
  console.log(`  θ=${(th/Math.PI).toFixed(4)}π  sim T=${r.t.toFixed(6)}s   law √(a/g)·θ=${law.toFixed(6)}s   Δ=${(Math.abs(r.t-law)*1000).toFixed(3)} ms`);
}

// ============================================================================
//  Claim 3 (BERNOULLI'S OPTICAL SOLUTION) — added as the page's third instrument.
//  Johann Bernoulli (1696) solved the brachistochrone by treating the bead as a
//  ray of LIGHT crossing horizontal layers whose speed grows with depth as
//  v=√(2gy) (Galileo). Fermat's least-time principle + Snell's law of refraction
//  then say sin(φ)/v is CONSTANT along the path, where φ is the angle from the
//  vertical (the normal to the layers). We check two independent things:
//   3a. Along the TRUE cycloid B=(2,1.4), sin(φ)/v is constant and equals
//       1/(2√(g·a)) exactly — i.e. the falling bead really does obey Snell's law,
//       so the cycloid IS the refraction (least-time) path. This is the literal
//       content of "a mechanics problem, answered by optics."
//   3b. The discrete layered-refraction CONSTRUCTION (the operable instrument):
//       slice the descent into N uniform-speed layers, refract by Snell at each
//       interface with that same constant — and the resulting jagged ray converges
//       to the cycloid as N grows: its landing point approaches B and its descent
//       time approaches the cycloid's. (It approaches B from the near side; the
//       gap shrinks ~1/N.) Every number below is recomputed, none asserted.
// ============================================================================
console.log(`\n--- BERNOULLI'S OPTICAL SOLUTION: the bead refracts like light (sin φ / v = const) ---`);
let snellFails = 0;
const SA = (name, cond, got) => { const ok = !!cond; console.log(`  ${ok?'✓':'✗'} ${name}${got!==undefined?'  ('+got+')':''}`); if (!ok) snellFails++; return ok; };

// 3a. invariant along the true cycloid through B=(2,1.4)
const aB = cyc.a, thBrach = cyc.thB;           // brachistochrone cycloid radius & final parameter
const snellC = 1/(2*Math.sqrt(g*aB));          // predicted Snell invariant for this cycloid
let smin = Infinity, smax = -Infinity;
for (let i=1;i<=40;i++){
  const th = thBrach*i/40;
  const phi = th/2;                            // tangent angle from the vertical = θ/2
  const yy = aB*(1-Math.cos(th));
  const v  = Math.sqrt(2*g*yy);
  const ratio = Math.sin(phi)/v;
  smin = Math.min(smin, ratio); smax = Math.max(smax, ratio);
}
console.log(`  cycloid B=(${X},${Y}): a=${aB.toFixed(6)} m,  predicted 1/(2√(g·a)) = ${snellC.toFixed(6)} s/m`);
console.log(`  sin(φ)/v sampled at 40 points along the curve: [${smin.toFixed(8)}, ${smax.toFixed(8)}]`);
SA('sin(φ)/v is constant along the cycloid (Snell holds for the falling bead)', (smax-smin) < 1e-9, `spread ${(smax-smin).toExponential(2)}`);
SA('and that constant equals 1/(2√(g·a)) exactly', Math.abs(smin-snellC) < 1e-9, `${snellC.toFixed(6)} s/m`);

// 3b. the discrete layered-refraction construction converges to the cycloid
function buildRay(N){
  let x = 0; const pts = [{x:0,y:0}]; let maxDev = 0;
  for (let k=1;k<=N;k++){
    const y0 = Y*(k-1)/N, y1 = Y*k/N, ym = (y0+y1)/2;
    const v = Math.sqrt(2*g*ym);
    const sinT = Math.min(1, snellC*v);        // Snell: sin θ = C·v  (θ from vertical)
    maxDev = Math.max(maxDev, Math.abs(sinT/v - snellC));
    const theta = Math.asin(sinT);
    x += (y1-y0)*Math.tan(theta);
    pts.push({x, y:y1});
  }
  return { pts, landX:x, maxDev };
}
const cycTimeB = Math.sqrt(aB/g)*thBrach;      // analytic cycloid descent time = 0.80138 s
console.log(`\n  layered light-ray (Snell staircase) → cycloid, as the layer count N grows:`);
console.log(`    target finish X=${X} m;  cycloid descent time = ${cycTimeB.toFixed(5)} s`);
let lastGap = Infinity, lastTime = 0;
for (const N of [2,4,8,16,32,64,128]){
  const ray = buildRay(N);
  const gapCm = Math.abs(ray.landX - X)*100;
  const T = descentTime(ray.pts).t;            // integrate the ray with the SAME engine as every ramp
  lastGap = gapCm; lastTime = T;
  console.log(`    N=${String(N).padStart(3)}  lands x=${ray.landX.toFixed(4)} m  (gap ${gapCm.toFixed(3)} cm)   time ${T.toFixed(5)} s   sinθ/v dev ${ray.maxDev.toExponential(1)}`);
}
SA('Snell holds at every interface of the construction (sinθ/v = C by build)', buildRay(64).maxDev < 1e-12, `dev ${buildRay(64).maxDev.toExponential(1)}`);
SA('the layered ray converges to the finish B as N grows (gap < 0.4 cm at N=128)', lastGap < 0.4, `gap ${lastGap.toFixed(3)} cm`);
SA('and its descent time converges to the cycloid time from below', lastTime < cycTimeB && (cycTimeB-lastTime) < 0.002, `${lastTime.toFixed(5)} → ${cycTimeB.toFixed(5)} s`);

console.log('\n' + (snellFails ? `OPTICAL SECTION: FAIL — ${snellFails} assertion(s) drifted.` : 'OPTICAL SECTION: ALL GREEN.'));
console.log(`\n  numbers the page quotes (instrument 3):`);
console.log(`    Snell invariant 1/(2√(g·a)) .......... ${snellC.toFixed(4)} s/m  (constant down the path)`);
console.log(`    layered ray at N=64 .................. gap ${(Math.abs(buildRay(64).landX-X)*100).toFixed(2)} cm, time ${descentTime(buildRay(64).pts).t.toFixed(5)} s`);
console.log(`    cycloid descent time (target) ....... ${cycTimeB.toFixed(5)} s\n`);
process.exit(snellFails ? 1 : 0);
