#!/usr/bin/env node
// Offline gate for /strata/what-is-the-house-edge-in-roulette/
// Recomputes EVERY number the page shows, from pocket counts and posted payout
// odds alone, two independent ways where possible:
//   (A) closed-form:  house edge = (N - 36) / N   for all standard bets,
//   (B) per-bet EV:   (k/N)*payout - ((N-k)/N)*1  enumerated bet by bet.
// Plus the five-number basket exception, European, French la partage, and a
// Monte-Carlo proof that Martingale does not change expected loss per unit staked.
// Exits 0 iff every check passes.

let pass = 0, fail = 0;
const EPS = 1e-12;
function check(name, got, want, eps = EPS) {
  const ok = Math.abs(got - want) <= eps;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}  got=${got}  want=${want}`);
  ok ? pass++ : fail++;
}
function checkBool(name, cond) {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}`);
  cond ? pass++ : fail++;
}

// ── Standard bets: k pockets, posted payout (x:1). All standard bets pay as if
//    36 pockets existed: payout = 36/k - 1. ───────────────────────────────────
const STANDARD = [
  { name: 'straight-up', k: 1,  pay: 35 },
  { name: 'split',       k: 2,  pay: 17 },
  { name: 'street',      k: 3,  pay: 11 },
  { name: 'corner',      k: 4,  pay: 8  },
  { name: 'six-line',    k: 6,  pay: 5  },
  { name: 'column',      k: 12, pay: 2  },
  { name: 'dozen',       k: 12, pay: 2  },
  { name: 'red/black',   k: 18, pay: 1  },
  { name: 'odd/even',    k: 18, pay: 1  },
  { name: 'high/low',    k: 18, pay: 1  },
];

// EV per unit staked, no partage.
function ev(N, k, pay) {
  return (k / N) * pay - ((N - k) / N) * 1;
}

console.log('== 1. Posted payouts obey payout = 36/k - 1 for every standard bet ==');
for (const b of STANDARD) {
  check(`${b.name}: 36/${b.k}-1`, 36 / b.k - 1, b.pay, 1e-9);
}

console.log('\n== 2. AMERICAN double-zero (N=38): every standard bet = -2/38 = -5.26% ==');
const AM_EDGE = 2 / 38; // 0.0526315...
for (const b of STANDARD) {
  const houseEdge = -ev(38, b.k, b.pay);
  check(`American ${b.name} house edge`, houseEdge, AM_EDGE);
}
// closed form (B): (N-36)/N
check('closed form (38-36)/38 == 2/38', (38 - 36) / 38, AM_EDGE);
check('2/38 == 1/19', 2 / 38, 1 / 19);
checkBool('American standard edge rounds to 5.26%', Math.round(AM_EDGE * 10000) / 100 === 5.26);

console.log('\n== 3. The five-number BASKET (0-00-1-2-3), pays 6:1: -3/38 = -7.89% ==');
const basketEdge = -ev(38, 5, 6);
check('basket house edge', basketEdge, 3 / 38);
checkBool('basket rounds to 7.89%', Math.round(basketEdge * 10000) / 100 === 7.89);
checkBool('basket is the lone bet WORSE than 5.26%', basketEdge > AM_EDGE + 1e-9);
// basket is underpaid: fair-36 payout would be 36/5 - 1 = 6.2, casino pays only 6.
check('basket fair-36 payout would be 6.2', 36 / 5 - 1, 6.2, 1e-9);

console.log('\n== 4. EUROPEAN single-zero (N=37): every standard bet = -1/37 = -2.70% ==');
const EU_EDGE = 1 / 37;
for (const b of STANDARD) {
  const houseEdge = -ev(37, b.k, b.pay);
  check(`European ${b.name} house edge`, houseEdge, EU_EDGE);
}
check('closed form (37-36)/37 == 1/37', (37 - 36) / 37, EU_EDGE);
checkBool('European edge rounds to 2.70%', Math.round(EU_EDGE * 10000) / 100 === 2.70);
checkBool('European halves American (2/38 -> ~1/37)',
  Math.abs(AM_EDGE / EU_EDGE - 1.947) < 0.01);

console.log('\n== 5. FRENCH la partage: even-money bets = -0.5/37 = -1.35% ==');
// Even-money bet, N=37: win 18/37 (+1), lose to opposite 18/37 (-1), lose to zero
// 1/37 but la partage returns half the stake (net -0.5).
function evPartage() {
  return (18 / 37) * 1 - (18 / 37) * 1 - (1 / 37) * 0.5;
}
const FR_EDGE = 0.5 / 37;
check('French la partage even-money EV', -evPartage(), FR_EDGE);
check('French even-money edge = 0.5/37', FR_EDGE, 0.5 / 37);
checkBool('French even-money rounds to 1.35%', Math.round(FR_EDGE * 10000) / 100 === 1.35);
checkBool('French is ~4x better than American even-money',
  Math.abs(AM_EDGE / FR_EDGE - 3.9) < 0.05);
