// The Edge of the Bow — offline verifier for the geometric optics of the rainbow.
//
// Everything the stratum claims about the rainbow is recomputed here from first
// principles and written to artifact.json. The spine is a *vector ray-tracer*
// through a sphere of water (refract / reflect / refract), so the geometry is
// never trusted to a hand-copied formula: the traced total deflection is checked
// against the closed form 180k° + 2i − 2(k+1)r at the start, and only once they
// agree within 1e-5 degrees on the sampled rays do we use the formula downstream.
//
// What gets checked, end to end:
//   • the ray-tracer agrees with the closed-form deviation (primary & secondary);
//   • the rainbow angle is the *extremum* of the deviation (the caustic) — found
//     two independent ways (numeric minimisation and the closed form
//     cos²i = (n²−1)/[k(k+2)]), which must agree;
//   • Descartes' 1637 method reproduced: bin the emergent angles of rays uniform
//     across the drop and watch them crowd at 42° — the caustic as a ray pile-up;
//   • dispersion: red sits *outside* the primary and *inside* the secondary, with
//     the bow widths these n-values force;
//   • Alexander's dark band: the angular gap between the bows that NO single- or
//     double-reflected ray can reach;
//   • the supernumerary mechanism (Young 1804): just inside the primary edge,
//     two rays have an optical-path difference, computed from the traced
//     polyline, that sets up interference; the fringe spacing scales as
//     (λ/a)^(2/3), the Airy signature, confirmed across drop sizes and colours.
//
// Run:  node research/the-edge-of-the-bow/verify.mjs
"use strict";
import { writeFileSync } from "node:fs";

const { sin, cos, tan, asin, acos, atan2, sqrt, abs, PI, hypot, cbrt } = Math;
const D = PI / 180; // degrees → radians
const deg = (x) => x / D;

// ─────────────────────────────────────────────────────────────────────────
// Inputs that are MEASURED, not derived — the refractive index of water at a
// few wavelengths. There is no single n: it is a function of wavelength (that
// is *why* a rainbow has colour) and also drifts a little with temperature and
// purity. These are rounded to three decimals from Tilton and Taylor, Table 5,
// p. 446, at 20 °C: https://nvlpubs.nist.gov/nistpubs/jres/20/jresv20n4p419_A1b.pdf
// The formula is cross-checked against ray tracing, then used for the angles.
const WATER = {
  red: { nm: 656, n: 1.331 }, // Fraunhofer C line, ~red
  yellow: { nm: 589, n: 1.333 }, // sodium D, the canonical "n = 4/3"
  violet: { nm: 405, n: 1.343 }, // ~h line, deep violet
};

const checks = [];
let id = 0;
function check(name, pass, detail) {
  id++;
  checks.push({ n: id, name, pass: !!pass, detail });
  if (!pass) console.error(`  ✗ [${id}] ${name} — ${detail}`);
}
const close = (a, b, tol) => abs(a - b) <= tol;

