#!/usr/bin/env node
// verify.mjs — The Charge That Crept (P1, the Verification Venue, method-error mode)
//
// Re-derives, from scratch, every number the page states or draws:
//   §1  the modern exact e and its esu conversion
//   §2  the oil-drop physics: q ∝ η^(3/2) at fixed observed velocities
//       (so a −0.5% viscosity error → a −0.75% charge error, the size of Millikan's miss)
//   §3  the viscosity correction arithmetic (Millikan's η vs the moderns, what it closes)
//   §4  the historical series of recommended values (data.mjs): every conversion,
//       every σ-deviation the chart shows, and the creep-shape claims the prose makes
//   §5  the anchoring toy model: closed form E[p_n] − T = w^n (p_0 − T) vs Monte Carlo
//
// Data + citations live in data.mjs; the page reads the same file. Run: node verify.mjs
import { SERIES, MILLIKAN, VISCOSITY, MODERN } from './data.mjs';

let n = 0, pass = 0;
function check(name, ok, detail = '') {
  n++;
  if (ok) { pass++; console.log(`  ok ${String(n).padStart(2)} — ${name}${detail ? '  [' + detail + ']' : ''}`); }
  else { console.error(`FAIL ${String(n).padStart(2)} — ${name}${detail ? '  [' + detail + ']' : ''}`); }
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('§1 the modern value and the unit bridge');
{
  // 2019 SI: e ≡ 1.602176634e-19 C exactly (by definition of the coulomb).
  // esu bridge: 1 C = 10·c statC with c in cm/s → 2 997 924 580 statC exactly.
  const eC = MODERN.e_coulomb;                    // 1.602176634e-19, exact
  const statC_per_C = MODERN.c_cm_s / 10;         // 2.99792458e10/10
  check('statC per coulomb = 2 997 924 580 (exact, from the exact c)',
    statC_per_C === 2997924580);
  const e_esu = eC * statC_per_C;                 // in esu (statcoulomb)
  check('e = 4.80320471e-10 esu (page & chart baseline)',
    close(e_esu / 1e-10, MODERN.e_esu_e10, 5e-8), (e_esu / 1e-10).toFixed(8));
}

console.log('§2 the oil-drop dependence: q ∝ η^(3/2)');
{
  // Stokes fall: (4/3)πa³Δρg = 6πηa·v1  →  a = sqrt(9ηv1 / (2gΔρ))
  // Balance with field: qE = 6πηa(v1+v2)  →  q = 6π η a (v1+v2)/E ∝ η^(3/2).
  const g = 980.665, drho = 0.9, E = 10;
  const q = (eta, v1, v2) => {
    const a = Math.sqrt(9 * eta * v1 / (2 * g * drho));
    return 6 * Math.PI * eta * a * (v1 + v2) / E;
  };
  // the exponent, measured from the formula itself over a decade of η:
  const [q1, q2] = [q(1e-4, .05, .03), q(1e-3, .05, .03)];
  const measuredExp = Math.log(q2 / q1) / Math.log(10);
  check('exponent of η in q, measured from the Stokes construction = 3/2',
    close(measuredExp, 1.5, 1e-12), measuredExp.toFixed(12));
  // sensitivity: a fractional viscosity error δ produces (1+δ)^1.5−1 ≈ 1.5δ in q
  const d = VISCOSITY.millikan_frac_low;          // how low Millikan's η was (fractional)
  check('a viscosity −' + (100 * d).toFixed(2) + '% ⇒ charge −' + (100 * (1 - Math.pow(1 - d, 1.5))).toFixed(2) + '% (≈1.5×)',
    close(1 - Math.pow(1 - d, 1.5), 1.5 * d, 0.02 * d));
}

console.log('§3 the viscosity correction arithmetic (facts.md pillar B)');
{
  // Kellström's recompute of Millikan's own data with the re-measured viscosity is
  // reported by secondary sources as 4.816–4.818 (±0.011–0.013); no canonical single
  // figure (facts B1). Our arithmetic from the two η's and the 3/2 power:
  const eCorr = MILLIKAN.value_esu * Math.pow(VISCOSITY.kellstrom_e4 / VISCOSITY.millikan_e4, 1.5);
  check('4.774 × (1.8348/1.8240)^{3/2} lands inside the reported 4.815–4.819 band',
    eCorr > VISCOSITY.kellstrom_e_lo && eCorr < VISCOSITY.kellstrom_e_hi, eCorr.toFixed(4));
  // the corrected value OVERSHOOTS the modern exact value by about one quoted error
  // (~0.013) — the page states this as "roughly one quoted error above":
  const over = (eCorr - MODERN.e_esu_e10) / 0.013;
  check('the viscosity-only correction overshoots the modern value by ~1 quoted error',
    over > 0.7 && over < 1.4, over.toFixed(2) + '×');
  // Millikan's η vs the modern interpolated figure: ~0.6% low
  const fracLow = (VISCOSITY.modern_e4 - VISCOSITY.millikan_e4) / VISCOSITY.modern_e4;
  check('Millikan’s η is ~0.60% below the modern 23 °C figure (as data.mjs states)',
    close(fracLow, VISCOSITY.millikan_frac_low, 0.0005), (100 * fracLow).toFixed(2) + '%');
  // and Kellström's η sits inside the modern band (±0.3% spread)
  check('Kellström’s 1.8348 sits within 0.3% of the modern 1.835',
    Math.abs(VISCOSITY.kellstrom_e4 - VISCOSITY.modern_e4) / VISCOSITY.modern_e4 < 0.003);
}

console.log('§4 the size of the miss');
{
  const missFrac = (MODERN.e_esu_e10 - MILLIKAN.value_esu) / MODERN.e_esu_e10;
  check('Millikan’s 4.774 sits 0.61% below the exact value', close(missFrac, 0.0061, 0.0002),
    (100 * missFrac).toFixed(3) + '%');
  const sig1913 = (MODERN.e_esu_e10 - MILLIKAN.value_esu) / MILLIKAN.err_esu;
  check('the miss is 3.2× his quoted ±0.009', close(sig1913, 3.2, 0.1), sig1913.toFixed(2) + '×');
  const sig1917 = (MODERN.e_esu_e10 - MILLIKAN.value_esu) / MILLIKAN.err_esu_1917;
  check('and 5.8× the ±0.005 of his later statements', close(sig1917, 5.8, 0.1), sig1917.toFixed(2) + '×');
  // his own 1911→1913 revision moved DOWN (4.891 → 4.774), away from the eventual value:
  check('his own 1911→1913 revision moved down, 4.891 → 4.774',
    MILLIKAN.value_esu_1911 > MILLIKAN.value_esu);
}

console.log('§4b the historical series (data.mjs ↔ chart ↔ prose)');
{
  // every carried C-value converts to the esu value at the exact bridge
  // (pre-SI rounding in the compilation ≤ 0.002 in the 4th decimal, so tol 2e-3)
  let convOk = true;
  for (const p of SERIES) if (p.value_C != null) {
    if (!close(p.value_C * 2.99792458, p.value_esu, 2e-3)) { convOk = false; console.error('   conv drift:', p.year, p.source); }
    if (p.err_C != null && p.err_esu > 0 && !close(p.err_C * 2.99792458, p.err_esu, 2e-4)) { convOk = false; console.error('   err drift:', p.year, p.source); }
  }
  check('every carried coulomb value converts to its esu value at 2.99792458 (≤2e-3 rounding)', convOk);

  const by = (y, src) => SERIES.find(p => p.year === y && (!src || p.source.startsWith(src)));
  const dev = p => (MODERN.e_esu_e10 - p.value_esu) / p.err_esu; // + = point sits below truth
  // the σ-deviations the chart's detail panel and the prose state:
  check('1913 Millikan sits +3.2 of his quoted limits below the truth', close(dev(by(1913)), 3.2, 0.1), dev(by(1913)).toFixed(2));
  check('1929 Birge review sits +6.6 quoted probable errors below', close(dev(by(1929, 'Birge')), 6.6, 0.1), dev(by(1929, 'Birge')).toFixed(2));
  check('Dec-1950 adjustment sits ~+14 of its own quoted probable errors below', close(dev(by(1950)), 13.9, 0.2), dev(by(1950)).toFixed(2));
  check('1969 TPL sits −2.2 (ABOVE the truth — the overshoot)', close(dev(by(1969)), -2.2, 0.1), dev(by(1969)).toFixed(2));
  check('2006 CODATA still 3.7 of its own standard uncertainties off', close(Math.abs(dev(by(2006))), 3.7, 0.15), dev(by(2006)).toFixed(2));

  // the shape claims in the prose:
  check('Birge 1929 recommended BELOW Millikan 1913 (the anchor pulled from both sides)',
    by(1929, 'Birge').value_esu < by(1913).value_esu);
  check('Bearden 1931 X-ray already ABOVE the 2019 exact value (the jump)',
    by(1931).value_esu > MODERN.e_esu_e10);
  check('the two 1936 oil-drop values straddle Millikan (Kellström high, Bäcklin–Flemberg low)',
    by(1936, 'Kellström').value_esu > MODERN.e_esu_e10 && by(1936, 'Bäcklin & Flemberg').value_esu < by(1913).value_esu);
  const reviews = SERIES.filter(p => p.cls === 'review');
  check('every recommended value 1929–1963 sits BELOW the 2019 exact value',
    reviews.filter(p => p.year <= 1963).every(p => p.value_esu < MODERN.e_esu_e10));
  let nonMono = false;
  for (let i = 1; i < reviews.length; i++) if (reviews[i].value_esu < reviews[i - 1].value_esu) nonMono = true;
  check('the review series is NOT a monotone staircase (it overshoots and dips)', nonMono);
  check('yet the 1929→1973 recommended trend is upward overall',
    reviews[0].value_esu < reviews.filter(p => p.year <= 1973).slice(-1)[0].value_esu);
  // Kellström's recomputed-e spread band contains our own arithmetic AND the modern value
  const eCorr2 = MILLIKAN.value_esu * Math.pow(VISCOSITY.kellstrom_e4 / VISCOSITY.millikan_e4, 1.5);
  check('our viscosity arithmetic (4.8165) falls inside the reported Kellström band 4.815–4.819',
    eCorr2 > VISCOSITY.kellstrom_e_lo && eCorr2 < VISCOSITY.kellstrom_e_hi, eCorr2.toFixed(4));
}

console.log('§6 the page embeds exactly this data (drift guard)');
{
  const { readFileSync, existsSync } = await import('node:fs');
  const { fileURLToPath } = await import('node:url');
  const { dirname, join } = await import('node:path');
  const here = dirname(fileURLToPath(import.meta.url));
  const pagePath = join(here, '..', '..', 'public', 'strata', 'the-charge-that-crept', 'index.html');
  if (existsSync(pagePath)) {
    const html = readFileSync(pagePath, 'utf8');
    const m = html.match(/<script id="series-data" type="application\/json">([\s\S]*?)<\/script>/);
    let ok = false;
    if (m) {
      try {
        const embedded = JSON.parse(m[1]);
        ok = JSON.stringify(embedded.series) === JSON.stringify(SERIES)
          && JSON.stringify(embedded.modern) === JSON.stringify(MODERN)
          && JSON.stringify(embedded.millikan) === JSON.stringify(MILLIKAN)
          && JSON.stringify(embedded.viscosity) === JSON.stringify(VISCOSITY);
      } catch { ok = false; }
    }
    check('the page’s inlined JSON is byte-identical to data.mjs (series, modern, millikan, viscosity)', ok);
  } else {
    check('page exists for drift check', false, 'index.html not found');
  }
}

console.log('§5 the anchoring toy model (declared model, not history)');
{
  // p_i = (1−w)(T+ε_i) + w·p_{i−1};  E[p_n] − T = wⁿ(p_0 − T)  (ε zero-mean)
  const T = 0, p0 = -1, w = 0.7, N = 12, RUNS = 200000, sigma = 0.3;
  // mulberry32 — deterministic
  let s = 0x51ED;
  const rnd = () => { s |= 0; s = s + 0x6D2B79F5 | 0; let t = Math.imul(s ^ s >>> 15, 1 | s); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
  const gauss = () => Math.sqrt(-2 * Math.log(1 - rnd())) * Math.cos(2 * Math.PI * rnd());
  const sum = new Array(N + 1).fill(0);
  for (let r = 0; r < RUNS; r++) {
    let p = p0;
    for (let i = 1; i <= N; i++) { p = (1 - w) * (T + sigma * gauss()) + w * p; sum[i] += p; }
  }
  let allOk = true;
  for (let i = 1; i <= N; i++) {
    const mc = sum[i] / RUNS, cf = Math.pow(w, i) * (p0 - T);
    if (!close(mc, cf, 6 * sigma * (1 - w) / Math.sqrt(RUNS) * Math.sqrt(i) + 1e-3)) allOk = false;
  }
  check(`closed form E[p_n]−T = wⁿ(p₀−T) matches ${RUNS.toLocaleString()} Monte-Carlo chains at every n ≤ ${N}`, allOk);
  // and the "independent" limit: w = 0 recovers unbiased measurement immediately
  check('w = 0 (no deference) ⇒ bias gone in one step (closed form)', Math.pow(0, 1) * (p0 - T) === 0);
}

console.log(`\n${pass}/${n} checks pass`);
if (pass !== n) process.exit(1);
