#!/usr/bin/env node
// verify.mjs — The straight-line linkage problem, checked offline.
//
// Two mechanisms, simulated from their BAR-LENGTH CONSTRAINTS ALONE (no
// inversion formula is assumed inside the forward kinematics — the identity is
// allowed to *emerge* and is then checked):
//
//   1. The Peaucellier–Lipkin cell (1864/1871) — the first planar linkage that
//      converts circular motion to an EXACT straight line. We show the output
//      point B satisfies OB·OD = a²−b² (inversion in a circle of radius √(a²−b²))
//      and, when the driver D is pinned to a circle through O, B's x-coordinate
//      is constant to machine precision: a true straight line.
//
//   2. Watt's linkage (1784) — the celebrated APPROXIMATE straight-line motion.
//      Its tracer bows by a measurable amount; we compute the deviation and set
//      it beside Peaucellier's zero.
//
// Run:  node verify.mjs            (prints checks, exits 1 on any failure)
//       node verify.mjs --json     (also writes page.json for the immersive page)
//
// No dependencies. Pure geometry.

const EPS = 1e-9;
let pass = 0, fail = 0;
const lines = [];
function check(name, ok, detail = "") {
  if (ok) { pass++; lines.push(`  ✓ ${name}${detail ? " — " + detail : ""}`); }
  else    { fail++; lines.push(`  ✗ ${name}${detail ? " — " + detail : ""}`); }
}

// ---- vector helpers ----
const sub = (p, q) => [p[0] - q[0], p[1] - q[1]];
const add = (p, q) => [p[0] + q[0], p[1] + q[1]];
const mul = (p, s) => [p[0] * s, p[1] * s];
const dot = (p, q) => p[0] * q[0] + p[1] * q[1];
const len = (p) => Math.hypot(p[0], p[1]);
const dist = (p, q) => len(sub(p, q));

// Intersect two circles; return [P+, P-] (the two points), or null if none.
function circleIntersect(c0, r0, c1, r1) {
  const d = dist(c0, c1);
  if (d < EPS) return null;
  if (d > r0 + r1 + EPS) return null;
  if (d < Math.abs(r0 - r1) - EPS) return null;
  const a = (r0 * r0 - r1 * r1 + d * d) / (2 * d);
  const h2 = r0 * r0 - a * a;
  const h = Math.sqrt(Math.max(0, h2));
  const u = mul(sub(c1, c0), 1 / d);          // unit c0->c1
  const perp = [-u[1], u[0]];
  const base = add(c0, mul(u, a));
  return [add(base, mul(perp, h)), sub(base, mul(perp, h))];
}

// ============================================================
// 1. PEAUCELLIER–LIPKIN CELL
// ============================================================
//
// Fixed pivot O at the origin. Two equal anchor bars OA = OC = a pin the rhombus
// vertices A and C to O. A rhombus A–B–C–D of side b carries the pencil B and the
// driver D at its free (opposite) vertices. A crank of length c pivots at a fixed
// point F with |OF| = c, so the crank circle (centre F, radius c) PASSES THROUGH O.
// Driving D around that circle makes B trace a straight line.

const a = 3.0;   // anchor-bar length
const b = 2.0;   // rhombus side  (need a > b so the power a²−b² > 0)
const c = 2.5;   // crank length   (|OF| = c so the crank circle passes through O)
const power = a * a - b * b;            // inversion power  k² = a²−b²
const O = [0, 0];
const F = [-c, 0];                       // |OF| = c  ✓

// Forward kinematics from crank angle θ — derived ONLY from bar lengths.
// Returns null where the cell cannot close (driver outside the annulus).
function peaucellier(theta) {
  const D = add(F, [c * Math.cos(theta), c * Math.sin(theta)]);  // crank: |FD| = c
  const r = len(D);                                              // |OD|
  if (r < Math.abs(a - b) + EPS || r > a + b - EPS) return null; // cell must close
  // A, C = the two intersections of circle(O,a) and circle(D,b):
  const ac = circleIntersect(O, a, D, b);
  if (!ac) return null;
  const [A, C] = ac;
  // B lies on line O–D, at the SECOND intersection of that line with circle(A,b)
  // (the first being D itself). Solve |s·û − A|² = b²  for scalar s along û = D/r:
  //   s² − 2(û·A) s + (|A|² − b²) = 0,  with |A| = a.
  // The two roots are s = r (the point D) and s = sB; their product is |A|²−b² = a²−b².
  const u = mul(D, 1 / r);
  const uA = dot(u, A);
  const disc = uA * uA - (a * a - b * b);
  const root = Math.sqrt(Math.max(0, disc));
  const s1 = uA + root, s2 = uA - root;       // {r, sB} in some order
  const sB = Math.abs(s1 - r) < Math.abs(s2 - r) ? s2 : s1;  // the root that ISN'T D
  const B = mul(u, sB);
  return { D, A, C, B, r, sB };
}

// Sweep the crank over the range where the cell stays closed.
const samplesP = [];
for (let i = 0; i <= 4000; i++) {
  const theta = (i / 4000) * 2 * Math.PI;
  const s = peaucellier(theta);
  if (s) samplesP.push({ theta, ...s });
}