// ─────────────────────────────────────────────────────────────────────────
// VECTOR RAY-TRACER through a unit sphere of water (radius 1), one ray in the
// x–y plane. Parallel sunlight travels in +x at height b (the impact parameter,
// 0..1 in drop radii). The ray refracts in, reflects internally k times, and
// refracts out. We accumulate optical path = Σ (segment length × medium index).
// Returns the total deflection (the turn from the incoming direction) and the
// optical path between a common entry plane and a plane ⟂ to the exit ray.
function trace(b, n, k) {
  if (b >= 1) return null;
  // start well to the left, on a wavefront plane x = −X0 (⟂ to incident d0)
  const X0 = 4;
  let p = [-X0, b];
  let d = [1, 0]; // unit incident direction
  let op = 0; // optical path
  let medium = 1; // outside

  // helper: advance to the unit circle along d (taking the *forward* hit),
  // choosing entry (first) or, when already inside, the far intersection.
  function hitCircle(p, d, wantInside) {
    // |p + t d|² = 1  →  t² + 2(p·d) t + (|p|²−1) = 0
    const pd = p[0] * d[0] + p[1] * d[1];
    const pp = p[0] * p[0] + p[1] * p[1] - 1;
    const disc = pd * pd - pp;
    if (disc < 0) return null;
    const s = sqrt(disc);
    const t1 = -pd - s, t2 = -pd + s;
    // pick the smallest strictly-positive t (next surface ahead)
    const eps = 1e-9;
    let t = null;
    if (t1 > eps) t = t1;
    else if (t2 > eps) t = t2;
    if (t == null) return null;
    return [p[0] + t * d[0], p[1] + t * d[1], t];
  }

  // 1) air → entry point A
  let h = hitCircle(p, d, false);
  if (!h) return null;
  op += medium * h[2]; // air segment to A
  p = [h[0], h[1]];

  // refract air→water. outward normal at p is p (unit, since |p|=1)
  function refract(d, nrm, eta) {
    // nrm oriented to point *against* the incident ray (into the side d comes from)
    const cosi = -(d[0] * nrm[0] + d[1] * nrm[1]);
    const k2 = 1 - eta * eta * (1 - cosi * cosi);
    if (k2 < 0) return null; // total internal reflection (shouldn't happen here)
    const c2 = sqrt(k2);
    return [
      eta * d[0] + (eta * cosi - c2) * nrm[0],
      eta * d[1] + (eta * cosi - c2) * nrm[1],
    ];
  }
  function reflect(d, nrm) {
    const dn = d[0] * nrm[0] + d[1] * nrm[1];
    return [d[0] - 2 * dn * nrm[0], d[1] - 2 * dn * nrm[1]];
  }
  const unit = (v) => { const L = hypot(v[0], v[1]); return [v[0] / L, v[1] / L]; };

  // at A the outward normal is p; it points *toward* the incoming ray's source side
  let nrm = unit([p[0], p[1]]); // outward
  d = refract(d, nrm, 1 / n);
  if (!d) return null;
  d = unit(d);
  medium = n;

  // 2) k internal reflections
  for (let j = 0; j < k; j++) {
    h = hitCircle(p, d, true);
    if (!h) return null;
    op += medium * h[2];
    p = [h[0], h[1]];
    // internal reflection off the inner surface: normal is inward (−p)
    nrm = unit([-p[0], -p[1]]);
    d = reflect(d, nrm);
    d = unit(d);
  }

  // 3) travel to exit surface, refract water→air
  h = hitCircle(p, d, true);
  if (!h) return null;
  op += medium * h[2];
  p = [h[0], h[1]];
  nrm = unit([-p[0], -p[1]]); // inner normal points against the outgoing-inside ray
  let dout = refract(d, nrm, n / 1);
  if (!dout) return null;
  dout = unit(dout);
  medium = 1;

  // 4) air to a reference plane through the origin, ⟂ to the exit ray dout.
  //    signed distance so the optical path difference between two parallel
  //    exit rays is reference-independent.
  const tExit = -(p[0] * dout[0] + p[1] * dout[1]); // p + t·dout hits plane {x·dout=0}
  op += medium * tExit;

  // total deflection: angle between d0=(1,0) and dout, accumulated as the ray
  // wound around. Use atan2 of the turn; primary winds ~138°, secondary ~231°.
  // We reconstruct the *unsigned* turn from the dot product is not enough (it
  // caps at 180°), so track via the closed form check separately; here return
  // the raw exit direction and let the caller compute deflection robustly.
  return { dout, op, exit: p };
}

// Robust total deflection for k reflections, from the analytic angles (this is
// the quantity we *cross-check* the tracer against, then use downstream).
function deviation(iDeg, n, k) {
  const i = iDeg * D;
  const sinr = sin(i) / n;
  if (sinr > 1) return null;
  const r = asin(sinr);
  // total turn = 2(i−r) + k(π − 2r) = kπ + 2i − 2(k+1)r
  return deg(k * PI + 2 * i - 2 * (k + 1) * r);
}
// viewing angle from the antisolar point (apparent radius of the bow)
const viewAngle = (thetaDeg) => {
  let t = ((thetaDeg % 360) + 360) % 360;
  return abs(180 - t);
};

