// verify-the-blade-the-camera-bent.mjs — the kinematics behind the stratum
// "The Blade the Camera Bent" (/strata/the-blade-the-camera-bent/).
//
// THE CLAIM the page makes, and that this script recomputes from scratch:
//
//   A rolling-shutter CMOS sensor does not expose all rows at once. It reads
//   them top-to-bottom, one line after the next, with a per-line delay tau
//   (the "line time"). A blade spinning at angular velocity omega is therefore
//   photographed at a slightly later instant on each lower row. The apparent
//   angle of a straight radial blade, imaged at sensor row y (rows from the
//   top), is exactly
//
//        theta(y) = theta0 + omega * (y * tau).                          (1)
//
//   So a straight blade images as a curve whose local slope, in angle per row,
//   is the CONSTANT  k = omega * tau  (radians/row). That single number is the
//   "clock" hidden in the bend: invert the imaged curve to recover k, and then
//
//        given a known RPM (=> known omega)  ->  recover tau (the line time),
//        given a measured tau                ->  recover RPM.
//
// This is pure kinematics plus the documented row-sequential readout model.
// The model generates unwrapped angle samples from omega and tau. The slope fit
// consumes those samples, and RPM conversion uses the known tau. This checks
// the model algebra; it does not measure rendered coordinates or canvas pixels.
//
//   run:  node research/the-blade-the-camera-bent/verify-the-blade-the-camera-bent.mjs
//
// No dependencies. Every number the page displays for its worked example is
// recomputed here and asserted.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;
const TWO_PI = Math.PI * 2;

// ── kinematics ──────────────────────────────────────────────────────────────
const omegaFromRPM = (rpm) => rpm * TWO_PI / 60;          // rad/s
const rpmFromOmega = (w) => w * 60 / TWO_PI;              // rpm
// (1): apparent angle of a straight radial blade at row y, line time tau (s/row)
const thetaAt = (theta0, omega, tau, y) => theta0 + omega * (y * tau);

// ── 1. The forward model: a straight blade bends by exactly omega*tau per row ─
console.log('\n— forward model: apparent angle theta(y) = theta0 + omega*tau*y —');
{
  const rpm = 3000, theta0 = 0;
  const omega = omegaFromRPM(rpm);
  // a "slow" consumer CMOS: full-frame readout T = 1/30 s over N = 1080 rows
  const N = 1080, Tread = 1 / 30;        // 33.33 ms full read
  const tau = Tread / N;                 // per-line time, s/row
  const k = omega * tau;                 // the clock: rad per row
  // slope is constant: the difference between any two adjacent rows equals k
  const d1 = thetaAt(theta0, omega, tau, 1) - thetaAt(theta0, omega, tau, 0);
  const d2 = thetaAt(theta0, omega, tau, 538) - thetaAt(theta0, omega, tau, 537);
  ok('angle per sensor row is constant across the frame',
     approx(d1, d2, 1e-15) && approx(d1, k, 1e-15), `k=${k.toExponential(4)} rad/row`);
  // total skew top-to-bottom = omega * T_readout
  const skewTotal = thetaAt(theta0, omega, tau, N) - theta0;
  ok('total bend over the frame = omega * T_readout',
     approx(skewTotal, omega * Tread, 1e-12),
     `${(skewTotal * 180 / Math.PI).toFixed(1)} deg over ${(Tread * 1000).toFixed(2)} ms`);
  // sanity on the line time itself: ~30.9 microseconds for a 1/30 s / 1080-row read
  ok('line time tau in the documented microsecond band (5–35 us)',
     tau > 5e-6 && tau < 35e-6, `tau=${(tau * 1e6).toFixed(2)} us/row`);
}

