#!/usr/bin/env node
// verify-are-you-due-for-a-win-gamblers-fallacy.mjs
// Recomputes EVERY number shown on the immersive page from first principles,
// two independent ways where possible. Prints per-check lines; exits 0 iff all pass.
//
// Claims under test:
//   1. Roulette base rates: European red = 18/37 = 48.65%; American red = 18/38 = 47.37%.
//   2. Independence: after any losing streak the NEXT spin's win rate equals the base rate.
//      Verified two ways: (a) closed form (conditional prob is unchanged, exactly p),
//      (b) Monte-Carlo simulation conditioning on a run of k losses -> next-win rate ~= p.
//   3. Monte Carlo 1913: (18/37)^26 ~= 1 in 137 million (a specified color 26 times);
//      2*(18/37)^26 ~= 1 in 68.4 million (either color 26 in a row = all-red OR all-black),
//      matching Wikipedia's "Gambler's fallacy" figure of ~1 in 68.4 million.
//   4. Without replacement, the "due" effect is REAL: drawing a finite 37-pocket wheel
//      without replacement, the conditional next-red rate after a run of blacks RISES.
//      Verified two ways: (a) hypergeometric closed form, (b) Monte-Carlo shuffle sim.
//   5. Miller & Sanjurjo (2018) selection bias: over all 2^4 = 16 four-flip sequences,
//      the average within-sequence proportion of heads-immediately-after-heads = 0.405
//      (exactly 17/42), averaged over the 14 sequences where it is defined.
//      Verified two ways: (a) brute enumeration, (b) exact rational 17/42.

let FAILED = 0;
function check(name, got, want, tol, extra) {
  const ok = Math.abs(got - want) <= tol;
  if (!ok) FAILED++;
  const g = typeof got === 'number' ? (Number.isInteger(got) ? got : got.toPrecision(8)) : got;
  const w = typeof want === 'number' ? (Number.isInteger(want) ? want : want.toPrecision(8)) : want;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}: got ${g}  want ${w} (+/-${tol})${extra ? '  ' + extra : ''}`);
}
function checkTrue(name, cond, extra) {
  if (!cond) FAILED++;
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${extra ? '  ' + extra : ''}`);
}

// deterministic RNG (mulberry32) so the Monte-Carlo checks are reproducible
function mulberry32(a) {
  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;
  };
}

console.log('== 1. Roulette base rates ==');
const pEuro = 18 / 37, pAmer = 18 / 38;
check('European red = 18/37', pEuro, 0.4864864865, 1e-9);
check('European red as %', pEuro * 100, 48.65, 5e-3);
check('American red = 18/38', pAmer, 0.4736842105, 1e-9);
check('American red as %', pAmer * 100, 47.37, 5e-3);
checkTrue('European > American (more red per spin on single-zero wheel)', pEuro > pAmer);

console.log('\n== 2. Independence: streak does not move the next spin ==');
// (a) closed form: for i.i.d. Bernoulli, P(win | k losses before) = p, identically.
// (b) Monte-Carlo: simulate spins, collect the outcome of the spin immediately
//     following every run of exactly-at-least k losses; the mean must equal p.
function simConditional(p, k, spins, seed) {
  const rng = mulberry32(seed);
  let run = 0, trials = 0, wins = 0;
  let prevAtLeastK = false;
  for (let i = 0; i < spins; i++) {
    const win = rng() < p; // "win" = red
    if (prevAtLeastK) { trials++; if (win) wins++; }
    if (win) run = 0; else run++;
    prevAtLeastK = run >= k;
  }
  return { rate: wins / trials, trials };
}
for (const k of [1, 5, 10]) {
  const { rate, trials } = simConditional(pEuro, k, 8_000_000, 12345 + k);
  // tolerance = 5 standard errors of a Bernoulli(p) mean over `trials` samples;
  // rarer streaks (bigger k) yield fewer trials, so the honest band is wider.
  const tol = 5 * Math.sqrt(pEuro * (1 - pEuro) / trials);
  check(`next-win rate after >=${k} losses ~= base ${pEuro.toFixed(4)} (n=${trials})`,
    rate, pEuro, tol, `sim=${rate.toFixed(4)} within +/-${tol.toFixed(4)}`);
}
checkTrue('closed form: conditional prob after any streak is EXACTLY p (independence)', true,
  'P(win | k losses) = p by definition of i.i.d.');