// ─────────────────────────────────────────────────────────────────────────
// 1) The ray-tracer agrees with the closed-form deviation. We recover the
//    tracer's deflection from its exit direction by matching against the
//    analytic value's wrapped direction, then assert agreement of the *exit
//    ray direction* — the unambiguous, frame-free check.
function exitDirFromTheta(thetaDeg) {
  // incident d0=(1,0); after turning by theta (the ray bends "downward" for b>0
  // in our convention), the exit unit direction is (cos θ, −sin θ) measured as a
  // rotation. We compare directions, which is convention-proof.
  return null; // (computed inline below)
}
for (const k of [1, 2]) {
  const n = WATER.yellow.n;
  let maxErr = 0;
  for (let iDeg = 5; iDeg < 89; iDeg += 7) {
    const b = sin(iDeg * D);
    const tr = trace(b, n, k);
    const thA = deviation(iDeg, n, k);
    if (!tr || thA == null) continue;
    // analytic exit direction: rotate (1,0) by −θ (b>0 bends to −y)
    const th = thA * D;
    const da = [cos(th), -sin(th)];
    const dotp = tr.dout[0] * da[0] + tr.dout[1] * da[1];
    const ang = deg(acos(Math.min(1, Math.max(-1, dotp))));
    maxErr = Math.max(maxErr, ang);
  }
  check(
    `ray-tracer matches closed-form deviation (k=${k}, max dir error)`,
    maxErr < 1e-5,
    `max exit-direction error ${maxErr.toExponential(2)}° over i=5..88°`
  );
}

// ─────────────────────────────────────────────────────────────────────────
// 2) The rainbow angle is the EXTREMUM of the deviation (the caustic), found
//    two independent ways: numeric minimisation of θ(i), and the closed form
//    cos²i* = (n²−1)/[k(k+2)]. They must agree, and the resulting viewing angle
//    must be the textbook 42° (primary) / 51° (secondary).
function numericExtremum(n, k) {
  // golden-section search on θ(i) over i∈(0,90); primary/secondary are minima of θ
  let lo = 1 * D, hi = 89 * D;
  const f = (i) => deviation(deg(i), n, k);
  const gr = (sqrt(5) - 1) / 2;
  let c = hi - gr * (hi - lo), d2 = lo + gr * (hi - lo);
  for (let it = 0; it < 200; it++) {
    if (f(c) < f(d2)) { hi = d2; d2 = c; c = hi - gr * (hi - lo); }
    else { lo = c; c = d2; d2 = lo + gr * (hi - lo); }
  }
  const iStar = (lo + hi) / 2;
  return { iDeg: deg(iStar), thetaDeg: deviation(deg(iStar), n, k) };
}
function closedFormExtremum(n, k) {
  const cos2 = (n * n - 1) / (k * (k + 2));
  const iStar = acos(sqrt(cos2));
  return { iDeg: deg(iStar), thetaDeg: deviation(deg(iStar), n, k), cos2 };
}
const bows = {};
for (const [name, k, expect] of [["primary", 1, 42], ["secondary", 2, 51]]) {
  const n = WATER.yellow.n;
  const num = numericExtremum(n, k);
  const cf = closedFormExtremum(n, k);
  check(
    `${name}: numeric extremum = closed form (incidence angle)`,
    close(num.iDeg, cf.iDeg, 1e-3),
    `numeric i*=${num.iDeg.toFixed(4)}°, closed-form i*=${cf.iDeg.toFixed(4)}°`
  );
  const va = viewAngle(cf.thetaDeg);
  check(
    `${name}: viewing angle ≈ ${expect}° (yellow, n=${n})`,
    close(va, expect, 0.7),
    `viewing angle ${va.toFixed(2)}° (deflection ${cf.thetaDeg.toFixed(2)}°)`
  );
  bows[name] = { k, iStar: cf.iDeg, deflection: cf.thetaDeg, viewAngle: va };
}

