#!/usr/bin/env node
// verify.mjs — the tea-leaf paradox, recomputed.  Deterministic (seeded), no deps.
//
//   node research/tea-leaf-paradox/verify.mjs
//
// WHAT THIS PROVES, AND WHAT IT DOESN'T.
//   The *rigorous* claim is CHECK 1: the sign of the net radial force in a
//   rotating fluid's bottom boundary layer. It follows from two facts that are
//   not in dispute — (a) the radial pressure gradient is set by the rotating
//   BULK (dp/dr = rho * Omega^2 * r, supplying the centripetal force up there),
//   and (b) friction slows the swirl near the floor (no-slip). A parcel near the
//   floor therefore feels the full inward pressure gradient but needs less
//   centripetal force, so the residual is a net INWARD force. That residual is
//   the engine of the whole paradox, and it is computed exactly below.
//
//   CHECKS 2-3 are ILLUSTRATIVE, not a first-principles Navier-Stokes solve:
//   they advect dense particles through a STYLISED axisymmetric flow that has the
//   circulation pattern Check 1 forces (inward along the bottom, up at the centre,
//   out at the top, down at the rim) and confirm the consequence — leaves pile at
//   the CENTRE — while the naive "centrifuge only" field sends them to the RIM.
//   This shows the mechanism's outcome; it does not derive the flow from scratch.
//   The page uses this same stylised field for its animation, and labels it as
//   such. The un-fakeable check is the one in your own kitchen: stir a real cup.
//
//   CHECK 4 is an order-of-magnitude estimate for a real teacup from the standard
//   scaling laws, with every input value printed. It is a scaling, not a
//   cup-specific measurement.
//
// Sources for the physics (cited, not computed): Thomson 1857; Einstein, Die
// Naturwissenschaften 14 (1926) 223-224; Bowles, "The Ekman Layer and Why Tea
// Leaves Go to the Center of the Cup"; Cushman-Roisin, Environmental Fluid
// Mechanics, ch. 8 (Ekman layer); Acheson, Elementary Fluid Dynamics.

'use strict';

// ── deterministic RNG (mulberry32) so runs are reproducible ──────────────────
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

let pass = 0, fail = 0;
function check(name, cond, detail) {
  (cond ? (pass++) : (fail++));
  console.log(`  ${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  — ' + detail : ''}`);
}
const r3 = (x) => Math.round(x * 1000) / 1000;

// Geometry, normalised: cup radius R = 1, depth H = 1, bulk rotation Omega = 1.
const R = 1, H = 1, OMEGA = 1;
// Boundary-layer thickness as a fraction of depth (schematic; real cups: delta/H ~ 1e-2).
const DELTA = 0.12;

// Swirl speed at height z (0 = floor, H = surface), as a fraction of the
// solid-body value Omega*r. Classic rotating-frame (Ekman-type) boundary layer:
// f(0)=0 at the no-slip floor, f -> 1 in the bulk, with the standard small
// overshoot of the Ekman spiral.  f = 1 - e^{-z/delta} cos(z/delta).
function swirlFrac(z) {
  const s = z / DELTA;
  return 1 - Math.exp(-s) * Math.cos(s);
}

console.log('TEA-LEAF PARADOX — verification\n');

// ── CHECK 1 — the mechanism: net radial force is INWARD in the boundary layer ──
// Per unit mass, at radius r and height z:
//   pressure-gradient term (set by the bulk):  -dp/dr / rho = -Omega^2 * r   (inward)
//   centripetal requirement of the local swirl: +v_theta^2 / r = +Omega^2 r f(z)^2
//   net radial acceleration a_r = Omega^2 r (f(z)^2 - 1)   <= 0  (inward) when f<=1
console.log('CHECK 1 — radial force balance (the engine), at r = 0.6 R:');
console.log('  z/H     swirl f(z)   a_r / (Omega^2 R)   direction');
const rTest = 0.6;
let aFloor = null, aBulk = null;
for (const z of [0.0, 0.04, 0.12, 0.3, 0.6, 1.0]) {
  const f = swirlFrac(z);
  const ar = OMEGA * OMEGA * rTest * (f * f - 1);   // net radial accel per mass
  if (z === 0.0) aFloor = ar;
  if (z === 1.0) aBulk = ar;
  const dir = ar < -1e-6 ? 'INWARD' : (ar > 1e-6 ? 'outward' : '~balanced');
  console.log(`  ${z.toFixed(2)}    ${r3(f).toString().padEnd(8)}    ${r3(ar).toString().padEnd(12)}      ${dir}`);
}
check('net radial force at the floor is strongly inward',
  aFloor < -0.3 * OMEGA * OMEGA * rTest, `a_r(floor) = ${r3(aFloor)} (Omega^2 R units)`);
check('net radial force in the bulk is ~balanced (|a_r| small)',
  Math.abs(aBulk) < 0.05 * OMEGA * OMEGA * rTest, `a_r(bulk) = ${r3(aBulk)}`);
console.log('');

// ── the stylised secondary (meridional) circulation Check 1 forces ───────────
// Inward along the bottom, upwelling at the centre, outward at the top, down the
// rim. Radial component: strong inward near the floor, fading with height; a weak
// outward return up high.  (Schematic; the qualitative pattern is what matters.)
function uRadial(rr, z) {
  const shape = rr * (1 - (rr * rr) / (R * R));        // 0 at axis and at wall, peak mid-radius
  const bottomIn = -Math.exp(-z / (2.2 * DELTA));      // inward, concentrated near the floor
  const topOut = 0.35 * Math.max(0, (z - 0.5) / 0.5);  // weak outward return near the surface
  return shape * (bottomIn + topOut);
}