// ── 2. The inversion RECOVERS omega*tau from the curve with no prior knowledge ─
// Sample the imaged curve at points (y_i, theta_i), then recover the slope k by
// ordinary least squares. The recovered k must equal omega*tau; dividing by a
// known omega gives back tau, dividing by a known tau gives back RPM.
console.log('\n— inversion: recover k = omega*tau from sampled curve points —');
function lsqSlope(ys, ths) {                 // slope of theta vs y, through the cloud
  const n = ys.length;
  let sy = 0, st = 0, syy = 0, syt = 0;
  for (let i = 0; i < n; i++) { sy += ys[i]; st += ths[i]; syy += ys[i] * ys[i]; syt += ys[i] * ths[i]; }
  return (n * syt - sy * st) / (n * syy - sy * sy);
}
{
  // a worked example matching the page's default reading:
  const rpm = 600, blades = 2;
  const omega = omegaFromRPM(rpm);
  const N = 1080, Tread = 1 / 30, tau = Tread / N;
  const kTrue = omega * tau;
  // synthesize 40 sampled rows of the bent blade, theta0 unknown to the inverter
  const theta0 = 0.7;            // arbitrary start angle, recovered as the intercept
  const ys = [], ths = [];
  for (let i = 0; i < 40; i++) {
    const y = Math.round(i * (N - 1) / 39);
    ys.push(y);
    ths.push(thetaAt(theta0, omega, tau, y));   // generated, unwrapped model samples
  }
  const kRec = lsqSlope(ys, ths);               // RECOVERED, no omega/tau used
  ok('recovered k matches omega*tau (the bend IS the clock)',
     approx(kRec, kTrue, 1e-12), `kRec=${kRec.toExponential(6)} vs ${kTrue.toExponential(6)}`);

  // given KNOWN rpm -> recover tau (the sensor line time)
  const tauRec = kRec / omega;
  ok('given known RPM, recovered tau matches the true line time',
     approx(tauRec, tau, 1e-15), `tauRec=${(tauRec * 1e6).toFixed(3)} us vs ${(tau * 1e6).toFixed(3)} us`);

  // given KNOWN tau -> recover RPM
  const omegaRec = kRec / tau;
  const rpmRec = rpmFromOmega(omegaRec);
  ok('given known tau, recovered RPM matches the true RPM',
     approx(rpmRec, rpm, 1e-6), `rpmRec=${rpmRec.toFixed(2)} vs ${rpm}`);

  // and blades just replicate the same arc rotated by 2pi/B — same slope k
  const armOffset = TWO_PI / blades;
  const kArm2 = (thetaAt(theta0 + armOffset, omega, tau, N - 1)
                 - (theta0 + armOffset)) / (N - 1);
  ok('every blade arm bends by the same per-row k', approx(kArm2, kTrue, 1e-12));
}

// ── 3. Global shutter (tau = 0) ⇒ the blade is perfectly straight ────────────
console.log('\n— global shutter limit: tau -> 0 snaps the blade straight —');
{
  const omega = omegaFromRPM(5000);
  const N = 1080;
  let maxDev = 0;
  for (let y = 0; y <= N; y++) maxDev = Math.max(maxDev, Math.abs(thetaAt(0, omega, 0, y)));
  ok('with tau = 0 the apparent angle is constant for every row (no bend)',
     approx(maxDev, 0, 1e-15), `max angular deviation = ${maxDev}`);
}

// ── 4. The page's DEFAULT reading: the exact numbers the HTML displays on load ─
// These figures are shown in the page's readouts and "the check" panel. If the
// page or the formula drifts, this catches it. Default chosen so the bend is a
// clean, recognisable ~120 deg hook (not a full-turn tangle).
console.log('\n— pinned DEFAULT numbers shown on the page (rpm 600) —');
{
  const rpm = 600, N = 1080, Tread = 1 / 30;
  const tau = Tread / N;
  const omega = omegaFromRPM(rpm);
  const k = omega * tau;
  const totalDeg = (omega * Tread) * 180 / Math.PI;
  // round exactly as the page does
  const tau_us = +(tau * 1e6).toFixed(2);     // microseconds/row, 2dp
  const omega_disp = +omega.toFixed(1);       // rad/s, 1dp
  const k_mrad = +(k * 1e3).toFixed(2);       // milli-rad/row, 2dp
  const total_disp = +totalDeg.toFixed(1);    // degrees, 1dp
  console.log(`  RPM 600, ${N} rows, T_read 1/30 s  ->  tau=${tau_us} us/row,` +
              ` omega=${omega_disp} rad/s, k=${k_mrad} mrad/row, total bend=${total_disp} deg`);
  ok('tau   = 30.86 us/row', approx(tau_us, 30.86, 0.005), `${tau_us}`);
  ok('omega = 62.8 rad/s',   approx(omega_disp, 62.8, 0.05), `${omega_disp}`);
  ok('k     = 1.94 mrad/row', approx(k_mrad, 1.94, 0.005), `${k_mrad}`);
  ok('total bend = 120.0 deg over the frame', approx(total_disp, 120.0, 0.05), `${total_disp}`);
  // 120 deg = 1/3 turn: a 600-rpm prop turns 1/3 of a revolution while the sensor
  // reads one 1/30 s frame (600 rpm = 10 rev/s; 10 * (1/30) = 1/3 rev).
  ok('cross-check: 600 rpm * (1/30 s) = 1/3 revolution = 120 deg',
     approx((rpm / 60) * Tread, 1 / 3, 1e-12));
}