// ─────────────────────────────────────────────────────────────────────────
// 3) Descartes' method (Les Météores, 1637), reproduced: he traced rays at many
//    impact parameters and *counted* where they emerged, finding them crowd near
//    42°. Brightness ∝ rays-per-unit-angle, which diverges at the extremum (the
//    caustic). We sample uniformly in b (uniform across the drop's face), bin the
//    emergent viewing angles, and confirm the fullest bin sits at the rainbow
//    angle — and that it holds far more rays than a typical bin.
function descartesHistogram(n, k, nRays = 400000, binDeg = 0.1) {
  const bins = new Map();
  for (let j = 0; j < nRays; j++) {
    const b = (j + 0.5) / nRays; // uniform in b ∈ (0,1)
    const iDeg = deg(asin(b));
    const th = deviation(iDeg, n, k);
    if (th == null) continue;
    const va = viewAngle(th);
    const key = Math.floor(va / binDeg);
    bins.set(key, (bins.get(key) || 0) + 1);
  }
  let bestKey = null, bestCount = -1, total = 0;
  for (const [key, c] of bins) { total += c; if (c > bestCount) { bestCount = c; bestKey = key; } }
  const meanCount = total / bins.size;
  return { peakAngle: (bestKey + 0.5) * binDeg, peakCount: bestCount, meanCount, nBins: bins.size };
}
{
  const n = WATER.yellow.n;
  const h = descartesHistogram(n, 1);
  check(
    "Descartes' pile-up: rays crowd at the rainbow angle (primary)",
    close(h.peakAngle, bows.primary.viewAngle, 0.4),
    `fullest 0.1° bin at ${h.peakAngle.toFixed(2)}° vs rainbow ${bows.primary.viewAngle.toFixed(2)}°`
  );
  check(
    "Descartes' pile-up is a genuine caustic (peak ≫ mean ray density)",
    h.peakCount > 8 * h.meanCount,
    `peak bin ${h.peakCount} rays vs mean ${h.meanCount.toFixed(0)} → ${(h.peakCount / h.meanCount).toFixed(1)}×`
  );
  bows.primary.descartes = h;
}

// ─────────────────────────────────────────────────────────────────────────
// 4) Dispersion: the colour order. Red has the smaller n, so the primary bow
//    puts red at the LARGER viewing angle (outer edge) and violet inner; the
//    secondary reverses it. And the bow widths are what these n-values force.
const colours = {};
for (const c of ["red", "yellow", "violet"]) {
  const n = WATER[c].n;
  colours[c] = {
    n,
    nm: WATER[c].nm,
    primary: viewAngle(closedFormExtremum(n, 1).thetaDeg),
    secondary: viewAngle(closedFormExtremum(n, 2).thetaDeg),
  };
}
check(
  "primary: red is OUTSIDE violet (red at larger viewing angle)",
  colours.red.primary > colours.violet.primary,
  `red ${colours.red.primary.toFixed(2)}° > violet ${colours.violet.primary.toFixed(2)}°`
);
check(
  "secondary: colour order REVERSES (red inside violet)",
  colours.red.secondary < colours.violet.secondary,
  `red ${colours.red.secondary.toFixed(2)}° < violet ${colours.violet.secondary.toFixed(2)}°`
);
const primaryWidth = colours.red.primary - colours.violet.primary;
check(
  "primary bow width (red−violet) ≈ 1.7° (this is why the bow is ~2° wide)",
  close(primaryWidth, 1.7, 0.4),
  `${primaryWidth.toFixed(2)}° between red and violet edges`
);