// Hazard guard: la partage does NOT help non-even-money bets; a straight-up on a
// French wheel keeps the full single-zero edge.
check('French straight-up (no partage) stays 1/37', -ev(37, 1, 35), EU_EDGE);

console.log('\n== 6. Invariance: edge is a property of the WHEEL, not the bet ==');
// For a fixed N, every standard bet yields identical edge (spread == 0).
for (const N of [38, 37]) {
  const edges = STANDARD.map(b => -ev(N, b.k, b.pay));
  const spread = Math.max(...edges) - Math.min(...edges);
  check(`N=${N}: max-min spread across all standard bets`, spread, 0);
}

console.log('\n== 7. Monte-Carlo: Martingale changes variance, NOT expected loss ==');
// Deterministic PRNG (mulberry32) so the gate is 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;
  };
}
// One red/black spin on American: win prob 18/38.
// Flat betting: 1 unit per spin. Track net and total wagered.
function simFlat(rng, spins) {
  let net = 0, wagered = 0;
  for (let i = 0; i < spins; i++) {
    wagered += 1;
    net += rng() < 18 / 38 ? +1 : -1;
  }
  return { net, wagered };
}
// Martingale: base 1, double on loss, reset on win. Finite bankroll + table cap.
// The point is per-unit-staked EV, which is invariant; bankroll/cap only reshape
// the outcome distribution (many small wins vs rare ruin), not the edge.
function simMartingale(rng, spins, bankroll, cap) {
  let net = 0, wagered = 0, bet = 1, bank = bankroll;
  for (let i = 0; i < spins; i++) {
    if (bet > cap || bet > bank) { bet = 1; } // reset when capped out (a real rule)
    wagered += bet;
    bank -= bet;
    if (rng() < 18 / 38) { bank += bet * 2; net += bet; bet = 1; }
    else { net -= bet; bet *= 2; }
  }
  return { net, wagered };
}
const rng1 = mulberry32(12345);
const rng2 = mulberry32(67890);
const SPINS = 4_000_000;
const flat = simFlat(rng1, SPINS);
const mart = simMartingale(rng2, SPINS, 1023, 512);
const flatEdge = -flat.net / flat.wagered;
const martEdge = -mart.net / mart.wagered;
console.log(`  flat:       net=${flat.net}  wagered=${flat.wagered}  loss/unit=${flatEdge.toFixed(5)}`);
console.log(`  martingale: net=${mart.net}  wagered=${mart.wagered}  loss/unit=${martEdge.toFixed(5)}`);
checkBool(`flat loss/unit converges to 5.26% (${(flatEdge * 100).toFixed(3)}%)`,
  Math.abs(flatEdge - AM_EDGE) < 0.002);
checkBool(`martingale loss/unit converges to SAME 5.26% (${(martEdge * 100).toFixed(3)}%)`,
  Math.abs(martEdge - AM_EDGE) < 0.002);
checkBool('both systems pinned to the house edge (differ by < 0.2 pt)',
  Math.abs(flatEdge - martEdge) < 0.002);

console.log('\n== 8. Session-distribution shape: Martingale = many small wins + rare ruin ==');
// Short fixed-length sessions; Martingale should win MORE often per session yet
// carry a fat catastrophic-loss tail (the honest failure mode).
function sessionNet(sim, seed, spins, ...rest) {
  return sim(mulberry32(seed), spins, ...rest).net;
}
const SESS = 20000, LEN = 60;
let flatWins = 0, martWins = 0, martWorst = 0, flatWorst = 0;
for (let s = 0; s < SESS; s++) {
  const f = sessionNet(simFlat, s * 2 + 1, LEN);
  const m = sessionNet(simMartingale, s * 2 + 2, LEN, 255, 128);
  if (f > 0) flatWins++;
  if (m > 0) martWins++;
  if (m < martWorst) martWorst = m;
  if (f < flatWorst) flatWorst = f;
}
console.log(`  flat: sessions ending ahead = ${(100 * flatWins / SESS).toFixed(1)}%  worst=${flatWorst}`);
console.log(`  mart: sessions ending ahead = ${(100 * martWins / SESS).toFixed(1)}%  worst=${martWorst}`);
checkBool('Martingale ends more sessions ahead than flat (many small wins)',
  martWins > flatWins);
checkBool('Martingale worst-case loss is far deeper than flat (rare ruin tail)',
  martWorst < flatWorst - 20);

console.log(`\n${fail === 0 ? 'ALL PASS' : 'FAILURES: ' + fail} (${pass} passed, ${fail} failed)`);
process.exit(fail === 0 ? 0 : 1);
