// verify.mjs — the check for "The Ring the Coffee Leaves" (the coffee-ring effect).
// Every number the interactive page prints is computed here, and every physical
// claim it makes is put to a numerical or analytic test. Run:
//     node verify.mjs        # prints the checklist, writes data.json, exits nonzero on fail.
//
// The stratum's thesis, made testable:
//
//   A drop of coffee dries to a dark RING, not a filled spot, because
//     (a) the contact line is PINNED (roughness/particles anchor the edge), and
//     (b) the drop evaporates FASTEST at that edge, so
//     (c) an outward capillary flow rushes to replenish the edge, carrying
//         essentially all the suspended particles there.
//
//   The non-obvious heart of (b): for a thin pinned drop in the diffusion-limited
//   regime, the vapour concentration above the drop solves Laplace's equation
//   with the drop surface held at saturation and the dry substrate flux-free —
//   the SAME boundary-value problem as a charged conducting DISK held at a fixed
//   potential. So the local evaporative flux J(r) is, exactly, the surface field
//   of that disk:  J(r) ∝ (1 − (r/R)²)^(−1/2), diverging (integrably) at the rim;
//   and the drop's total mass-loss rate is the disk's CAPACITANCE, C = 8 ε₀ R —
//   set by the RADIUS, not the area (the "diameter law").
//
//   Refs: Deegan, Bakajin, Dupont, Huber, Nagel & Witten, Nature 389 (1997) 827
//   ("Capillary flow as the cause of ring stains…"); Deegan et al., Phys. Rev. E
//   62 (2000) 756 (the flux exponent, contact-angle dependent); Popov, Phys. Rev.
//   E 71 (2005) 036313 (evaporation & deposit growth); Jackson, Classical
//   Electrodynamics, §3.12 & the charged-disk capacitance C=8ε₀a.
//
// Nothing about the answer is assumed. The (1−(r/R)²)^(−1/2) law and the "8" are
// recovered from a Coulomb kernel + an equipotential demand in disk.mjs; the
// edge-weighting and the contact-angle exponent are then checked in closed form.

import { solveDisk, cumulative, cumExact, ringPotentialInPlane } from './disk.mjs';
import { writeFileSync } from 'node:fs';