check("Peaucellier cell closes over a real arc of crank travel",
  samplesP.length > 1500, `${samplesP.length} valid samples of 4001`);

// (P1) Every bar holds its length at every sampled pose — this is a real mechanism.
{
  let maxErr = 0;
  for (const s of samplesP) {
    const errs = [
      Math.abs(dist(O, s.A) - a), Math.abs(dist(O, s.C) - a),    // anchors
      Math.abs(dist(s.A, s.B) - b), Math.abs(dist(s.B, s.C) - b), // rhombus
      Math.abs(dist(s.C, s.D) - b), Math.abs(dist(s.D, s.A) - b),
      Math.abs(dist(F, s.D) - c),                                 // crank
    ];
    maxErr = Math.max(maxErr, ...errs);
  }
  check("all seven bars hold their length across the whole sweep",
    maxErr < EPS, `max length error ${maxErr.toExponential(2)}`);
}

// (P2) The inversion identity OB·OD = a²−b² EMERGES (never assumed above).
{
  let maxErr = 0;
  for (const s of samplesP) {
    const OB = len(s.B), OD = s.r;
    maxErr = Math.max(maxErr, Math.abs(OB * OD - power));
  }
  check(`inversion identity OB·OD = a²−b² holds (= ${power.toFixed(4)})`,
    maxErr < EPS, `max error ${maxErr.toExponential(2)}`);
}

// (P3) B is exactly the inverse of D: B = (k²/|OD|²)·D.
{
  let maxErr = 0;
  for (const s of samplesP) {
    const expect = mul(s.D, power / (s.r * s.r));
    maxErr = Math.max(maxErr, dist(s.B, expect));
  }
  check("output B equals the geometric inverse of driver D about O",
    maxErr < EPS, `max error ${maxErr.toExponential(2)}`);
}

// (P4) THE PAYOFF: B's x-coordinate is constant — an exact straight line.
let pXconst = 0, pYspan = 0;
{
  const xs = samplesP.map(s => s.B[0]);
  const ys = samplesP.map(s => s.B[1]).filter(Number.isFinite);
  const xmin = Math.min(...xs), xmax = Math.max(...xs);
  pXconst = (xmin + xmax) / 2;
  pYspan = Math.max(...ys) - Math.min(...ys);
  check("B traces an EXACT straight line: B.x is constant to machine precision",
    (xmax - xmin) < EPS, `Δx over the whole stroke = ${(xmax - xmin).toExponential(2)}`);
  // and the constant matches the closed form −(a²−b²)/(2c):
  const closed = -power / (2 * c);
  check("the line sits at the closed-form abscissa −(a²−b²)/(2c)",
    Math.abs(pXconst - closed) < EPS,
    `measured ${pXconst.toFixed(6)} vs formula ${closed.toFixed(6)}`);
  check("the straight line is genuinely traversed (B sweeps a real vertical span)",
    pYspan > 1, `vertical span ${pYspan.toFixed(3)}`);
}

// ============================================================
// 2. WATT'S LINKAGE — approximate straight line (1784)
// ============================================================
//
// Two EQUAL rockers of length rW pivot at fixed points O1=(0,g), O2=(0,−g); a
// coupler of length cW joins their free ends A, B; the tracer M is the coupler's
// MIDPOINT. M traces "Watt's curve" — a figure-eight (the lemniscate, for the
// crossed-square case). Watt worked the engine at the curve's NODE — its self-
// crossing — where the path is straight to THIRD order. We put the node at the
// origin (mid-way between the pivots): there A = −B, so the coupler passes through
// the centre, and the design relation falls out clean: the node sits at tracer-
// height g/2 exactly when the coupler is TWICE the rocker, cW = 2·rW. Driving the
// crank near that pose sweeps a near-perfect straight line through the origin.

const g = 1.0;                 // pivots at (0, ±g)
const rW = 1.6;                // rocker length
const cW = 2 * rW;             // coupler length = 2·rocker  → node at height g/2
const O1 = [0, g], O2 = [0, -g];
const ayN = g / 2;                                    // node tracer-height parameter
const axN = Math.sqrt(rW * rW - (ayN - g) * (ayN - g)); // node A x-coordinate
const A0 = [axN, ayN], B0 = [-axN, -ayN];             // node pose: A = −B, M = origin
const phiN = Math.atan2(ayN - g, axN);                // crank (rocker-O1) angle at the node

function watt(phi, prevB) {
  const A = add(O1, [rW * Math.cos(phi), rW * Math.sin(phi)]);
  const sol = circleIntersect(O2, rW, A, cW);
  if (!sol) return null;
  const B = dist(sol[0], prevB) <= dist(sol[1], prevB) ? sol[0] : sol[1];
  return { A, B, M: mul(add(A, B), 0.5) };
}

// Sweep the crank about the node pose; track the coupler branch by continuity.
function sweepWatt(halfSpan, steps) {
  const out = [];
  let prevB = B0;
  for (let i = -steps; i <= steps; i++) {
    const phi = phiN + (i / steps) * halfSpan;
    const s = watt(phi, prevB);
    if (!s) return null;
    prevB = s.B;
    out.push({ phi, ...s });
  }
  return out;
}