// ─────────────────────────────────────────────────────────────────────────
// 5) Alexander of Aphrodisias' dark band (~200 AD): the gap between the bows
//    that no ray with one or two internal reflections reaches. Single-reflection light emerges only at viewing angles
//    ≤ the primary extremum (light fills the disc *inside* the primary); double-
//    reflection light only at angles ≥ the secondary extremum (outside it).
//    Sample every b for k=1 and k=2 and confirm the band (primaryRed, secondaryRed)
//    is reached by neither.
function reachableAngles(n, k, nRays = 4000) {
  let lo = +Infinity, hi = -Infinity;
  for (let j = 0; j < nRays; j++) {
    const b = (j + 0.5) / nRays;
    const th = deviation(deg(asin(b)), n, k);
    if (th == null) continue;
    const va = viewAngle(th);
    lo = Math.min(lo, va); hi = Math.max(hi, va);
  }
  return { lo, hi };
}
{
  const n = WATER.red.n; // band edges set by red (the extreme colour of each bow facing the band)
  const p = reachableAngles(n, 1);
  const s = reachableAngles(n, 2);
  // primary fills [0, ~42], secondary fills [~50.5, ~max]; band = (p.hi, s.lo)
  const bandLo = p.hi, bandHi = s.lo;
  check(
    "primary light only reaches angles ≤ its rainbow angle (disc inside is lit)",
    close(p.hi, colours.red.primary, 0.05) && p.lo < 5,
    `primary reaches ${p.lo.toFixed(2)}°..${p.hi.toFixed(2)}°`
  );
  check(
    "secondary light only reaches angles ≥ its rainbow angle (outside is lit)",
    close(s.lo, colours.red.secondary, 0.05),
    `secondary reaches ${s.lo.toFixed(2)}°..${s.hi.toFixed(2)}°`
  );
  check(
    "Alexander's dark band is genuinely empty (no 1- or 2-reflection ray lands in it)",
    bandHi - bandLo > 6 && bandLo > 41 && bandHi < 52,
    `dark band ≈ ${bandLo.toFixed(2)}°..${bandHi.toFixed(2)}° (width ${(bandHi - bandLo).toFixed(2)}°)`
  );
  bows.darkBand = { lo: bandLo, hi: bandHi };
}

// ─────────────────────────────────────────────────────────────────────────
// 6) The higher-order bows live around the SUN, not the antisolar point — which
//    is why the 3rd & 4th are nearly unobservable (lost in the glare) and were
//    first photographed only in 2011. Closed form for k=3,4; viewing angle is
//    measured from the antisolar point, so a value near 138° means 42° from the
//    sun (behind the observer's shadow-pointing axis).
for (const [name, k] of [["tertiary", 3], ["quaternary", 4]]) {
  const n = WATER.yellow.n;
  const th = closedFormExtremum(n, k).thetaDeg;
  const fromAnti = viewAngle(th);
  const fromSun = 180 - fromAnti;
  check(
    `${name} (k=${k}) sits toward the SUN, not the antisolar point`,
    fromSun < 60,
    `${fromSun.toFixed(1)}° from the sun (${fromAnti.toFixed(1)}° from antisolar)`
  );
  bows[name] = { k, fromSunDeg: fromSun };
}

// ─────────────────────────────────────────────────────────────────────────
// 7) THE WALL — where ray optics ends. Two facts ray optics cannot escape:
//    (a) JUST INSIDE the primary edge, viewing directions have TWO impact
//        parameters (the two sides of the extremum); they merge at the rainbow
//        angle and vanish beyond it. This is the geometry behind both the caustic
//        and the supernumeraries.
//    (b) Those two rays have different optical paths → they interfere (Young,
//        1804). Computing the path difference from the *traced* polyline, the
//        fringe spacing scales as (λ/a)^(2/3) — the Airy (1838) signature. We
//        confirm the two-ray structure, then the scaling across drop size and
//        colour. The full intensity envelope (the Airy integral) is cited, not
//        computed here: this verifies the *mechanism and its scaling*, and names
//        the rest as the wall.

// (a) two rays near the primary edge; one farther inside, none outside
function twoRaysAt(n, k, viewTarget) {
  // solve viewAngle(deviation(i)) = viewTarget for i on each side of i*
  const iStar = closedFormExtremum(n, k).iDeg;
  const g = (iDeg) => viewAngle(deviation(iDeg, n, k)) - viewTarget;
  function bisect(a, b) {
    let fa = g(a), fb = g(b);
    if (fa * fb > 0) return null;
    for (let it = 0; it < 200; it++) {
      const m = (a + b) / 2, fm = g(m);
      if (fa * fm <= 0) { b = m; fb = fm; } else { a = m; fa = fm; }
    }
    return (a + b) / 2;
  }
  const left = bisect(1, iStar);
  const right = bisect(iStar, 88);
  return [left, right].filter((x) => x != null);
}
{
  const n = WATER.yellow.n, k = 1, rb = bows.primary.viewAngle;
  const inside = twoRaysAt(n, k, rb - 1.0); // 1° inside the bow
  const deeper = twoRaysAt(n, k, 10); // counterexample to two rays at every interior angle
  const outside = twoRaysAt(n, k, rb + 1.0); // 1° outside (dark side)
  check(
    "1° inside the primary edge, TWO rays; at 10° from antisolar, ONE",
    inside.length === 2 && abs(inside[0] - inside[1]) > 1 && deeper.length === 1,
    `1° inside: ${inside.length} rays at i=${inside.map((x) => x.toFixed(1)).join(", ")}°; at 10°: ${deeper.length} ray`
  );
  check(
    "outside the primary (the dark side) NO ray reaches",
    outside.length === 0,
    `1° outside: ${outside.length} rays`
  );
}

