#!/usr/bin/env node
// research/the-coin-you-cant-fake/verify.mjs
//
// The check behind "The Coin You Can't Fake"
// (public/strata/the-coin-you-cant-fake/index.html) — the claim that a few
// simple statistics separate a HUMAN-invented "random" coin sequence from a
// REAL fair coin, and that every number the page states is exact.
//
// The page runs three detectors live in the browser. This file proves the
// statistical facts those detectors rest on, each by two INDEPENDENT methods:
//
//   (A) EXACT closed-form / dynamic programming
//   (B) SEEDED MONTE-CARLO simulation of a real fair coin
//
// If the exact math and a genuinely random sampler ever disagree beyond the
// stated tolerance, a number on the page would be a lie — so this file fails
// loudly. Deterministic (seeded PRNG). Run:  node verify.mjs
'use strict';

// ---------------------------------------------------------------------------
// A well-distributed, deterministic PRNG (mulberry32) standing in for a real
// fair coin. We are NOT claiming this is cryptographically random — only that
// it is a genuine, unbiased, memory-less bit source, which is exactly the null
// model ("a real coin") the page tests a human against. The browser page uses
// crypto.getRandomValues for its live "real coin"; here we seed for
// reproducibility so the verifier's numbers never move.
// ---------------------------------------------------------------------------
function mulberry32(seed) {
  let a = seed >>> 0;
  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;
  };
}

// ---------------------------------------------------------------------------
// EXACT distribution of the LONGEST RUN of identical symbols in n fair flips.
//
// dp[j] = probability that the first i flips end in a current run of length j,
// AND no run so far has exceeded m. State j runs 1..m. Each new flip either
// extends the current run (prob 1/2) or switches symbol and starts a run of 1
// (prob 1/2). If a run would exceed m, that path is dropped — it is exactly the
// event "longest run > m". So sum(dp) after n flips = P(longest run <= m).
// This is exact arithmetic, no sampling.
// ---------------------------------------------------------------------------
function pLongestRunAtMost(n, m) {
  if (m < 1) return 0;
  if (n === 0) return 1;
  let dp = new Array(m + 1).fill(0);
  dp[1] = 1; // after the first flip: a run of length 1, with certainty
  for (let i = 2; i <= n; i++) {
    const nd = new Array(m + 1).fill(0);
    let switchMass = 0;
    for (let j = 1; j <= m; j++) switchMass += dp[j]; // any state can switch -> run 1
    nd[1] = 0.5 * switchMass;
    for (let j = 1; j < m; j++) nd[j + 1] = 0.5 * dp[j]; // extend (j==m would exceed -> dropped)
    dp = nd;
  }
  return dp.reduce((s, x) => s + x, 0);
}

// Full PMF of the longest run for n flips, plus its mean, from the exact CDF.
function longestRunStats(n) {
  const cdf = []; // cdf[m] = P(L <= m), m = 0..n
  cdf[0] = 0;
  for (let m = 1; m <= n; m++) cdf[m] = pLongestRunAtMost(n, m);
  const pmf = [];
  for (let m = 1; m <= n; m++) pmf[m] = cdf[m] - cdf[m - 1];
  let mean = 0;
  for (let m = 1; m <= n; m++) mean += m * pmf[m];
  // median = smallest m with cdf >= 0.5
  let median = n;
  for (let m = 1; m <= n; m++) { if (cdf[m] >= 0.5) { median = m; break; } }
  // mode = argmax pmf
  let mode = 1, best = -1;
  for (let m = 1; m <= n; m++) { if (pmf[m] > best) { best = pmf[m]; mode = m; } }
  return { cdf, pmf, mean, median, mode };
}