const checks = [];
const check = (name, pass, detail) => { checks.push({ name, pass: !!pass, detail }); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ─────────────────────────────────────────────────────────────────────────────
// 1. THE FLUX PROFILE IS A CHARGED DISK: σ(r) ∝ (1 − (r/R)²)^(−1/2)
//    Verified by recovering the cumulative charge law Q(r)/Q(R)=1−√(1−(r/R)²)
//    from the numerical solve (which knows only Coulomb's law + "be equipotential").
// ─────────────────────────────────────────────────────────────────────────────
const R = 1;
const solHi = solveDisk(R, 600, 1);
{
  let worst = 0;
  const probes = [0.3, 0.5, 0.7, 0.9, 0.95];
  for (const x of probes) worst = Math.max(worst, Math.abs(cumulative(solHi, x * R) - cumExact(x * R, R)));
  check('numerical disk charge follows Q(r)/Q(R)=1−√(1−(r/R)²)  (⇒ σ∝(1−(r/R)²)^(−½))',
    worst < 2e-3, `max deviation ${worst.toExponential(2)} over r/R∈{${probes.join(',')}}`);
}
{
  // Convergence: the deviation must SHRINK as the discretisation refines — proof
  // the residual is discretisation, not a real departure from the (1−·)^(−½) law.
  const dev = (K) => {
    const s = solveDisk(R, K, 1);
    let w = 0; for (const x of [0.5, 0.9]) w = Math.max(w, Math.abs(cumulative(s, x * R) - cumExact(x * R, R)));
    return w;
  };
  const d1 = dev(150), d2 = dev(600);
  check('that agreement TIGHTENS as the solve refines (it is the law, not a fit)',
    d2 < d1 * 0.6, `K=150 dev ${d1.toExponential(2)} → K=600 dev ${d2.toExponential(2)}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 2. THE "8": disk capacitance C = 8 ε₀ R  ⇒ total evaporation ∝ RADIUS, not area
//    disk.mjs works in units where 1/(4πε₀)=1, so C_gaussian = Q/V0 → 2R/π,
//    and C_SI = 4πε₀·C_gaussian = 8 ε₀ R.  We recover the coefficient 8.
// ─────────────────────────────────────────────────────────────────────────────
{
  const Cg = solHi.Q / solHi.V0;          // Q/V0 in natural units → 2R/π
  const coeff = 4 * Math.PI * Cg / R;      // = C_SI/(ε₀R), should → 8
  check('disk capacitance coefficient recovered as C = 8 ε₀ R  (the "diameter law")',
    near(coeff, 8, 0.02), `numeric C/(ε₀R) = ${coeff.toFixed(4)} (exact 8; 2R/π check ${Cg.toFixed(5)} vs ${(2 / Math.PI).toFixed(5)})`);
}
{
  // Total flux scales with R, not R²: double the radius, capacitance doubles.
  const s2 = solveDisk(2 * R, 600, 1);
  const ratio = (s2.Q / s2.V0) / (solHi.Q / solHi.V0);
  check('double the drop radius → total evaporation rate DOUBLES (∝R), not ×4 (∝R²)',
    near(ratio, 2, 0.01), `Q(2R)/Q(R) = ${ratio.toFixed(4)} (perimeter/diameter law: exactly 2)`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 3. THE EDGE-WEIGHTING, EXACTLY. With J(r)∝(1−(r/R)²)^(−½), the flux emitted
//    between radii r₁ and r₂ is ∝ √(1−(r₁/R)²) − √(1−(r₂/R)²). So the outer
//    10% of the RADIUS (only 19% of the AREA) emits √0.19 = 43.6% of all vapour.
// ─────────────────────────────────────────────────────────────────────────────
const fluxOutside = (x) => Math.sqrt(1 - x * x);            // fraction of flux from r>xR
{
  const f = fluxOutside(0.9);                                // outer 10% of radius
  check('outer 10% of the radius (19% of the area) emits √0.19 = 43.6% of the vapour',
    near(f, Math.sqrt(0.19), 1e-12), `analytic fraction = ${(100 * f).toFixed(1)}%  (=√0.19)`);
  // cross-check the analytic edge fraction against the NUMERIC disk solve
  const fNum = 1 - cumulative(solHi, 0.9 * R);
  check('…and the numerical disk solve agrees on that 43.6% edge fraction',
    Math.abs(fNum - f) < 3e-3, `numeric ${(100 * fNum).toFixed(1)}% vs analytic ${(100 * f).toFixed(1)}%`);
  // The clean headline: the outer QUARTER-of-the-area (r > √¾ R) emits exactly HALF.
  const rHalf = Math.sqrt(0.75);                             // area outside = 1 − 0.75 = 25%
  check('the outer 25% of the AREA (r > √¾·R ≈ 0.866R) emits exactly 50% of the vapour',
    near(fluxOutside(rHalf), 0.5, 1e-12), `flux beyond 0.866R = ${(100 * fluxOutside(rHalf)).toFixed(1)}% (=√(1−¾)); inner half r<0.5R emits only ${(100 * (1 - fluxOutside(0.5))).toFixed(1)}%`);
}
{
  // The flux DIVERGES at the rim but the TOTAL is finite: ∫₀ᴿ (1−(r/R)²)^(−½) r dr
  // /R² = 1 (finite), while J(r)→∞ as r→R. Show the integral is finite & =1.
  const N = 200000; let I = 0;
  for (let i = 0; i < N; i++) { const r = (i + 0.5) / N; I += r / Math.sqrt(1 - r * r) / N; }
  check('rim flux DIVERGES yet total is finite (integrable singularity): ∫₀¹ r(1−r²)^(−½)dr = 1',
    near(I, 1, 2e-3), `numeric ∫ = ${I.toFixed(4)} (exact 1)`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 4. THE CONTACT-ANGLE EXPONENT. For a spherical-cap drop of contact angle θ the
//    edge flux goes as (R−r)^(−λ) with λ = (π−2θ)/(2π−2θ)  (Deegan 2000; Popov
//    2005). θ→0 gives the flat-disk ½; θ=90° gives λ=0 (UNIFORM flux, no rush to
//    the edge); θ>90° gives λ<0 — flux peaks at the CENTRE, the ring inverts.
// ─────────────────────────────────────────────────────────────────────────────
const lambda = (thetaDeg) => { const t = thetaDeg * Math.PI / 180; return (Math.PI - 2 * t) / (2 * Math.PI - 2 * t); };
{
  check('λ(0°) = ½ — the flat-drop limit matches the charged disk exactly',
    near(lambda(0), 0.5, 1e-12), `λ(0°) = ${lambda(0).toFixed(4)}`);
  check('λ(90°) = 0 — a hemispherical drop evaporates UNIFORMLY (no edge rush)',
    near(lambda(90), 0, 1e-12), `λ(90°) = ${lambda(90).toFixed(6)}`);
  check('λ(120°) < 0 — a fat, non-wetting drop peaks its flux at the CENTRE (ring inverts)',
    lambda(120) < 0, `λ(120°) = ${lambda(120).toFixed(4)}`);
  check('λ(40°) = 5/14 = 0.3571 exactly — a typical partially-wetting drop is still edge-weighted',
    near(lambda(40), 5 / 14, 1e-4), `λ(40°) = ${lambda(40).toFixed(5)} (exact 5/14 = ${(5 / 14).toFixed(5)})`);
  // The popular linear shortcut λ ≈ ½ − θ/π (Hu & Larson 2002) is right only at the
  // endpoints and wrong in the middle — a "show the check" catch, not a fudge.
  const huLarson = (deg) => 0.5 - (deg * Math.PI / 180) / Math.PI;   // = 0.5 − θ/π
  check('the widely-quoted linear shortcut λ≈½−θ/π is off by 22% at 40° (0.278 vs 0.357) — we use the exact wedge λ',
    Math.abs(huLarson(40) - lambda(40)) > 0.07 && near(huLarson(0), lambda(0), 1e-9) && near(huLarson(90), lambda(90), 1e-9),
    `linear ${huLarson(40).toFixed(3)} vs exact ${lambda(40).toFixed(3)} at 40°; agree only at 0° & 90°`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 5. THE COMPENSATING OUTWARD FLOW. Mass conservation in a thin pinned drop forces
//    a depth-averaged radial velocity that carries liquid (and its particles) to
//    the rim. Its sign must be OUTWARD everywhere (v̄_r > 0 for 0<r<R) whenever the
//    edge evaporates faster than the mean — which the (1−(r/R)²)^(−½) profile does.
//    We test the sign using the thin-drop height-averaged mass balance directly:
//        v̄_r(r) · h(r) · r  =  (1/ρ)∫₀ʳ [J_z(r') − (ḣ contribution)] r' dr'
//    Rather than model h(t) in detail (idealisation-heavy), we test the robust
//    core: the cumulative evaporative loss inside r outruns the areal share, so
//    liquid must be exported across every interior circle → outward flow.
// ─────────────────────────────────────────────────────────────────────────────
{
  // Fraction of the drop's PLAN AREA inside radius x is x². Fraction of the
  // evaporation drawn from inside x is Q(x)/Q(R)=1−√(1−x²). Because evaporation
  // is edge-heavy, the area inside x loses LESS than its area share only near the
  // centre — the imbalance integrated is what drives flow. The clean, sign-robust
  // statement: for every 0<x<1 the OUTER region beyond x loses more than its area
  // share, so net liquid must move outward across the circle at x.
  let outwardEverywhere = true, worstX = 0;
  for (let i = 1; i < 100; i++) {
    const x = i / 100;
    const evapOutside = fluxOutside(x);          // share of evaporation beyond x
    const areaOutside = 1 - x * x;               // area share beyond x
    if (evapOutside <= areaOutside) { outwardEverywhere = false; worstX = x; }
  }
  check('edge always over-evaporates vs its area share ⇒ flow is OUTWARD across every interior circle',
    outwardEverywhere, outwardEverywhere ? 'evap-share > area-share for all r (drives particles to the rim)' : `fails at x=${worstX}`);
}

// ─────────────────────────────────────────────────────────────────────────────
// 6. THE ENHANCEMENT IS LARGE BUT FINITE INSIDE, INFINITE ONLY AT THE RIM.
//    With J(r)∝(1−(r/R)²)^(−½), the flux at any interior point exceeds the
//    centre flux by (1−(r/R)²)^(−½). At r=0.99R that is ×7.09; the singularity
//    lives only exactly on the contact line, which is why the deposit is a sharp
//    ring rather than a broad bright zone. (A clean, exact number for the page.)
// ─────────────────────────────────────────────────────────────────────────────
{
  const enh = (x) => 1 / Math.sqrt(1 - x * x);        // J(xR)/J(0)
  check('flux at r=0.99R is 7.09× the centre flux — steep, but finite off the rim',
    near(enh(0.99), 7.0888, 1e-3), `J(0.99R)/J(0) = ${enh(0.99).toFixed(3)} (= (1−0.99²)^(−½)); J(0.5R)/J(0)=${enh(0.5).toFixed(3)}`);
}

// ═══ report ══════════════════════════════════════════════════════════════════
const data = {
  disk: {
    method: 'ring-collocation solve of a charged conducting disk (Coulomb kernel + equipotential), K=600',
    capacitanceCoeff: +(4 * Math.PI * (solHi.Q / solHi.V0) / R).toFixed(4),   // → 8
    capacitanceExactCoeff: 8,
    cumulativeLaw: 'Q(r)/Q(R) = 1 − √(1 − (r/R)²)',
  },
  fluxProfile: 'J(r) ∝ (1 − (r/R)²)^(−1/2)   (thin-drop, diffusion-limited)',
  edgeFraction_outer10pctRadius: +(100 * fluxOutside(0.9)).toFixed(1),          // 43.6 %
  edgeFraction_isSqrt019: +Math.sqrt(0.19).toFixed(4),
  contactAngleExponent: {
    formula: 'λ(θ) = (π − 2θ)/(2π − 2θ)',
    'λ_0deg': +lambda(0).toFixed(4), 'λ_40deg': +lambda(40).toFixed(4),
    'λ_90deg': +lambda(90).toFixed(4), 'λ_120deg': +lambda(120).toFixed(4),
  },
  perimeterLaw: 'total evaporation rate ∝ R (capacitance), not R² (area)',
};
writeFileSync(new URL('./data.json', import.meta.url), JSON.stringify(data, null, 2));

const pass = checks.filter((c) => c.pass).length;
console.log('\n  THE RING THE COFFEE LEAVES — verification');
console.log('  ' + '─'.repeat(64));
for (const c of checks) console.log(`  ${c.pass ? '✓' : '✗'} ${c.name}\n      ${c.detail}`);
console.log('  ' + '─'.repeat(64));
console.log(`  ${pass}/${checks.length} checks green\n`);
console.log('  key numbers (all printed on the page):');
console.log(`    flux profile        J(r) ∝ (1 − (r/R)²)^(−1/2)`);
console.log(`    disk capacitance    C = 8 ε₀ R  (numeric coeff ${(4 * Math.PI * (solHi.Q / solHi.V0) / R).toFixed(4)})`);
console.log(`    edge fraction       outer 10% of radius emits ${(100 * fluxOutside(0.9)).toFixed(1)}% of vapour`);
console.log(`    contact-angle law   λ(θ)=(π−2θ)/(2π−2θ):  0°→${lambda(0).toFixed(2)}  40°→${lambda(40).toFixed(2)}  90°→${lambda(90).toFixed(2)}  120°→${lambda(120).toFixed(2)}`);
process.exit(pass === checks.length ? 0 : 1);
