#!/usr/bin/env node
// research/reuleaux-constant-width/verify.mjs — offline verifier for the stratum on
// curves of constant width (the Reuleaux triangle).
//
//   node research/reuleaux-constant-width/verify.mjs
//
// Re-derives, from the geometry in reuleaux.mjs, everything the page asserts:
//   I.   CONSTANT WIDTH — the width of a Reuleaux triangle / pentagon / heptagon is the
//        same in every direction (a full turn sampled), so a board resting on top of a
//        rolling one stays perfectly level. The circle does it too; these are not circles.
//   II.  BARBIER'S THEOREM (1860) — every curve of constant width w has perimeter
//        exactly π·w, the same as a circle of diameter w. Checked for n = 3, 5, 7.
//   III. BLASCHKE–LEBESGUE — among all width-w curves the Reuleaux triangle has the
//        LEAST area, ½(π−√3)w² ≈ 0.7048 w²; the circle the MOST, (π/4)w² ≈ 0.7854 w²;
//        the pentagon and heptagon fall strictly between, closer to the circle.
//   IV.  THE SQUARE-HOLE DRILL — a Reuleaux triangle rotated inside a square sweeps a
//        hole covering ≈ 0.9877 of it (four rounded corners left over), reproduced by a
//        grid-and-rotation simulation that never uses that number.
//
// "Show the check": the geometry is reuleaux.mjs; every number below is recomputed here.

import {
  boundary, perimeter, area, widthAt, vertices, inside,
  drillCoverage, areaCircle, areaReuleauxTriangle, DRILL_COVERAGE_EXACT,
} from './reuleaux.mjs';

let PASS = 0, FAIL = 0;
const log = [];
function check(name, cond, got, want) {
  if (cond) { PASS++; log.push(`  ok   ${name}`); }
  else { FAIL++; log.push(`  FAIL ${name}\n         got:  ${got}\n         want: ${want}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const W = 1; // work at unit width

log.push('\nI. Constant width — the same in every direction (a full turn):');
for (const n of [3, 5, 7]) {
  const pts = boundary(n, W, 0.3, 400);
  let maxDev = 0;
  for (let k = 0; k < 360; k++) {
    const wth = widthAt(pts, (k * Math.PI) / 180);
    maxDev = Math.max(maxDev, Math.abs(wth - W));
  }
  check(`Reuleaux ${n}-gon: width = 1.000 at every angle (max deviation < 1e-3)`,
    maxDev < 1e-3, maxDev.toExponential(2), '< 1e-3');
}
{
  // The rolling claim restated: at every rotation, the vertical width (board-to-ground)
  // is exactly 1 — so a plank on top of a rolling Reuleaux triangle never rises or dips.
  let maxDev = 0;
  for (let deg = 0; deg < 360; deg++) {
    const pts = boundary(3, W, (deg * Math.PI) / 180, 400);
    maxDev = Math.max(maxDev, Math.abs(widthAt(pts, Math.PI / 2) - W));
  }
  check('a board on a rolling Reuleaux triangle stays level (vertical gap ≡ 1)',
    maxDev < 1e-3, maxDev.toExponential(2), '< 1e-3');
}

log.push('\nII. Barbier’s theorem — perimeter = π·w for every constant-width curve:');
for (const n of [3, 5, 7]) {
  const p = perimeter(boundary(n, W, 0.11, 2000));
  check(`Reuleaux ${n}-gon: perimeter = π (got ${p.toFixed(5)})`,
    near(p, Math.PI, 2e-3), p.toFixed(5), Math.PI.toFixed(5));
}

log.push('\nIII. Blaschke–Lebesgue — the triangle is the smallest, the circle the largest:');
{
  const aTri = area(boundary(3, W, 0.07, 4000));
  const aPen = area(boundary(5, W, 0.07, 4000));
  const aHep = area(boundary(7, W, 0.07, 4000));
  const aCirc = areaCircle(W);
  check('Reuleaux-triangle area = ½(π−√3) ≈ 0.70477 (numeric matches closed form)',
    near(aTri, areaReuleauxTriangle(W), 1e-3) && near(areaReuleauxTriangle(W), 0.70477, 1e-4),
    aTri.toFixed(5), areaReuleauxTriangle(W).toFixed(5));
  check('circle area = π/4 ≈ 0.78540',
    near(aCirc, 0.785398, 1e-5), aCirc.toFixed(5), '0.78540');
  check('areas increase triangle < pentagon < heptagon < circle (same width)',
    aTri < aPen && aPen < aHep && aHep < aCirc,
    `${aTri.toFixed(4)} < ${aPen.toFixed(4)} < ${aHep.toFixed(4)} < ${aCirc.toFixed(4)}`,
    'strictly increasing');
  check('the triangle is the extreme minimiser — 10.3% less area than the circle',
    near((1 - aTri / aCirc) * 100, 10.27, 0.1), ((1 - aTri / aCirc) * 100).toFixed(2), '10.27');
}

log.push('\nIV. The Watts square-hole drill — coverage by simulation:');
{
  // Sanity: a width-1 Reuleaux triangle fits inside a 1×1 square at any orientation
  // (its bounding box is always 1×1 because the width is 1 in every direction).
  const V = vertices(3, W, 0.4);
  const bp = boundary(3, W, 0.4, 400);
  let minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity;
  for (const p of bp) { minx = Math.min(minx, p.x); maxx = Math.max(maxx, p.x);
    miny = Math.min(miny, p.y); maxy = Math.max(maxy, p.y); }
  check('the shape’s bounding box is exactly 1×1 (fits the square at any angle)',
    near(maxx - minx, 1, 1e-3) && near(maxy - miny, 1, 1e-3),
    `${(maxx - minx).toFixed(4)}×${(maxy - miny).toFixed(4)}`, '1×1');
  // Corners of the square are NOT covered — the drilled hole has rounded corners.
  const cornerCovered = inside({ x: minx + 0.002, y: miny + 0.002 },
    V.map((v) => ({ x: v.x - minx, y: v.y - miny })), W);
  check('the square’s corner is left uncovered (the hole is rounded, not exact)',
    cornerCovered === false, cornerCovered, 'false');

  // The exact coverage is 2√3 + π/6 − 3 (OEIS A066666); the closed form and the number.
  check('exact drilled coverage = 2√3 + π/6 − 3 ≈ 0.987700',
    near(DRILL_COVERAGE_EXACT, 0.9877004, 1e-6), DRILL_COVERAGE_EXACT.toFixed(7), '0.9877004');
  // The union simulation (exact registration) converges UP to that closed form.
  const cov = drillCoverage(1, 400, 720);
  check(`union simulation approaches the closed form (got ${cov.toFixed(5)}, → 0.98770)`,
    cov < DRILL_COVERAGE_EXACT && near(cov, DRILL_COVERAGE_EXACT, 3e-3),
    cov.toFixed(5), '≲ 0.98770');
}

// ── report ──────────────────────────────────────────────────────────────────────
console.log(log.join('\n'));
console.log(`\n${FAIL === 0 ? 'ALL PASS' : 'FAILURES'} — ${PASS}/${PASS + FAIL} checks\n`);
process.exit(FAIL === 0 ? 0 : 1);