// ---------------------------------------------------------------------------
// SIMULATION: draw a real fair coin sequence and measure the three tells the
// page reports. Returns { L: longest run, R: number of runs, switches, heads }.
// ---------------------------------------------------------------------------
function measure(seq) {
  const n = seq.length;
  let L = 1, cur = 1, R = 1, switches = 0, heads = 0;
  if (seq[0]) heads++;
  for (let i = 1; i < n; i++) {
    if (seq[i]) heads++;
    if (seq[i] === seq[i - 1]) { cur++; if (cur > L) L = cur; }
    else { cur = 1; R++; switches++; }
  }
  return { L, R, switches, heads };
}
function realCoin(n, rand) {
  const s = new Array(n);
  for (let i = 0; i < n; i++) s[i] = rand() < 0.5 ? 1 : 0;
  return s;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const f2 = (x) => x.toFixed(2);
const f3 = (x) => x.toFixed(3);
const pct = (x) => (100 * x).toFixed(2) + '%';
let failures = 0;
function check(name, cond, detail) {
  const tag = cond ? 'PASS' : 'FAIL';
  if (!cond) failures++;
  console.log(`  [${tag}] ${name}${detail ? '  —  ' + detail : ''}`);
}

console.log('THE COIN YOU CAN\'T FAKE — verifier\n');
console.log('Null model: a real fair coin (unbiased, memory-less). Everything below');
console.log('is what such a coin does — the yardstick a human is measured against.\n');

const N = 100;               // the page's default sequence length
const TRIALS = 4_000_000;    // Monte-Carlo sample size
const rand = mulberry32(0xC0FFEE01);

// ===========================================================================
// 1. LONGEST RUN — exact DP vs. a 4-million-coin simulation must agree.
// ===========================================================================
console.log(`LONGEST STREAK in n=${N} fair flips (the headline tell):`);
const lr = longestRunStats(N);

// Monte-Carlo the same quantity independently.
let simMeanL = 0;
const simCountLle = new Array(N + 2).fill(0); // simCountLle[m] = # trials with L <= m
let simGE6 = 0, simLE3 = 0;
for (let t = 0; t < TRIALS; t++) {
  const { L } = measure(realCoin(N, rand));
  simMeanL += L;
  for (let m = L; m <= N + 1; m++) simCountLle[m]++;
  if (L >= 6) simGE6++;
  if (L <= 3) simLE3++;
}
simMeanL /= TRIALS;

console.log(`  exact:  mean = ${f3(lr.mean)}   median = ${lr.median}   mode = ${lr.mode}`);
console.log(`  sim :   mean = ${f3(simMeanL)}   (${(TRIALS/1e6).toFixed(0)}M coins)`);
check('exact longest-run mean  ≡  simulation', Math.abs(lr.mean - simMeanL) < 0.01,
  `|exact - sim| = ${(Math.abs(lr.mean - simMeanL)).toExponential(2)}`);

const exactGE6 = 1 - lr.cdf[5];   // P(L >= 6) = 1 - P(L <= 5)
const exactLE3 = lr.cdf[3];       // P(L <= 3)
check('P(longest streak ≥ 6): exact ≡ sim', Math.abs(exactGE6 - simGE6 / TRIALS) < 3e-3,
  `exact ${pct(exactGE6)}  vs sim ${pct(simGE6 / TRIALS)}`);
check('P(longest streak ≤ 3): exact ≡ sim', Math.abs(exactLE3 - simLE3 / TRIALS) < 3e-3,
  `exact ${pct(exactLE3)}  vs sim ${pct(simLE3 / TRIALS)}`);

console.log(`  THE SHOWING: a real coin's longest streak is ≥ 6 about ${pct(exactGE6)} of the time,`);
console.log(`               yet 3 or shorter only about ${pct(exactLE3)} of the time.`);
console.log(`               Humans almost always hand back a longest streak of 3 or 4 — the tail`);
console.log(`               a real coin lives in, humans vacate.\n`);

// The exact PMF the page can quote directly.
console.log('  exact PMF of the longest streak (m : P(L=m)):');
let line = '   ';
for (let m = 2; m <= 12; m++) line += ` ${m}:${(100 * lr.pmf[m]).toFixed(1)}%`;
console.log(line + '\n');

// ===========================================================================
// 2. NUMBER OF RUNS / SWITCH COUNT — the Wald–Wolfowitz runs test.
//    Switches S over n-1 adjacent pairs are i.i.d. Bernoulli(1/2) for a fair
//    coin (independence proof: given the middle flip, "differs from left" and
//    "differs from right" are each 1/2 and independent). So S ~ Binomial(n-1, 1/2),
//    and the number of runs R = S + 1 exactly.
// ===========================================================================
console.log('NUMBER OF RUNS  R = switches + 1  (the runs test):');
const meanS = (N - 1) / 2, varS = (N - 1) / 4;      // Binomial(n-1, 1/2)
const meanR = meanS + 1, sdR = Math.sqrt(varS);
let simMeanR = 0, simVarAcc = 0;
const rand2 = mulberry32(0x5EED1234);
for (let t = 0; t < TRIALS; t++) {
  const { R } = measure(realCoin(N, rand2));
  simMeanR += R; simVarAcc += R * R;
}
simMeanR /= TRIALS;
const simVarR = simVarAcc / TRIALS - simMeanR * simMeanR;
console.log(`  exact:  E[R] = ${f2(meanR)}   sd = ${f3(sdR)}`);
console.log(`  sim :   E[R] = ${f3(simMeanR)}   sd = ${f3(Math.sqrt(simVarR))}`);
check('E[R] exact ≡ sim', Math.abs(meanR - simMeanR) < 0.02, `Δ=${Math.abs(meanR - simMeanR).toExponential(2)}`);
check('sd[R] exact ≡ sim', Math.abs(sdR - Math.sqrt(simVarR)) < 0.02);

// Cross-check against the classical (fixed-margin) runs-test formula at n1=n2=50.
{
  const n1 = 50, n2 = 50, n = n1 + n2;
  const ER = 1 + (2 * n1 * n2) / n;
  const VR = (2 * n1 * n2 * (2 * n1 * n2 - n)) / (n * n * (n - 1));
  console.log(`  classical runs test at n1=n2=50:  E[R]=${f2(ER)}  Var=${f2(VR)}  sd=${f3(Math.sqrt(VR))}`);
  check('classical fixed-margin E[R] = 51 (differs from unconditional 50.5 by design)',
    Math.abs(ER - 51) < 1e-9, 'conditioning on balanced counts shifts the mean by +0.5');
}
console.log('  A human who over-alternates pushes R well ABOVE 50.5; the z-score is (R-50.5)/4.97.\n');

// ===========================================================================
// 3. COUNT BALANCE — a real coin is usually NOT 50/50. E|heads - 50|.
// ===========================================================================
console.log('COUNT IMBALANCE  |heads - tails|  (the weakest, noisiest tell):');
let simMeanImb = 0;
const rand3 = mulberry32(0xBA1A9CE0);
for (let t = 0; t < TRIALS; t++) {
  const { heads } = measure(realCoin(N, rand3));
  simMeanImb += Math.abs(2 * heads - N);
}
simMeanImb /= TRIALS;
// Exact E|2H - n| for H~Binomial(n,1/2): sum_h |2h-n| * C(n,h) / 2^n, via log-binomial.
function exactMeanImbalance(n) {
  // log C(n,h)
  const logFact = new Array(n + 1).fill(0);
  for (let i = 2; i <= n; i++) logFact[i] = logFact[i - 1] + Math.log(i);
  const logC = (h) => logFact[n] - logFact[h] - logFact[n - h];
  let e = 0;
  for (let h = 0; h <= n; h++) e += Math.abs(2 * h - n) * Math.exp(logC(h) - n * Math.log(2));
  return e;
}
const exactImb = exactMeanImbalance(N);
console.log(`  exact E|heads-tails| = ${f3(exactImb)}   sim = ${f3(simMeanImb)}`);
check('E|heads-tails| exact ≡ sim', Math.abs(exactImb - simMeanImb) < 0.03,
  `a real 100-flip coin lands about ${Math.round(exactImb)} apart, not 50/50`);
console.log('  Humans balance too well (they steer toward 50/50); a real coin drifts.\n');

// ===========================================================================
// 4. THE IDENTITY the live detector relies on: longest identical-run
//    = 1 + (longest run of "no-switch" among the n-1 adjacency bits), and
//    those adjacency bits are i.i.d. fair. Verify both sides match per-sequence.
// ===========================================================================
console.log('IDENTITY CHECK (per-sequence, 200k coins): L(flips) == 1 + Lrun(adjacency bits):');
let mism = 0;
const rand4 = mulberry32(0x1D3A7);
for (let t = 0; t < 200_000; t++) {
  const s = realCoin(N, rand4);
  const { L } = measure(s);
  // adjacency "same" bits
  let cur = 0, best = 0;
  for (let i = 1; i < N; i++) { if (s[i] === s[i - 1]) { cur++; if (cur > best) best = cur; } else cur = 0; }
  if (L !== 1 + best) mism++;
}
check('longest identical-run = 1 + longest same-adjacency-run (every sequence)', mism === 0,
  `${mism} mismatches in 200k`);

// ===========================================================================
console.log('\n' + (failures === 0
  ? 'ALL CHECKS PASSED — the exact math and a real fair coin agree; every number the page states is grounded.'
  : `${failures} CHECK(S) FAILED.`));
process.exit(failures === 0 ? 0 : 1);