// (b) optical-path difference between the two rays, from the tracer, and the
//     (λ/a)^(2/3) supernumerary scaling.
function opDifference(n, k, viewTarget) {
  // for unit drop (a=1): two rays at the same viewing angle, optical paths differ
  const is = twoRaysAt(n, k, viewTarget);
  if (is.length !== 2) return null;
  const t0 = trace(sin(is[0] * D), n, k);
  const t1 = trace(sin(is[1] * D), n, k);
  if (!t0 || !t1) return null;
  return abs(t0.op - t1.op); // in drop radii (a=1)
}
// supernumerary offset: angle inside the bow where path difference = m·(λ/a)
// (λ in drop radii). Sweep inward from the rainbow angle until ΔOP_radii = m·λ/a.
function supernumeraryOffset(n, k, lambda_over_a, m) {
  const rb = viewAngle(closedFormExtremum(n, k).thetaDeg);
  let lastD = 0;
  for (let off = 0.001; off < 5; off += 0.001) {
    const d = opDifference(n, k, rb - off); // ΔOP in drop radii (a=1)
    if (d == null) continue;
    // physical ΔOP/a = d (dimensionless, since op was for a=1). interference at
    // ΔOP = m·λ  →  d = m·(λ/a). Find first crossing for this m.
    if (lastD < m * lambda_over_a && d >= m * lambda_over_a) return off;
    lastD = d;
  }
  return null;
}
{
  // path difference grows from zero at the rainbow angle — confirm monotone onset
  const n = WATER.yellow.n, k = 1, rb = bows.primary.viewAngle;
  const dNear = opDifference(n, k, rb - 0.05);
  const dFar = opDifference(n, k, rb - 0.8);
  check(
    "the two rays' optical paths differ, and the gap grows away from the rainbow angle",
    dNear != null && dFar != null && dFar > dNear && dNear >= 0,
    `ΔOP: ${(dNear ?? NaN).toExponential(2)} (0.05° in) → ${(dFar ?? NaN).toExponential(2)} (0.8° in), drop radii`
  );

  // (λ/a)^(2/3) scaling across DROP SIZE: shrink the drop 8× → λ/a grows 8× →
  // the first supernumerary offset should grow by 8^(2/3) = 4×.
  const lam = 589e-9; // yellow, metres
  const aBig = 1.0e-3, aSmall = aBig / 8; // 1 mm vs 0.125 mm drops
  const offBig = supernumeraryOffset(WATER.yellow.n, 1, lam / aBig, 1);
  const offSmall = supernumeraryOffset(WATER.yellow.n, 1, lam / aSmall, 1);
  const sizeRatio = offSmall / offBig;
  check(
    "supernumerary spacing scales as (λ/a)^(2/3) across DROP SIZE (8× → 4×)",
    offBig && offSmall && close(sizeRatio, Math.pow(8, 2 / 3), 0.15),
    `1st supernumerary offset ${(offBig * 60).toFixed(2)}′ → ${(offSmall * 60).toFixed(2)}′ as a→a/8; ratio ${sizeRatio.toFixed(2)} vs 8^(2/3)=${Math.pow(8, 2 / 3).toFixed(2)}`
  );

  // (λ/a)^(2/3) scaling across COLOUR: 2× wavelength → 2^(2/3)=1.587× offset.
  const a = 0.3e-3;
  const offShort = supernumeraryOffset(WATER.yellow.n, 1, 400e-9 / a, 1);
  const offLong = supernumeraryOffset(WATER.yellow.n, 1, 800e-9 / a, 1);
  const colRatio = offLong / offShort;
  check(
    "supernumerary spacing scales as (λ/a)^(2/3) across WAVELENGTH (2× → 1.59×)",
    offShort && offLong && close(colRatio, Math.pow(2, 2 / 3), 0.15),
    `λ 400→800 nm: offset ratio ${colRatio.toFixed(2)} vs 2^(2/3)=${Math.pow(2, 2 / 3).toFixed(2)}`
  );

  // The DIRECTION of the size dependence — the observable, honest claim: smaller
  // drops spread the fringes wider. Visibility also depends on the spread of
  // drop sizes. We verify the monotone direction, not a restriction to mist.
  // Airy's wave approximation is cited, not computed here; this two-ray model
  // checks the scaling without claiming exact fringe positions.
  bows.supernumerary = {
    note: "Young (1804) two-ray interference: verified mechanism + (λ/a)^(2/3) scaling; Airy's (1838) wave approximation is cited, not computed; exact fringe positions are not claimed.",
    sizeScalingExponent_target: 2 / 3,
    sizeRatio_8x_drops: sizeRatio,
    colourRatio_2x_lambda: colRatio,
  };
  check(
    "smaller drops spread the fringes wider",
    offSmall != null && offBig != null && offSmall > offBig,
    `1st-fringe offset grows ${(offSmall / offBig).toFixed(2)}× when the drop shrinks 8×`
  );
}