// ── 4b. A fast stress case (the slider's high end): a full-turn spiral ────────
console.log('\n— stress case: rpm 2400 (the bend exceeds one turn) —');
{
  const rpm = 2400, N = 1080, Tread = 1 / 30;
  const tau = Tread / N, omega = omegaFromRPM(rpm);
  const totalDeg = (omega * Tread) * 180 / Math.PI;
  ok('total bend = 480.0 deg = 4/3 turn at 2400 rpm', approx(+totalDeg.toFixed(1), 480.0, 0.05),
     `${totalDeg.toFixed(1)} deg`);
  ok('cross-check: 2400 rpm * (1/30 s) = 4/3 revolution',
     approx((rpm / 60) * Tread, 4 / 3, 1e-12));
}

// 5. Fit the generated, unwrapped model samples across the slider range.
// This is the same algebra used by the page's recover(). It does not test a
// photo measurement, an overlap threshold, or whether measured angles wrap.
console.log('\n— inversion exact across the slider range (fit theta vs row) —');
{
  const lsq = (ys, ths) => {
    const n = ys.length; let sy=0, st=0, syy=0, syt=0;
    for (let i=0;i<n;i++){ sy+=ys[i]; st+=ths[i]; syy+=ys[i]*ys[i]; syt+=ys[i]*ths[i]; }
    return (n*syt - sy*st) / (n*syy - sy*sy);
  };
  const theta0 = -Math.PI/2;
  const recover = (rpm, Tread, N) => {
    const omega = omegaFromRPM(rpm), tau = Tread/N;
    const ys = [], ths = [], M = 60;
    for (let i=0;i<M;i++){ const row = i*(N-1)/(M-1); ys.push(row); ths.push(thetaAt(theta0, omega, tau, row)); }
    const k = lsq(ys, ths);
    return Tread > 0 ? rpmFromOmega(k / tau) : 0;
  };
  for (const rpm of [50, 600, 2400, 8000]) {
    const rec = recover(rpm, 1/30, 1080);
    ok(`recover rpm ${String(rpm).padStart(4)} from model samples`, approx(rec, rpm, 1e-6), `got ${rec.toFixed(3)}`);
  }
  ok('global shutter (T_read=0) recovers 0 (no clock)', approx(recover(600, 0, 1080), 0, 1e-9));
}

