#!/usr/bin/env node
// verify.mjs — every number the "Half a Turn to the Floor" stratum shows,
// recomputed from first principles / from Matthews's published relations and
// asserted. Run: `node research/butter-side-down/verify.mjs`.
//
// THE CLAIM THE PAGE SETTLES (narrow and sturdy):
//   Toast knocked off a table EDGE has a real, physical bias to land
//   butter-side-down — not because of the butter's weight, and not because
//   it's "all in your head," but because it leaves the edge buttered-side-up
//   and from a table-height fall there is only time for about HALF a turn.
//   It is geometry, not luck and not psychology. The famous debunk ("just
//   confirmation bias / it's really 50-50") is testing the WRONG drop:
//   thrown or dropped-flat toast really is ~50-50 (no angular momentum) —
//   MythBusters got both answers in one episode. The bias is specific to the
//   edge-pivot launch, which happens to be the usual real-world failure mode.
//
// THE MODEL (Matthews 1995). Toast = thin rigid lamina, half-length a. Its
//   centre of mass overhangs the edge by delta; eta = delta/a is the overhang
//   parameter (eta0 ~ 0.015 for toast, ~0.02 for bread; mu ~ 0.25). Gravity
//   torque pivots it about the edge; it grips and turns, then slips free at a
//   detachment angle phi with angular velocity
//        omega0^2 = (6 g / a) * (eta0 / (1 + 3 eta0^2)) * sin(phi)
//   then free-falls rotating at constant omega0 for time tau = sqrt(2(h-2a)/g).
//   The toast lands butter-DOWN if its total turn lands in (90 deg, 270 deg);
//   to recover butter-UP it must pass 270 deg. Matthews's published closed
//   forms (via Oikofuge's verbatim transcription; corroborated by the peer-
//   reviewed Bacon, Heald & James 2001):
//        critical table height for butter-up:  h/a = 2 + pi^2 (1+3 eta0^2)/(12 eta0)
//        overhang needed for butter-up at h=0.75 m, a=0.05 m:  eta0 > ~0.06
//   We could NOT machine-read the original 1995 scan (the PDF text layer is
//   corrupted), so the detachment treatment we use (the on-edge turn phi and
//   sin phi consistent with BOTH published thresholds) is a reconstruction:
//   it is the unique choice that makes the two published formulas exact, and
//   it reproduces the third anchor (the ~half-turn butter-down result) on its
//   own. Where a value is cited rather than computed we say so.
//
// SOURCES
//   Matthews, R.A.J. "Tumbling toast, Murphy's Law and the fundamental
//     constants." Eur. J. Phys. 16(4), 172-176 (1995). DOI 10.1088/0143-0807/16/4/005.
//     (1996 Ig Nobel Prize in Physics.)
//   Bacon, M.E.; Heald, G.; James, M. "A closer look at tumbling toast."
//     Am. J. Phys. 69(1), 38-43 (2001). DOI 10.1119/1.1289213.
//   Press, W.H. "Man's size in terms of fundamental constants." Am. J. Phys.
//     48(8), 597-598 (1980). DOI 10.1119/1.12326.
//   Matthews, R.A.J. "Testing Murphy's Law: urban myths as a source of school
//     science projects." School Science Review 83(302), 23-28 (2001).
//   Oikofuge, "R.A.J. Matthews: Tumbling Toast..." (verbatim eqn transcription).
//   MythBusters episode 28 (2005), mythresults.com/episode28.

let pass = 0, fail = 0;
const approx = (a, b, rel = 0.02) => Math.abs(a - b) <= Math.abs(b) * rel;
function check(name, got, want, rel) {
  const ok = approx(got, want, rel);
  const g = typeof got === 'number' ? got.toPrecision(6) : got;
  const w = typeof want === 'number' ? want.toPrecision(6) : want;
  console.log(`${ok ? 'ok  ' : 'FAIL'}  ${name}: ${g}  (expect ~ ${w})`);
  ok ? pass++ : fail++;
}
function assert(name, cond) {
  console.log(`${cond ? 'ok  ' : 'FAIL'}  ${name}`);
  cond ? pass++ : fail++;
}

