#!/usr/bin/env node
// Benford's Law — the verifier behind /strata/the-first-digit-is-a-one/
//
// Every number the page shows a reader is recomputed here, headless, two ways
// where possible (BigInt-exact vs. the log-mantissa shortcut), so the page can
// never quietly drift from the arithmetic. Run: `node research/benford/verify.mjs`
//
// What it proves, in order:
//   1. The law itself: P(d) = log10(1 + 1/d) sums to 1, matches the quoted table.
//   2. Powers of two are Benford — exactly, in the limit (Weyl equidistribution),
//      cross-checked BigInt vs. log so the shortcut the page uses is sound.
//   3. Fibonacci and factorials, same.
//   4. The HONEST boundary: single-scale / uniform / assigned data is NOT Benford.
//   5. Scale invariance: a Benford set stays Benford after a unit change; a
//      non-Benford set does not become Benford — the property that makes the law
//      unique (Pinkham 1961).
//   6. The mechanism: dropping a point uniformly on the log ("mantissa") axis
//      reproduces the law — Benford <=> the fractional part of log10(x) is uniform.
//   7. The second-digit law (flatter), as a bonus check.
//
// No external data, no network: the exactly-Benford sequences (2^n, Fibonacci,
// n!) are self-contained and provable, which is why they lead the page.

const LOG10_2 = Math.log10(2);
const PHI = (1 + Math.sqrt(5)) / 2;

let PASS = 0, FAIL = 0;
const log = (...a) => console.log(...a);
function check(name, cond, detail = '') {
  if (cond) { PASS++; log(`  ✓ ${name}${detail ? '  ' + detail : ''}`); }
  else { FAIL++; log(`  ✗ ${name}  ${detail}`); }
}
function hr(t) { log('\n' + t + '\n' + '─'.repeat(t.length)); }

// ---- the law ---------------------------------------------------------------
const benford = d => Math.log10(1 + 1 / d);
const BEN = Array.from({ length: 9 }, (_, i) => benford(i + 1)); // index 0 => digit 1

// leading digit of a positive integer given as a BigInt (exact: first char)
const leadBig = b => Number(b.toString()[0]);
// leading digit from the mantissa (fractional part of log10) — the shortcut the
// page uses to reach far past what BigInt can hold: d = floor(10^{frac(log10 x)})
function leadFromLog(log10x) {
  let f = log10x - Math.floor(log10x);
  let d = Math.floor(Math.pow(10, f));
  return d === 10 ? 9 : (d < 1 ? 1 : d); // guard float edges at the [1,10) rim
}

// tally leading digits 1..9 from an iterator of leading digits
function tally(iter) {
  const c = new Array(10).fill(0); let n = 0;
  for (const d of iter) { if (d >= 1 && d <= 9) { c[d]++; n++; } }
  return { counts: c, n };
}
function fractions({ counts, n }) { return counts.slice(1).map(x => x / n); }
// total-variation distance between an observed 9-vector and Benford
function tvToBenford(fr) {
  let s = 0; for (let i = 0; i < 9; i++) s += Math.abs(fr[i] - BEN[i]); return s / 2;
}
function tvBetween(a, b) { let s = 0; for (let i = 0; i < 9; i++) s += Math.abs(a[i] - b[i]); return s / 2; }
const pct = x => (100 * x).toFixed(1).padStart(4);

// ---------------------------------------------------------------------------
hr('1. The law:  P(d) = log10(1 + 1/d)');
const table = BEN.map((p, i) => `  ${i + 1}: ${pct(p)}%`).join('');
log('  digit:  ' + table);
const quoted = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6];
const sum = BEN.reduce((a, b) => a + b, 0);
check('probabilities sum to 1', Math.abs(sum - 1) < 1e-12, `sum=${sum}`);
check('matches the quoted table (30.1 … 4.6)',
  BEN.every((p, i) => Math.abs(+(100 * p).toFixed(1) - quoted[i]) < 0.05),
  '[' + BEN.map(p => (100 * p).toFixed(1)).join(', ') + ']');
check('digit 1 is 6.6x digit 9', Math.abs(BEN[0] / BEN[8] - 6.579) < 0.01,
  `ratio=${(BEN[0] / BEN[8]).toFixed(3)}`);