// 6. Complete row geometry, including pieces disconnected from the hub.
// Intersect a straight, finite-width radial arm with each row at that row's
// capture time. A second calculation intersects the rotated rectangle's edges.
console.log('\nRow geometry: compare clipping with independent polygon intersections');
function armRowSpan(armTh0, A, cy, R, py, width) {
  const th=armTh0+A*py, c=Math.cos(th), s=Math.sin(th), dy=py-cy;
  let lo=-R-width, hi=R+width;
  const clip=(a,b,lower,upper)=>{
    if (Math.abs(a)<1e-12) return b>=lower && b<=upper;
    const x0=(lower-b)/a, x1=(upper-b)/a;
    lo=Math.max(lo,Math.min(x0,x1)); hi=Math.min(hi,Math.max(x0,x1));
    return lo<=hi;
  };
  if (!clip(c,dy*s,0,R) || !clip(-s,dy*c,-width/2,width/2)) return null;
  return {lo,hi};
}
function polygonSpan(th, cy, R, py, width) {
  const vertices=[[0,-width/2],[R,-width/2],[R,width/2],[0,width/2]].map(([u,v])=>
    [u*Math.cos(th)-v*Math.sin(th),cy+u*Math.sin(th)+v*Math.cos(th)]);
  const xs=[];
  for (let i=0;i<4;i++) {
    const [x0,y0]=vertices[i], [x1,y1]=vertices[(i+1)%4];
    if (Math.abs(y1-y0)<1e-10) {
      if (Math.abs(py-y0)<1e-10) xs.push(x0,x1);
    } else if (py>=Math.min(y0,y1)-1e-10 && py<=Math.max(y0,y1)+1e-10) {
      xs.push(x0+(py-y0)*(x1-x0)/(y1-y0));
    }
  }
  return xs.length ? {lo:Math.min(...xs),hi:Math.max(...xs)} : null;
}
{
  const cy=150,R=138,H=300;
  for (const rpm of [0,50,600,900,950,1000,2400,3000,8000]) {
    let mismatch=0, tested=0;
    for (const Tread of [0,1/30,0.06]) for (let arm=0;arm<6;arm++) {
      const A=omegaFromRPM(rpm)*Tread/H, th0=-Math.PI/2+arm*TWO_PI/6;
      for (let py=0;py<H;py+=0.5) {
        const span=armRowSpan(th0,A,cy,R,py,4), ref=polygonSpan(th0+A*py,cy,R,py,4);
        if (Boolean(span)!==Boolean(ref) || (span && (Math.abs(span.lo-ref.lo)>1e-7 || Math.abs(span.hi-ref.hi)>1e-7))) mismatch++;
        tested++;
      }
    }
    ok(`all sampled row spans match rotated blade at ${rpm} RPM`,mismatch===0,`${tested} comparisons, ${mismatch} mismatches`);
  }
  const th0=-Math.PI/2, A=omegaFromRPM(950)/30/H, py=14;
  const radius=(py-cy)/Math.sin(th0+A*py), dx=radius*Math.cos(th0+A*py);
  const span=armRowSpan(th0,A,cy,R,py,4);
  ok('950 RPM: disconnected tip branch is present', radius>0 && radius<R && span && span.lo<=dx && span.hi>=dx,
    `point=(${(180+dx).toFixed(6)},14), radius=${radius.toFixed(6)}`);
  const horizontal=armRowSpan(0,0,cy,R,cy,4);
  ok('horizontal global-shutter arm covers hub to tip',horizontal && horizontal.lo===0 && horizontal.hi===R);
}

// 7. A concrete counterexample to the old 180-degree overlap/unwrap threshold.
// Generate the COMPLETE thin-arm centerline by intersecting every sampled row
// with the radial blade. No radius continuation or model angle is used in the fit.
console.log('\n190-degree counterexample: raw geometric angles need no unwrapping');
{
  const A=omegaFromRPM(950)/30/300, paths=[];
  for (let arm=0;arm<2;arm++) {
    const ys=[],angles=[],segments=[];
    let previous=null,jumps=0;
    for (let y=12;y<=288;y+=0.5) {
      const th=-Math.PI/2+arm*Math.PI+A*y;
      const r=(y-150)/Math.sin(th);
      if (!(r>=8 && r<=138)) { previous=null; continue; }
      const x=r*Math.cos(th),dy=y-150,angle=Math.atan2(dy,x);
      if (angles.length && Math.abs(angle-angles.at(-1))>Math.PI) jumps++;
      ys.push(y/300*1080); angles.push(angle);
      const p=[x,dy];
      if (previous) segments.push([previous,p]);
      previous=p;
    }
    const recovered=rpmFromOmega(lsqSlope(ys,angles)/(1/30/1080));
    ok(`190 degrees, arm ${arm}: raw atan2 fit recovers 950 RPM without unwrapping`,jumps===0 && approx(recovered,950,1e-6),
      `${ys.length} samples, ${jumps} branch-cut jumps, RPM=${recovered.toFixed(9)}`);
    paths.push(...segments);
  }
  const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
  const intersects=(a,b,c,d)=>cross(a,b,c)*cross(a,b,d)<-1e-8 && cross(c,d,a)*cross(c,d,b)<-1e-8;
  let crossings=0;
  for (let i=0;i<paths.length;i++) for (let j=i+1;j<paths.length;j++) if (intersects(...paths[i],...paths[j])) crossings++;
  ok('190-degree centerline paths have no crossing away from the hub',crossings===0,`${crossings} crossings`);
  ok('intersection diagnostic detects a deliberate crossing',intersects([0,0],[2,2],[0,2],[2,0]));
  ok('angle-jump diagnostic detects a deliberate branch-cut jump',Math.abs((-Math.PI+0.1)-(Math.PI-0.1))>Math.PI);
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