const g = 9.81;            // m/s^2
const DEG = 180 / Math.PI;
const a = 0.05;            // toast half-length, m (a 10 cm slice)
const ETA_TOAST = 0.015;   // overhang parameter, toasted bread
const ETA_BREAD = 0.020;   // overhang parameter, untoasted bread
const PHI = Math.PI / 2;   // detachment / on-edge turn in this reconstruction (sin phi = 1)

// ── The model, exactly as drawn in the instrument ───────────────────────────
// angular velocity at departure (Matthews's relation)
function omega0(eta) { return Math.sqrt((6 * g / a) * (eta / (1 + 3 * eta * eta)) * Math.sin(PHI)); }
// free-fall time after departure
function tau(h) { return Math.sqrt(2 * Math.max(h - 2 * a, 0) / g); }
// total turn at impact (radians): on-edge turn + free-fall turn
function totalTurn(h, eta) { return PHI + omega0(eta) * tau(h); }
// lands butter-down iff the turn lands in (90 deg, 270 deg)
function buttersDown(h, eta) {
  const t = ((totalTurn(h, eta) * DEG) % 360 + 360) % 360;
  return t > 90 && t < 270;
}
// Matthews's published critical-height closed form
function critHeightOverA(eta) { return 2 + Math.PI * Math.PI * (1 + 3 * eta * eta) / (12 * eta); }

console.log('\n— The drop: rotation and verdict —');

// 1. From a standard ~0.75 m table, real toast turns ~half a turn -> butter-down
const turn075 = totalTurn(0.75, ETA_TOAST) * DEG;
check('total turn from a 0.75 m table (deg)', turn075, 178, 0.03);
assert('  ...lands in the (90,270) window -> BUTTER-DOWN', buttersDown(0.75, ETA_TOAST));
assert('  ...and it is essentially half a turn (170-190 deg)', turn075 > 170 && turn075 < 190);

// 2. The free-fall turn alone is ~88 deg; the rest is the on-edge grip (~90 deg)
const fallTurn = omega0(ETA_TOAST) * tau(0.75) * DEG;
check('free-fall turn alone from 0.75 m (deg)', fallTurn, 87.6, 0.03);

// 3. Critical table height for a butter-UP landing (normal toast) ~ 2.8-3 m
const hCrit = critHeightOverA(ETA_TOAST) * a;
check('critical table height for butter-up, toast (m)', hCrit, 2.84, 0.03);
assert('  ...Matthews reports "about three metres"', approx(hCrit, 3.0, 0.1));
assert('  a 0.75 m table is far below the flip height', 0.75 < hCrit / 3);

// 4. At the critical height the turn is exactly 270 deg (edge-on -> just butter-up)
check('turn at the critical height (deg)', totalTurn(hCrit, ETA_TOAST) * DEG, 270, 0.01);
assert('  just above the critical height it flips to butter-up',
  !buttersDown(hCrit * 1.05, ETA_TOAST) && buttersDown(hCrit * 0.95, ETA_TOAST));

// 5. The overhang threshold at a normal table: need eta0 > ~0.06 for butter-up
//    (solve totalTurn(0.75, eta) = 270 deg for eta)
function thresholdEta(h) {
  let lo = 0.001, hi = 0.5;
  for (let i = 0; i < 80; i++) {
    const mid = (lo + hi) / 2;
    (totalTurn(h, mid) * DEG < 270) ? (lo = mid) : (hi = mid);
  }
  return (lo + hi) / 2;
}
const etaCrit = thresholdEta(0.75);
check('overhang eta0 needed for butter-up at 0.75 m', etaCrit, 0.064, 0.05);
assert('  ...> Matthews\'s stated "exceed 0.06"; real toast (0.015) is well under', etaCrit > 0.06 && ETA_TOAST < etaCrit);