// Advect dense (settling) particles. Each step: settle toward the floor, get
// carried radially by uRadial at its height; swirl only spins it (no radius
// change). Reflect at the wall, clamp at the floor.  Pure kinematics.
function runCloud({ seed, centrifugeOnly }) {
  const rng = mulberry32(seed);
  const N = 600, steps = 4000, dt = 0.01, settle = 0.5;
  const P = [];
  for (let i = 0; i < N; i++) P.push({ r: Math.sqrt(rng()) * 0.95 * R, z: 0.3 + rng() * 0.6 });
  const meanR0 = P.reduce((s, p) => s + p.r, 0) / N;
  for (let s = 0; s < steps; s++) {
    for (const p of P) {
      p.z -= settle * dt;                       // sediment toward the floor
      if (p.z < 0) p.z = 0;
      const ur = centrifugeOnly
        ? 0.6 * p.r * (1 - p.r * p.r)            // naive: pure outward flinging
        : uRadial(p.r, p.z);                     // real: boundary-layer secondary flow
      p.r += ur * dt;
      if (p.r < 0) p.r = -p.r;
      if (p.r > R) p.r = R - (p.r - R);          // reflect at the wall
    }
  }
  const meanR = P.reduce((s, p) => s + p.r, 0) / N;
  const fracCentre = P.filter((p) => p.r < 0.2 * R).length / N;
  const fracRim = P.filter((p) => p.r > 0.8 * R).length / N;
  return { meanR0, meanR, fracCentre, fracRim };
}

// ── CHECK 2 — the consequence: the secondary flow piles leaves at the CENTRE ──
console.log('CHECK 2 — advecting 600 dense particles in the real (secondary-flow) field:');
const real = runCloud({ seed: 12345, centrifugeOnly: false });
console.log(`  mean radius: ${r3(real.meanR0)} R  ->  ${r3(real.meanR)} R`);
console.log(`  fraction within centre (r < 0.2 R): ${r3(real.fracCentre)}`);
check('mean radius collapses toward the axis', real.meanR < 0.25 * R, `final mean r = ${r3(real.meanR)} R`);
check('the great majority end in the central pile', real.fracCentre > 0.85, `${(real.fracCentre * 100).toFixed(0)}% within r < 0.2 R`);
console.log('');

// ── CHECK 3 — the contrast: the naive centrifuge picture sends them to the RIM ─
console.log('CHECK 3 — the same particles in the naive "centrifuge only" field:');
const naive = runCloud({ seed: 12345, centrifugeOnly: true });
console.log(`  mean radius: ${r3(naive.meanR0)} R  ->  ${r3(naive.meanR)} R`);
console.log(`  fraction at the rim (r > 0.8 R): ${r3(naive.fracRim)}`);
check('the naive picture drives them to the rim', naive.meanR > 0.8 * R, `final mean r = ${r3(naive.meanR)} R`);
check('centre vs rim — the two pictures genuinely disagree',
  real.meanR < 0.3 && naive.meanR > 0.8, `centre ${r3(real.meanR)} R vs rim ${r3(naive.meanR)} R`);
console.log('');

// ── CHECK 4 — order-of-magnitude scalings for a real teacup ──────────────────
// Standard laws (Cushman-Roisin ch. 8): Ekman-layer thickness delta ~ sqrt(nu/Omega);
// Ekman number E = nu/(Omega H^2); spin-up (Ekman) time t_su ~ H / sqrt(nu*Omega).
console.log('CHECK 4 — teacup scalings (inputs printed; this is a scaling, not a measurement):');
const nu = 1.0e-6;     // kinematic viscosity of water near room temp, m^2/s
const Hc = 0.05;       // cup depth, m  (~5 cm)
const Om = 6.0;        // fluid rotation after a brisk stir, rad/s (~1 turn/s)
const delta = Math.sqrt(nu / Om);
const Ek = nu / (Om * Hc * Hc);
const tSpinUp = Hc / Math.sqrt(nu * Om);
const tViscous = Hc * Hc / nu;
console.log(`  inputs: nu = ${nu} m^2/s, H = ${Hc} m, Omega = ${Om} rad/s`);
console.log(`  Ekman-layer thickness  delta ~ sqrt(nu/Omega) = ${(delta * 1000).toFixed(2)} mm`);
console.log(`  Ekman number           E = nu/(Omega H^2)      = ${Ek.toExponential(1)}`);
console.log(`  spin-up (Ekman) time   t ~ H/sqrt(nu*Omega)    = ${tSpinUp.toFixed(0)} s`);
console.log(`  pure-viscous time      H^2/nu                  = ${tViscous.toFixed(0)} s  (would-be, if no Ekman pumping)`);
check('Ekman layer is sub-millimetre to millimetre thin', delta > 1e-4 && delta < 2e-3, `${(delta * 1000).toFixed(2)} mm`);
check('spin-up time is tens of seconds (matches the kitchen)', tSpinUp > 5 && tSpinUp < 120, `${tSpinUp.toFixed(0)} s`);
check('Ekman pumping settles the cup far faster than viscosity alone', tSpinUp < 0.1 * tViscous,
  `${tSpinUp.toFixed(0)} s vs ${tViscous.toFixed(0)} s`);
console.log('');

console.log(`${fail === 0 ? 'ALL GREEN' : 'SOME FAILED'} — ${pass} passed, ${fail} failed.`);
process.exit(fail === 0 ? 0 : 1);
