#!/usr/bin/env node
// Offline verifier for the stratum "Benford's Law: One Leads Most Often".
//
// It reproduces, from first principles and from the committed data snapshots, every
// load-bearing number the immersive page shows:
//   1. the law itself, P(d) = log10(1 + 1/d), and its consequences;
//   2. four real datasets' leading-digit distributions + conformity (chi-square, MAD);
//   3. three deterministic sequences whose leading digits are PROVABLY Benford
//      (powers of 2, Fibonacci, factorials), via exact BigInt arithmetic — no floats;
//   4. the scale-invariance fact (the whole reason the law exists) and base invariance.
//
// Run:  node research/the-first-digit/verify.mjs
// Data: research/the-first-digit/data/*.json  (World Bank, CC-BY 4.0; NIST CODATA, public domain)
//
// Every assertion is checked to a stated tolerance; the run prints "PASS n/n" or throws.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const DATA = path.join(HERE, 'data');

let pass = 0, total = 0;
const log = [];
function check(name, cond, detail = '') {
  total++;
  if (cond) { pass++; log.push(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { log.push(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); throw new Error('CHECK FAILED: ' + name + ' :: ' + detail); }
}
const near = (a, b, eps) => Math.abs(a - b) <= eps;

// ── helpers ──────────────────────────────────────────────────────────────────
const log10 = (x) => Math.log(x) / Math.LN10;
// Benford probability of leading digit d (1..9)
const benford = (d) => log10(1 + 1 / d);
const BENFORD = Array.from({ length: 9 }, (_, i) => benford(i + 1));

// leading (first significant) decimal digit of a positive real
function leadFloat(x) {
  let s = Math.abs(x);
  if (s === 0) return 0;
  while (s >= 10) s /= 10;
  while (s < 1) s *= 10;
  return Math.floor(s);
}
// leading digit of a positive BigInt — exact, just the first character
const leadBig = (n) => Number(n.toString()[0]);

// histogram of leading digits 1..9 for an array of numbers (floats)
function histFloat(arr) {
  const h = Array(10).fill(0);
  for (const v of arr) { const d = leadFloat(v); if (d >= 1) h[d]++; }
  return h.slice(1);
}
// counts (length 9) -> proportions
const props = (h) => { const n = h.reduce((a, b) => a + b, 0); return h.map((c) => c / n); };
// Pearson chi-square of observed counts vs Benford, with df = 8
function chiSquare(h) {
  const n = h.reduce((a, b) => a + b, 0);
  let x = 0;
  for (let i = 0; i < 9; i++) { const e = n * BENFORD[i]; x += (h[i] - e) ** 2 / e; }
  return x;
}
// Nigrini's mean absolute deviation (a standard Benford-conformity metric)
function mad(h) {
  const p = props(h);
  let s = 0; for (let i = 0; i < 9; i++) s += Math.abs(p[i] - BENFORD[i]);
  return s / 9;
}
// total-variation distance between two distributions of length 9
const tvd = (p, q) => 0.5 * p.reduce((a, _, i) => a + Math.abs(p[i] - q[i]), 0);

console.log('\nBenford\'s Law: One Leads Most Often - offline verification\n');

// ── 1 · the law itself ───────────────────────────────────────────────────────
// canonical percentages every textbook prints
const PCT = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6];
for (let d = 1; d <= 9; d++) {
  check(`law P(${d}) = log10(1+1/${d}) ≈ ${PCT[d - 1]}%`,
    near(BENFORD[d - 1] * 100, PCT[d - 1], 0.06),
    `${(BENFORD[d - 1] * 100).toFixed(2)}%`);
}
check('law sums to 1 (telescoping log10 of 10/1)',
  near(BENFORD.reduce((a, b) => a + b, 0), 1, 1e-12),
  BENFORD.reduce((a, b) => a + b, 0).toFixed(15));
check('digit 1 occurs EXACTLY as often as digits 5–9 combined (both = log10 2)',
  near(BENFORD[0], BENFORD.slice(4).reduce((a, b) => a + b, 0), 1e-12) && near(BENFORD[0], log10(2), 1e-12),
  `P(1)=P(5..9)=log10(2)=${(BENFORD[0] * 100).toFixed(4)}%`);
check('law is strictly decreasing in d', BENFORD.every((v, i) => i === 0 || v < BENFORD[i - 1]), 'monotone');
// generalized leading two digits: P(first two = "10") etc. P(d) for two-digit = log10(1+1/dd)
check('two-digit form: P(first two digits = 10) = log10(1+1/10)',
  near(log10(1 + 1 / 10) * 100, 4.139, 1e-3), `${(log10(1 + 1 / 10) * 100).toFixed(3)}%`);

// ── 2 · real datasets ────────────────────────────────────────────────────────
function loadVals(file, key = 'value') {
  const rows = JSON.parse(fs.readFileSync(path.join(DATA, file), 'utf8'));
  return rows.map((r) => Math.abs(typeof r === 'number' ? r : r[key])).filter((v) => v > 0);
}
// Each dataset carries its own HONEST expectation. The three socioeconomic sets
// conform tightly; physical constants are the famous loose fit (Benford is not a law
// of nature) — we assert only the shape there, and let chi-square report the truth.
const datasets = [
  { label: 'country populations 2022 (World Bank, CC-BY)', vals: loadVals('population-2022.json'), tightP1: true, conforms05: true },
  { label: 'country surface areas km² 2022 (World Bank)', vals: loadVals('surface-area-2022.json'), tightP1: true, conforms05: true },
  { label: 'national GDP USD 2022 (World Bank)', vals: loadVals('gdp-usd-2022.json'), tightP1: true, conforms05: true },
  { label: 'physical constants (NIST CODATA, public domain)', vals: loadVals('codata-constants.json'), tightP1: false, conforms05: true },
];
// chi-square critical value, df=8: alpha=0.05 -> 15.51; alpha=0.01 -> 20.09
const CHI_05 = 15.507, CHI_01 = 20.090;
for (const { label, vals, tightP1, conforms05 } of datasets) {
  const h = histFloat(vals);
  const n = h.reduce((a, b) => a + b, 0);
  const x2 = chiSquare(h);
  const m = mad(h);
  const orders = log10(Math.max(...vals)) - log10(Math.min(...vals));
  check(`${label}: digit 1 is the plurality`,
    h[0] === Math.max(...h), `counts ${h.join(' ')} (n=${n})`);
  check(`${label}: P(1) ${tightP1 ? 'within 5 pts of' : 'elevated above (loose fit,'} Benford's 30.1%${tightP1 ? '' : ')'}`,
    tightP1 ? Math.abs(props(h)[0] - BENFORD[0]) < 0.05 : props(h)[0] >= BENFORD[0],
    `P(1)=${(props(h)[0] * 100).toFixed(1)}%`);
  check(`${label}: chi² ${conforms05 ? 'conforms @5% (< 15.51)' : 'does NOT conform @5% (≥ 15.51) — the honest loose fit'}`,
    conforms05 ? x2 < CHI_05 : x2 >= CHI_05,
    `chi²=${x2.toFixed(2)}`);
  check(`${label}: spans ≥ 3 orders of magnitude`,
    orders >= 3, `${orders.toFixed(1)} decades`);
  log.push(`       (chi²=${x2.toFixed(2)}  ${x2 < CHI_05 ? '< 15.51, conforms @5%' : x2 < CHI_01 ? '∈[15.51,20.09), conforms @1% only' : '≥ 20.09, does NOT conform'};  MAD=${m.toFixed(4)})`);
}

// ── 3 · deterministic sequences — PROVABLY Benford, exact BigInt ──────────────
// 3a · powers of two: leading digit of 2^n follows Benford because {n·log10 2} is
//      equidistributed mod 1 (Weyl, log10 2 irrational). Exact via BigInt strings.
function seqHist(next, N, x0) {
  const h = Array(10).fill(0);
  let x = x0;
  for (let i = 0; i < N; i++) { h[leadBig(x)]++; x = next(x); }
  return h.slice(1);
}
{
  const N = 20000;
  const h = seqHist((x) => x * 2n, N, 1n);
  const t = tvd(props(h), BENFORD);
  check('powers of two (2^0..2^19999): leading digits within TVD 0.01 of Benford',
    t < 0.01, `TVD=${t.toFixed(4)}, counts ${h.join(' ')}`);
  check('powers of two: P(1) ≈ 30.1% (exact BigInt count)',
    Math.abs(props(h)[0] - BENFORD[0]) < 0.01, `P(1)=${(props(h)[0] * 100).toFixed(2)}%`);
}
// 3b · Fibonacci numbers — log10 φ irrational, so also Benford
{
  const N = 20000;
  const h = Array(10).fill(0);
  let a = 1n, b = 1n;
  for (let i = 0; i < N; i++) { h[leadBig(a)]++; [a, b] = [b, a + b]; }
  const hh = h.slice(1);
  const t = tvd(props(hh), BENFORD);
  check('Fibonacci (F_1..F_20000): leading digits within TVD 0.01 of Benford',
    t < 0.01, `TVD=${t.toFixed(4)}`);
}
// 3c · factorials — proven Benford (Diaconis 1977)
{
  const N = 5000;
  const h = Array(10).fill(0);
  let f = 1n;
  for (let i = 1; i <= N; i++) { f *= BigInt(i); h[leadBig(f)]++; }
  const hh = h.slice(1);
  const t = tvd(props(hh), BENFORD);
  check('factorials (1!..5000!): leading digits within TVD 0.02 of Benford',
    t < 0.02, `TVD=${t.toFixed(4)}`);
}
// 3d · a NON-example: leading digit of n itself (1..N) is NOT Benford — it oscillates.
{
  const N = 9999;
  const h = Array(10).fill(0);
  for (let n = 1; n <= N; n++) h[leadBig(BigInt(n))]++;
  const hh = h.slice(1);
  // 1..9999: each digit is leading equally often -> ~ uniform, NOT Benford
  check('control: leading digit of 1..9999 is ~uniform (NOT Benford)',
    Math.abs(props(hh)[0] - 1 / 9) < 0.02 && tvd(props(hh), BENFORD) > 0.15,
    `P(1)=${(props(hh)[0] * 100).toFixed(1)}%, TVD-to-Benford=${tvd(props(hh), BENFORD).toFixed(3)}`);
}

// ── 4 · scale invariance (the engine of the law) ─────────────────────────────
// Equidistribution picture: on the log-scale circle [0,1), leading digit = d exactly
// when frac(log10 x) ∈ [log10 d, log10(d+1)); that arc has length log10(1+1/d) = P(d).
for (let d = 1; d <= 9; d++) {
  const arc = log10(d + 1) - log10(d);
  check(`log-circle arc for digit ${d} has length log10(1+1/${d})`,
    near(arc, BENFORD[d - 1], 1e-12));
}
// Multiplying every value by a constant c rotates the log-circle by frac(log10 c).
// For a log-uniform (Benford) population the digit law is therefore INVARIANT under
// scaling. Demonstrate numerically with a large log-uniform sample, scaled by wild c.
{
  // deterministic log-uniform sample on [1,10^6): x = 10^(i/M)
  const M = 200000;
  const base = Array.from({ length: M }, (_, i) => Math.pow(10, (i / M) * 6));
  const h0 = props(histFloat(base));
  check('log-uniform sample already obeys Benford (TVD < 0.005)',
    tvd(h0, BENFORD) < 0.005, `TVD=${tvd(h0, BENFORD).toFixed(4)}`);
  for (const c of [2, 3, 7, 137.035, 0.001, Math.PI]) {
    const hc = props(histFloat(base.map((x) => x * c)));
    check(`scale-invariance: ×${c} leaves the leading-digit law within TVD 0.01`,
      tvd(hc, BENFORD) < 0.01 && tvd(hc, h0) < 0.01,
      `TVD-to-Benford=${tvd(hc, BENFORD).toFixed(4)}`);
  }
}
// Base invariance: in base b the law is log_b(1+1/d). In base 2 the only leading
// digit is 1, with probability log2(2)=1 — the law's degenerate but consistent edge.
{
  const logb = (x, b) => Math.log(x) / Math.log(b);
  // base 16: P(d=1) = log16(2) = 0.25
  check('base invariance: in hex, P(leading digit = 1) = log16(2) = 0.25',
    near(logb(2, 16), 0.25, 1e-12), `${logb(2, 16).toFixed(6)}`);
  // base-b law sums to 1 for b=16
  let s = 0; for (let d = 1; d < 16; d++) s += logb(1 + 1 / d, 16);
  check('base-16 leading-digit law sums to 1', near(s, 1, 1e-12), s.toFixed(15));
}

// ── report ───────────────────────────────────────────────────────────────────
console.log(log.join('\n'));
console.log(`\n${pass === total ? 'PASS' : 'INCOMPLETE'} ${pass}/${total} checks\n`);
if (pass !== total) process.exit(1);