// ---------------------------------------------------------------------------
hr('2. Powers of two are Benford — exactly, in the limit');
// (a) The page tallies leading digits from EXACT BigInt values, not the log
// shortcut. Here we show why: the shortcut agrees with the exact digit for all
// 10000 values EXCEPT where 10^{frac} lands on an integer (a digit-rim), where
// double-precision rounds to the wrong side. The only such case in range is
// n=3 (2^3 = 8, exactly 10^0.90309..., which floors to 7 in floating point).
let mism = 0, nonBoundary = 0, firstMism = null;
{
  let p = 1n;
  for (let n = 1; n <= 10000; n++) {
    p *= 2n;
    const exact = leadBig(p);
    const f = n * LOG10_2 - Math.floor(n * LOG10_2);
    const raw = Math.pow(10, f);
    const viaLog = leadFromLog(n * LOG10_2);
    if (exact !== viaLog) {
      mism++;
      if (!firstMism) firstMism = { n, exact, viaLog, raw };
      if (Math.abs(raw - Math.round(raw)) > 1e-9) nonBoundary++; // a genuine, non-rim disagreement
    }
  }
}
check('every log-shortcut disagreement is a digit-rim rounding (not a real error)',
  nonBoundary === 0,
  `${mism} disagreement(s), all at 10^frac≈integer; only case: n=${firstMism.n} (2^${firstMism.n}=${2 ** firstMism.n}), exact=${firstMism.exact} vs shortcut=${firstMism.viaLog}`);
check('the page therefore uses exact BigInt digits — no rim error survives', mism <= 1);
// (b) convergence to Benford as N grows
function pow2Lead(N) { return (function* () { for (let n = 1; n <= N; n++) yield leadFromLog(n * LOG10_2); })(); }
const tv2 = [100, 1000, 10000, 100000].map(N => ({ N, tv: tvToBenford(fractions(tally(pow2Lead(N)))) }));
for (const { N, tv } of tv2) log(`  N=${String(N).padStart(6)}   TV to Benford = ${tv.toFixed(4)}`);
check('TV shrinks monotonically as N grows', tv2.every((x, i) => i === 0 || x.tv <= tv2[i - 1].tv + 1e-9));
check('TV(2^n, N=100000) < 0.003', tv2[3].tv < 0.003, `TV=${tv2[3].tv.toFixed(4)}`);
const p2hist = fractions(tally(pow2Lead(100000)));
log('  2^n leading-digit census (N=100000):');
log('    ' + p2hist.map((f, i) => `${i + 1}:${pct(f)}`).join('  '));
log('    benford ' + BEN.map(f => pct(f)).join('  ').replace(/^/, ''));

// ---------------------------------------------------------------------------
hr('3. Fibonacci and factorials');
// Fibonacci: BigInt exact, cross-checked against the log form
//   leading digit of F_n = floor(10^{frac(n*log10(phi) - log10(sqrt5))})
const LOG10_PHI = Math.log10(PHI), LOG10_SQRT5 = Math.log10(Math.sqrt(5));
let fibMism = 0;
{
  let a = 1n, b = 1n; // F1=F2=1
  for (let n = 1; n <= 5000; n++) {
    const exact = leadBig(a);
    const viaLog = leadFromLog(n * LOG10_PHI - LOG10_SQRT5);
    // the closed form is only asymptotic; allow the first handful to differ
    if (n > 5 && exact !== viaLog) fibMism++;
    [a, b] = [b, a + b];
  }
}
check('Fibonacci: BigInt-exact == Binet log form (n=6..5000)', fibMism === 0, `${fibMism} mismatches`);
function fibLead(N) {
  return (function* () { let a = 1n, b = 1n; for (let n = 1; n <= N; n++) { yield leadBig(a);[a, b] = [b, a + b]; } })();
}
const tvFib = tvToBenford(fractions(tally(fibLead(10000))));
check('TV(Fibonacci, N=10000) < 0.003', tvFib < 0.003, `TV=${tvFib.toFixed(4)}`);
// Factorials n! are Benford too (Diaconis 1977) — but converge visibly slower
// than 2^n / Fibonacci, so we assert the TREND, not a tight bound at small N.
function factLead(N) {
  return (function* () { let f = 1n; for (let n = 1; n <= N; n++) { f *= BigInt(n); yield leadBig(f); } })();
}
const tvFactSeq = [500, 1000, 2000, 4000, 8000].map(N => ({ N, tv: tvToBenford(fractions(tally(factLead(N)))) }));
for (const { N, tv } of tvFactSeq) log(`  n!  N=${String(N).padStart(4)}   TV to Benford = ${tv.toFixed(4)}`);
check('n! converges to Benford (TV shrinks monotonically)',
  tvFactSeq.every((x, i) => i === 0 || x.tv < tvFactSeq[i - 1].tv));
check('n! TV(N=8000) < 0.01 — slower than 2^n, but converging', tvFactSeq[4].tv < 0.01,
  `TV=${tvFactSeq[4].tv.toFixed(4)}`);