console.log('\n== 3. Monte Carlo, 18 Aug 1913 (fair single-zero wheel) ==');
const p26 = Math.pow(18 / 37, 26);      // a specified color 26 times
const pEither = 2 * p26;                // either color 26 in a row = all-red OR all-black
check('(18/37)^26 odds (millions), 1 in ~137M', 1 / p26 / 1e6, 136.8, 0.3);
check('2*(18/37)^26 odds (millions), 1 in ~68.4M (either color)', 1 / pEither / 1e6, 68.4, 0.3);
checkTrue('spin 27 conditional prob of red still exactly 18/37', (18 / 37) === pEuro);

console.log('\n== 4. WITHOUT replacement, the "due" effect is REAL ==');
// A finite single-zero wheel treated as a 37-pocket deck drawn WITHOUT replacement:
// 18 red, 18 black, 1 green. After drawing b blacks (and 0 reds, 0 green), the
// conditional prob the NEXT draw is red = 18 / (37 - b): it RISES as black depletes.
// (a) hypergeometric closed form:
function condRedAfterBlacks(b) { return 18 / (37 - b); }
const afterNone = condRedAfterBlacks(0);
const after5 = condRedAfterBlacks(5);
const after10 = condRedAfterBlacks(10);
check('without replacement: next-red after 0 blacks = 18/37', afterNone, 18 / 37, 1e-12);
check('without replacement: next-red after 5 blacks = 18/32', after5, 18 / 32, 1e-12);
check('without replacement: next-red after 10 blacks = 18/27', after10, 18 / 27, 1e-12);
checkTrue('the "due" effect climbs monotonically as color depletes',
  afterNone < after5 && after5 < after10,
  `${afterNone.toFixed(3)} < ${after5.toFixed(3)} < ${after10.toFixed(3)}`);
// (b) Monte-Carlo shuffle: deal a shuffled 37-pocket deck; count only the decks
//     whose first b cards are all black, then record card b+1. This is the clean
//     conditional P(card b+1 = red | first b are black); it must match 18/(37-b).
function simNoReplace(b, decks, seed) {
  const rng = mulberry32(seed);
  let trials = 0, reds = 0;
  const base = [];
  for (let i = 0; i < 18; i++) base.push('R');
  for (let i = 0; i < 18; i++) base.push('B');
  base.push('G');
  for (let d = 0; d < decks; d++) {
    const deck = base.slice();
    for (let i = deck.length - 1; i > 0; i--) { // Fisher-Yates
      const j = Math.floor(rng() * (i + 1));
      const t = deck[i]; deck[i] = deck[j]; deck[j] = t;
    }
    let allBlack = true;
    for (let q = 0; q < b; q++) if (deck[q] !== 'B') { allBlack = false; break; }
    if (allBlack) { trials++; if (deck[b] === 'R') reds++; }
  }
  return { rate: reds / trials, trials };
}
{
  const { rate, trials } = simNoReplace(5, 40_000_000, 999);
  const tol = 5 * Math.sqrt((18 / 32) * (1 - 18 / 32) / trials);
  check(`sim without replacement: next-red | first 5 are black ~= 18/32 (n=${trials})`,
    rate, 18 / 32, tol, `sim=${rate.toFixed(4)} within +/-${tol.toFixed(4)}`);
}

console.log('\n== 5. Miller & Sanjurjo (2018) 40.5% selection bias ==');
// Enumerate all 16 four-flip sequences. In each, among flips at positions 1..3 that
// are Heads, what fraction is immediately followed by Heads? Average that within-
// sequence proportion over the 14 sequences where at least one H is so eligible.
let sum = 0, defined = 0;
for (let m = 0; m < 16; m++) {
  const s = [];
  for (let i = 0; i < 4; i++) s.push((m >> i) & 1); // 1 = Heads
  let nAfterH = 0, nHafterH = 0;
  for (let i = 0; i < 3; i++) if (s[i] === 1) { nAfterH++; if (s[i + 1] === 1) nHafterH++; }
  if (nAfterH > 0) { sum += nHafterH / nAfterH; defined++; }
}
const avg = sum / defined;
check('sequences where H-after-H is defined = 14', defined, 14, 0);
check('average heads-after-heads proportion = 0.405 (enumeration)', avg, 0.4047619048, 1e-9);
check('exact rational 17/42', 17 / 42, avg, 1e-12, '(0.405, below the 0.5 "fair" value)');
checkTrue('the artifact is a downward bias: 0.405 < 0.5, so a naive test understates HH',
  avg < 0.5);

console.log('');
if (FAILED === 0) {
  console.log('ALL CHECKS PASS.');
  process.exit(0);
} else {
  console.log(`${FAILED} CHECK(S) FAILED.`);
  process.exit(1);
}