// ─────────────────────────────────────────────────────────────────────────
// 8) The wink, kept honest: the primary rainbow's radius (~42°) and Douglas
//    Adams' "Answer to Everything" (42) are the SAME integer by coincidence —
//    a fact about a base-10 degree convention, not about nature. Asserted as a
//    coincidence, never as meaning.
check(
  "the 42° radius rounds to the integer 42 (a base-10 coincidence, not a law)",
  Math.round(bows.primary.viewAngle) === 42,
  `primary radius ${bows.primary.viewAngle.toFixed(2)}° → rounds to 42`
);

// ─────────────────────────────────────────────────────────────────────────
const passed = checks.filter((c) => c.pass).length;
const artifact = {
  title: "The Edge of the Bow — geometric optics of the rainbow",
  generated: new Date().toISOString(),
  water_refractive_index: WATER,
  bows: {
    primary: { ...bows.primary, descartes: undefined },
    secondary: bows.secondary,
    tertiary: bows.tertiary,
    quaternary: bows.quaternary,
  },
  descartes_pileup: bows.primary.descartes,
  colours,
  primary_bow_width_deg: primaryWidth,
  alexanders_dark_band: bows.darkBand,
  supernumerary: bows.supernumerary,
  checks: { passed, total: checks.length, all: checks },
};
writeFileSync(
  new URL("./artifact.json", import.meta.url),
  JSON.stringify(artifact, null, 2)
);

console.log(`\nThe Edge of the Bow — ${passed}/${checks.length} checks passing.`);
console.log(`  primary   rainbow angle : ${bows.primary.viewAngle.toFixed(2)}°  (red ${colours.red.primary.toFixed(2)}° outer, violet ${colours.violet.primary.toFixed(2)}° inner)`);
console.log(`  secondary rainbow angle : ${bows.secondary.viewAngle.toFixed(2)}°  (colours reversed)`);
console.log(`  Alexander's dark band   : ${bows.darkBand.lo.toFixed(2)}°..${bows.darkBand.hi.toFixed(2)}°`);
console.log(`  supernumerary scaling   : (λ/a)^(2/3) confirmed (8× drop → ${bows.supernumerary.sizeRatio_8x_drops.toFixed(2)}×, target ${Math.pow(8, 2 / 3).toFixed(2)}×)`);
console.log(`  artifact → research/the-edge-of-the-bow/artifact.json`);
if (passed !== checks.length) process.exit(1);