// ---------------------------------------------------------------------------
hr('4. The honest boundary — where the law does NOT hold');
// uniform integers 1..100 (an "assigned range")
function uniformIntsLead(lo, hi) {
  return (function* () { for (let x = lo; x <= hi; x++) yield Number(String(x)[0]); })();
}
const tvUni = tvToBenford(fractions(tally(uniformIntsLead(1, 100))));
check('uniform ints 1..100 are NOT Benford (TV large)', tvUni > 0.12, `TV=${tvUni.toFixed(4)}`);
// single-scale "heights": 150..199 cm — everything leads with 1
const tvHeights = tvToBenford(fractions(tally(uniformIntsLead(150, 199))));
check('single-scale heights (150..199) are NOT Benford', tvHeights > 0.5, `TV=${tvHeights.toFixed(4)} (digit 1 ~100%)`);
// uniform reals on [1,10): leading digit d with prob 1/9 each
{
  const c = new Array(10).fill(0); const M = 900000;
  for (let i = 0; i < M; i++) { const x = 1 + 9 * (i + 0.5) / M; c[Math.floor(x)]++; }
  const fr = c.slice(1).map(x => x / M);
  const tvU = tvToBenford(fr);
  check('uniform reals on [1,10) are NOT Benford (~11.1% each)', tvU > 0.15,
    `TV=${tvU.toFixed(4)}, each~${pct(fr[0])}%`);
}

// ---------------------------------------------------------------------------
hr('5. Scale invariance (Pinkham 1961) — the property that makes Benford unique');
// A Benford set stays Benford after ANY unit change (multiply by a constant).
function scaledPow2Lead(N, c) {
  const lc = Math.log10(c);
  return (function* () { for (let n = 1; n <= N; n++) yield leadFromLog(n * LOG10_2 + lc); })();
}
for (const c of [7, Math.PI, 1 / 3, 2.20462]) { // incl. kg->lb
  const fr = fractions(tally(scaledPow2Lead(100000, c)));
  const tv = tvToBenford(fr);
  check(`2^n rescaled by ${c.toFixed(4)} is still Benford`, tv < 0.004, `TV=${tv.toFixed(4)}`);
}
// A NON-Benford set does not become Benford under rescaling, and its shape moves.
{
  const base = fractions(tally(uniformIntsLead(1, 100)));
  const scaled = (function () {
    const c = new Array(10).fill(0); let n = 0;
    for (let x = 1; x <= 100; x++) { const v = x * 3.7; c[Number(String(v.toFixed(4).replace('.', ''))[0])]++; n++; }
    return c.slice(1).map(v => v / n);
  })();
  const moved = tvBetween(base, scaled);
  const stillNot = tvToBenford(scaled);
  check('a non-Benford set is not scale-stable (its shape shifts)', moved > 0.02, `shift TV=${moved.toFixed(4)}`);
  check('...and rescaling does not rescue it to Benford', stillNot > 0.05, `TV=${stillNot.toFixed(4)}`);
}

// ---------------------------------------------------------------------------
hr('6. The mechanism — Benford <=> the mantissa (frac of log10) is uniform');
// Drop points uniformly on the log axis [0,1); tally which digit band they fall in.
// Band for digit d is [log10(d), log10(d+1)); its width IS log10(1+1/d).
{
  const c = new Array(10).fill(0); const M = 1000000;
  for (let i = 0; i < M; i++) {
    const f = (i + 0.5) / M;            // uniform mantissa
    c[leadFromLog(f)]++;
  }
  const fr = c.slice(1).map(x => x / M);
  const tv = tvToBenford(fr);
  check('uniform mantissa reproduces Benford exactly', tv < 0.001, `TV=${tv.toFixed(5)}`);
}

// ---------------------------------------------------------------------------
hr('7. Bonus — the second-digit law (flatter than the first)');
// P(second digit = d) = sum_{k=1}^{9} log10(1 + 1/(10k + d)), d = 0..9
const secondLaw = Array.from({ length: 10 }, (_, d) => {
  let s = 0; for (let k = 1; k <= 9; k++) s += Math.log10(1 + 1 / (10 * k + d)); return s;
});
log('  second digit:  ' + secondLaw.map((p, d) => `${d}:${pct(p)}`).join('  '));
check('second-digit probabilities sum to 1', Math.abs(secondLaw.reduce((a, b) => a + b, 0) - 1) < 1e-12);
check('second digit is flatter (0 ~ 12.0%, 9 ~ 8.5%)',
  Math.abs(secondLaw[0] - 0.11968) < 1e-3 && Math.abs(secondLaw[9] - 0.08499) < 1e-3,
  `P(0)=${pct(secondLaw[0])}% P(9)=${pct(secondLaw[9])}%`);
// cross-check against 2^n second digits
{
  const c = new Array(10).fill(0); let n = 0;
  let p = 1n;
  for (let k = 1; k <= 20000; k++) {
    p *= 2n; const s = p.toString();
    if (s.length >= 2) { c[Number(s[1])]++; n++; }
  }
  const fr = c.map(x => x / n);
  let tv = 0; for (let d = 0; d < 10; d++) tv += Math.abs(fr[d] - secondLaw[d]); tv /= 2;
  check('2^n second digits match the second-digit law', tv < 0.01, `TV=${tv.toFixed(4)}`);
}

// ---------------------------------------------------------------------------
hr(`RESULT: ${PASS} passed, ${FAIL} failed`);
if (FAIL) process.exit(1);