const samplesW = sweepWatt(0.16, 1000);   // the engine's working stroke, near the node
check("Watt linkage closes across its working stroke", samplesW && samplesW.length > 1500,
  `${samplesW ? samplesW.length : 0} samples`);

// straight-line residual of a sampled arc: max perpendicular distance from the
// chord joining its endpoints, and the stroke length (chord length).
function lineResidual(pts) {
  const p0 = pts[0].M, p1 = pts[pts.length - 1].M;
  const dir = sub(p1, p0), L = len(dir), u = mul(dir, 1 / L);
  let bow = 0;
  for (const s of pts) {
    const v = sub(s.M, p0);
    const proj = v[0] * u[0] + v[1] * u[1];
    bow = Math.max(bow, Math.hypot(v[0] - proj * u[0], v[1] - proj * u[1]));
  }
  return { stroke: L, bow };
}

// (W1) Watt's three bars hold their length (it is a real mechanism too).
{
  let maxErr = 0;
  for (const s of samplesW) {
    maxErr = Math.max(maxErr,
      Math.abs(dist(O1, s.A) - rW),
      Math.abs(dist(O2, s.B) - rW),
      Math.abs(dist(s.A, s.B) - cW));
  }
  check("Watt's three bars hold their length across the sweep",
    maxErr < EPS, `max length error ${maxErr.toExponential(2)}`);
}

// (W2) The tracer BOWS — straight, but only approximately (a measurable, nonzero
// deviation), where Peaucellier's is machine-zero.
let wStroke = 0, wBow = 0, wPartsPer = 0;
{
  const lr = lineResidual(samplesW);
  wStroke = lr.stroke; wBow = lr.bow; wPartsPer = lr.stroke / lr.bow;
  check("Watt's tracer is straight only APPROXIMATELY — a measurable, nonzero bow",
    wBow > 1e-6,
    `bows ${wBow.toExponential(3)} over a ${wStroke.toFixed(3)} stroke ≈ 1 part in ${Math.round(wPartsPer)}`);
}

// (W3) The bow is CUBIC in the stroke (third-order contact at the node) — the
// hallmark of a deliberately designed straight-line linkage, not a lucky tangent.
// (Measured near the node, where the cubic term dominates; higher-order terms
// steepen it past stroke ≈ 0.3.)
const wTable = [];
{
  for (const hs of [0.02, 0.04, 0.08, 0.16, 0.32]) {
    const s = sweepWatt(hs, 500);
    if (!s) continue;
    const lr = lineResidual(s);
    wTable.push({ stroke: lr.stroke, bow: lr.bow, partsPer: Math.round(lr.stroke / lr.bow) });
  }
  // growth order from the two smallest strokes (cleanest cubic regime):
  const order = Math.log(wTable[1].bow / wTable[0].bow) / Math.log(wTable[1].stroke / wTable[0].stroke);
  check("Watt's bow grows as the CUBE of the stroke (third-order contact)",
    order > 2.7 && order < 3.4,
    `measured growth order ≈ ${order.toFixed(2)} (ideal 3); 1 part in ${wTable[0].partsPer} at the tightest stroke`);
}

// (W4) The decisive contrast, stated as a ratio: exact vs merely-excellent.
let pDev = 0;
{
  const xs = samplesP.map(s => s.B[0]); pDev = Math.max(...xs) - Math.min(...xs);
  check("Peaucellier is EXACT where Watt is only approximate: the gap is astronomical",
    wBow > 1e6 * Math.max(pDev, Number.MIN_VALUE),
    `Watt bows ${wBow.toExponential(2)}; Peaucellier ${pDev.toExponential(2)} (machine zero)`);
}

// ---- report ----
console.log("\nThe straight-line linkage problem — offline verification\n");
console.log(lines.join("\n"));
console.log(`\n${pass}/${pass + fail} checks passed.${fail ? "  FAIL." : "  All green."}\n`);

if (process.argv.includes("--json")) {
  // Emit a compact set of figures the immersive page quotes verbatim.
  const out = {
    peaucellier: {
      a, b, c, power,
      lineX: pXconst,
      lineXClosedForm: -power / (2 * c),
      verticalSpan: pYspan,
      maxDeviation: (() => { const xs = samplesP.map(s => s.B[0]); return Math.max(...xs) - Math.min(...xs); })(),
      samples: samplesP.length,
    },
    watt: {
      g, r: rW, coupler: cW, nodeHeight: ayN, nodeAx: axN,
      bow: wBow, stroke: wStroke, partsPer: Math.round(wPartsPer),
      table: wTable, samples: samplesW.length,
    },
    checks: { passed: pass, total: pass + fail },
    generated: new Date().toISOString(),
  };
  const fs = await import("node:fs");
  const path = new URL("./page.json", import.meta.url);
  fs.writeFileSync(path, JSON.stringify(out, null, 2) + "\n");
  console.log("wrote page.json");
}

process.exit(fail ? 1 : 0);