// 6. Bread (eta0=0.02) turns slightly more than toast, but still butter-down from a table
assert('untoasted bread also lands butter-down from a 0.75 m table', buttersDown(0.75, ETA_BREAD));
assert('bread (more overhang) turns a touch more than toast', totalTurn(0.75, ETA_BREAD) > totalTurn(0.75, ETA_TOAST));

console.log('\n— The schools experiment (cited figures; stats recomputed) —');
// Matthews 2001 schools experiment, free-fall-from-table trial.
// 9,821 drops / 6,101 butter-side-down is the precise pair that traces through
// secondary sources; the round "21,000" in the popular press is the total
// across all three of his experiments (breakdown unverified). We assert the
// arithmetic + significance, and label the counts as cited, not measured.
const N = 9821, DOWN = 6101;
const frac = DOWN / N;
check('butter-down fraction 6101/9821', frac, 0.6212, 1e-3);
assert('  ...about 62%, well above chance', frac > 0.60 && frac < 0.63);
const z = (frac - 0.5) / Math.sqrt(0.25 / N);     // one-proportion z vs p=0.5
check('z-score vs the 50-50 null', z, 24.0, 0.02);
assert('  ...overwhelmingly significant (z > 5)', z > 5);

console.log('\n— The fundamental-constants reach (Matthews\'s "rough and ready" arg) —');
// Press (1980) / Matthews (1995): the max height of a bipedal organism is set
// by the requirement that a fall onto the head not fracture the skull; bone
// strength bottoms out in atomic binding energy, hence the fundamental
// constants. Matthews: L_H < ~50 (alpha/alpha_G)^(1/4) a0. The prefactor ~50
// is itself a rough composite of biological order-of-magnitude factors; we
// compute the constants-only core and recover ~3 m. THIS IS EXPLICITLY
// ORDER-OF-MAGNITUDE / SEMI-SERIOUS (Matthews's own words: "pretty rough and
// ready"; Press's brittle version was ~100x too small).
const alpha = 7.2973525693e-3;            // fine-structure constant
const G = 6.67430e-11;                    // m^3 kg^-1 s^-2
const m_p = 1.67262192369e-27;            // kg
const hbar = 1.054571817e-34;             // J s
const c = 2.99792458e8;                   // m/s
const a0 = 5.29177210903e-11;             // Bohr radius, m
const alpha_G = G * m_p * m_p / (hbar * c);   // gravitational coupling (protons)
check('gravitational coupling alpha_G', alpha_G, 5.906e-39, 5e-3);
check('alpha / alpha_G', alpha / alpha_G, 1.2356e36, 5e-3);
const L_H = 50 * Math.pow(alpha / alpha_G, 0.25) * a0;
check('max biped height L_H (m)', L_H, 2.79, 0.05);
assert('  ...lands at the "~3 m" Matthews quotes', approx(L_H, 3.0, 0.1));
// the tallest verified human, Robert Wadlow, was 2.72 m — inside the bound.
const WADLOW = 2.72;
assert('tallest human ever (Wadlow, 2.72 m) sits inside the L_H bound', WADLOW < L_H);
// the punchline: a table can be at most ~L_H/2, still far below the flip height
assert('max table (~L_H/2) is below the ~2.8 m a toast needs to flip back', L_H / 2 < hCrit);

console.log('\n— The drop method is everything (the record-correction) —');
// Thrown / dropped-flat toast carries little or no spin -> ~50-50. We model the
// "no edge" cases as zero imparted rotation: the verdict is then a coin flip,
// NOT a butter-down bias. (Asserted structurally, not as a measured number.)
assert('edge-pivot launch produces a real bias (butter-down)', buttersDown(0.75, ETA_TOAST));
assert('the bias needs the edge: it is geometric, present for a wide range of heights below ~2.8 m',
  buttersDown(0.4, ETA_TOAST) && buttersDown(1.0, ETA_TOAST) && buttersDown(2.0, ETA_TOAST));

console.log(`\n${fail === 0 ? 'ALL GREEN' : 'SOME RED'} — ${pass}/${pass + fail} checks passed.`);
process.exit(fail === 0 ? 0 : 1);
