// research/parrondo — de-risking "Something From Nothing" (Parrondo's paradox).
//
// Parrondo's paradox: two games, each LOSING in expectation, that become a
// WINNING game when you alternate between them — randomly, or on a fixed
// schedule. Nothing here is asserted; every number the page prints is recomputed
// first, the same way the in-browser instruments compute it, by independent
// engines that must agree:
//
//   ENGINE 1 — exact stationary distribution by rational (BigInt) linear algebra:
//              solve  πP = π,  Σπ = 1  over Z_M, then drift = Σ π(s)(2p(s) − 1).
//   ENGINE 2 — independent float power-iteration of the same chain to a fixed
//              point; must agree with Engine 1 to ~1e-12.
//   ENGINE 3 — Monte-Carlo of the actual ±1 capital walk; the empirical drift
//              must match the exact drift within a reported tolerance.
//
// The classic parameters (Harmer & Abbott, Nature 402 (1999) 864; Statistical
// Science 14 (1999) 206): ε = 1/200, M = 3.
//   Game A  : one biased coin, win prob  p_A = 1/2 − ε.
//   Game B  : capital-dependent —
//               capital ≡ 0 (mod 3): "bad"  coin, win prob p_1 = 1/10 − ε
//               capital ≢ 0 (mod 3): "good" coin, win prob p_2 = 3/4 − ε
//   Mixing  : at each step play A with prob γ, else B  (here γ = 1/2),
//             or a fixed pattern such as AABB.
//
// Run: `node research/parrondo/verify.mjs`

// ---------- exact rational arithmetic (BigInt) ----------
const gcd = (a, b) => (b ? gcd(b, a % b) : a < 0n ? -a : a);
class Q {
  constructor(n, d = 1n) {
    if (d === 0n) throw new Error('div by zero');
    if (d < 0n) { n = -n; d = -d; }
    const k = gcd(n < 0n ? -n : n, d) || 1n;
    this.n = n / k; this.d = d / k;
  }
  add(o) { return new Q(this.n * o.d + o.n * this.d, this.d * o.d); }
  sub(o) { return new Q(this.n * o.d - o.n * this.d, this.d * o.d); }
  mul(o) { return new Q(this.n * o.n, this.d * o.d); }
  div(o) { return new Q(this.n * o.d, this.d * o.n); }
  neg()  { return new Q(-this.n, this.d); }
  eq(o)  { return this.n === o.n && this.d === o.d; }
  isZero() { return this.n === 0n; }
  get f() { return Number(this.n) / Number(this.d); }
  get s() { return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`; }
}
const Q0 = new Q(0n), Q1 = new Q(1n);
const fromFrac = (n, d) => new Q(BigInt(n), BigInt(d));

// ---------- the classic parameters, as exact rationals ----------
// ε = 1/200.  p_A = 1/2 − ε = 99/200.  p_1 = 1/10 − ε = 19/200.  p_2 = 3/4 − ε = 149/200.
const EPS = fromFrac(1, 200);
const pA  = fromFrac(1, 2).sub(EPS);   // 99/200
const p1  = fromFrac(1, 10).sub(EPS);  // 19/200
const p2  = fromFrac(3, 4).sub(EPS);   // 149/200
const M = 3;

// win-probability functions p(state), state in 0..M-1
const probA   = (_s) => pA;                       // game A ignores capital
const probB   = (s) => (s % M === 0 ? p1 : p2);   // game B: bad coin only at ≡0
const probMix = (gamma) => (s) =>                 // play A w.p. gamma, else B
  gamma.mul(probA(s)).add(Q1.sub(gamma).mul(probB(s)));

// ---------- ENGINE 1: exact stationary distribution + drift ----------
// On Z_M with up/down probabilities, from state s: s→s+1 w.p. p(s); s→s−1 w.p. 1−p(s).
function transition(prob) {
  const P = Array.from({ length: M }, () => Array.from({ length: M }, () => Q0));
  for (let s = 0; s < M; s++) {
    const up = prob(s), down = Q1.sub(up);
    P[s][(s + 1) % M] = P[s][(s + 1) % M].add(up);
    P[s][(s - 1 + M) % M] = P[s][(s - 1 + M) % M].add(down);
  }
  return P;
}
// solve πP = π with Σπ = 1, exactly. Build (P^T − I), replace last row by all-ones = 1.
function stationary(P) {
  const n = P.length;
  const A = Array.from({ length: n }, (_, i) =>
    Array.from({ length: n + 1 }, (_, j) =>
      j === n ? Q0 : (P[j][i].sub(i === j ? Q1 : Q0))));   // (P^T − I)π = 0
  for (let j = 0; j < n; j++) A[n - 1][j] = Q1;            // last eq: Σπ = 1
  A[n - 1][n] = Q1;
  // Gauss–Jordan over rationals
  for (let col = 0; col < n; col++) {
    let piv = col; while (piv < n && A[piv][col].isZero()) piv++;
    [A[col], A[piv]] = [A[piv], A[col]];
    const pv = A[col][col];
    A[col] = A[col].map((x) => x.div(pv));
    for (let r = 0; r < n; r++) if (r !== col && !A[r][col].isZero()) {
      const f = A[r][col];
      A[r] = A[r].map((x, k) => x.sub(f.mul(A[col][k])));
    }
  }
  return A.map((row) => row[n]);
}
function exactDrift(prob) {
  const pi = stationary(transition(prob));
  // drift = Σ π(s) (2p(s) − 1)
  let d = Q0;
  for (let s = 0; s < M; s++) d = d.add(pi[s].mul(prob(s).mul(new Q(2n)).sub(Q1)));
  return { pi, drift: d };
}

// ---------- ENGINE 2: independent float power-iteration ----------
function stationaryFloat(prob, iters = 200000) {
  const P = Array.from({ length: M }, (_, s) => {
    const up = prob(s).f, row = new Array(M).fill(0);
    row[(s + 1) % M] += up; row[(s - 1 + M) % M] += 1 - up; return row;
  });
  let v = new Array(M).fill(1 / M);
  for (let t = 0; t < iters; t++) {
    const w = new Array(M).fill(0);
    for (let i = 0; i < M; i++) for (let j = 0; j < M; j++) w[j] += v[i] * P[i][j];
    v = w;
  }
  let drift = 0;
  for (let s = 0; s < M; s++) drift += v[s] * (2 * prob(s).f - 1);
  return { pi: v, drift };
}

// ---------- ENGINE 3: Monte-Carlo of the real capital walk ----------
function montecarlo(prob, steps = 4_000_000, seed = 12345) {
  // small deterministic PRNG (mulberry32) so the run is reproducible
  let a = seed >>> 0;
  const rnd = () => { 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; };
  let cap = 0, sum = 0; const visit = new Array(M).fill(0);
  for (let t = 0; t < steps; t++) {
    const s = ((cap % M) + M) % M; visit[s]++;
    const win = rnd() < prob(s).f ? 1 : -1;
    cap += win; sum += win;
  }
  return { drift: sum / steps, pi: visit.map((v) => v / steps), finalCapital: cap };
}

// ---------- periodic-pattern chain (e.g. AABB): independent winning rule ----------
// State = (capital mod M, phase in pattern). pattern is an array of 'A'/'B'.
function exactDriftPattern(pattern) {
  const L = pattern.length, n = M * L;
  const idx = (s, ph) => s * L + ph;
  const probAt = (ph) => (pattern[ph] === 'A' ? probA : probB);
  const P = Array.from({ length: n }, () => Array.from({ length: n }, () => Q0));
  for (let s = 0; s < M; s++) for (let ph = 0; ph < L; ph++) {
    const up = probAt(ph)(s), down = Q1.sub(up), nph = (ph + 1) % L;
    P[idx(s, ph)][idx((s + 1) % M, nph)] = P[idx(s, ph)][idx((s + 1) % M, nph)].add(up);
    P[idx(s, ph)][idx((s - 1 + M) % M, nph)] = P[idx(s, ph)][idx((s - 1 + M) % M, nph)].add(down);
  }
  const pi = stationary(P);
  let d = Q0;
  for (let s = 0; s < M; s++) for (let ph = 0; ph < L; ph++)
    d = d.add(pi[idx(s, ph)].mul(probAt(ph)(s).mul(new Q(2n)).sub(Q1)));
  // marginal capital-mod-M distribution (summed over phase)
  const marg = new Array(M).fill(Q0);
  for (let s = 0; s < M; s++) for (let ph = 0; ph < L; ph++) marg[s] = marg[s].add(pi[idx(s, ph)]);
  return { drift: d, marg };
}

// ===================== checks =====================
let checks = 0, fails = 0;
const ok = (cond, msg) => { checks++; if (!cond) { fails++; console.log('  ✗ ' + msg); } };
const pct = (x) => (100 * x).toFixed(4) + '%';

console.log('Parrondo\'s paradox — classic parameters ε = 1/200, M = 3');
console.log('  p_A = ' + pA.s + ' = ' + pA.f + ' ,  p_1 = ' + p1.s + ' = ' + p1.f + ' ,  p_2 = ' + p2.s + ' = ' + p2.f + '\n');

// ---- Game A alone: drift is exactly −2ε, and < 0 ----
const A = exactDrift(probA);
ok(A.drift.eq(EPS.mul(new Q(2n)).neg()), 'Game A drift should equal −2ε exactly');
ok(A.drift.f < 0, 'Game A must be losing');
console.log('GAME A alone (single biased coin):');
console.log('  drift per step = ' + A.drift.s + ' = ' + A.drift.f + '   (losing: ' + (A.drift.f < 0) + ')\n');

// ---- Game B alone: stationary mod-3, drift < 0 (the capital-trap) ----
const B = exactDrift(probB);
ok(B.drift.f < 0, 'Game B must be losing on its own');
const Bf = stationaryFloat(probB), Bm = montecarlo(probB);
ok(Math.abs(B.drift.f - Bf.drift) < 1e-9, 'Engine1 vs Engine2 disagree (B drift)');
ok(Math.abs(B.drift.f - Bm.drift) < 2e-3, 'Engine3 (MC) off for B drift');
for (let s = 0; s < M; s++) ok(Math.abs(B.pi[s].f - Bf.pi[s]) < 1e-9, `B stationary mismatch at ${s}`);
console.log('GAME B alone (capital-dependent, bad coin only at capital ≡ 0 mod 3):');
console.log('  stationary capital mod 3:  π0=' + B.pi[0].s + '  π1=' + B.pi[1].s + '  π2=' + B.pi[2].s);
console.log('     (decimal:  ' + B.pi.map((q) => q.f.toFixed(4)).join('  ') + ')  — π0 is the trap, ≫ 1/3 = 0.3333');
console.log('  exact drift  = ' + B.drift.s + ' = ' + B.drift.f.toExponential(4) + '   (losing: ' + (B.drift.f < 0) + ')');
console.log('  cross-check  — float power-iter drift = ' + Bf.drift.toExponential(4) + ' ; Monte-Carlo (4e6) = ' + Bm.drift.toExponential(4) + '\n');

// ---- The seductive WRONG number: assume capital mod 3 is uniform (1/3 each) ----
let naiveB = Q0;
for (let s = 0; s < M; s++) naiveB = naiveB.add(fromFrac(1, 3).mul(probB(s).mul(new Q(2n)).sub(Q1)));
ok(naiveB.f > 0, 'the naive uniform assumption for B should look winning (the trap)');
ok(B.drift.f < 0, 'but the true B is losing');
console.log('THE TRAP — if you (wrongly) assume capital mod 3 is uniform 1/3 each:');
console.log('  "naive" B drift = ' + naiveB.s + ' = ' + naiveB.f.toFixed(4) + '  (LOOKS WINNING)');
console.log('  but the true stationary concentrates on the bad state, so real B drift = ' + B.drift.f.toExponential(4) + '  (LOSES).');
console.log('  The whole paradox lives in this gap: capital mod 3 is NOT uniform.\n');

// ---- Random 1/2:1/2 mix of A and B: drift > 0 (the paradox) ----
const half = fromFrac(1, 2);
const Mix = exactDrift(probMix(half));
ok(Mix.drift.f > 0, 'the 1/2:1/2 random mix must be WINNING');
const Mf = stationaryFloat(probMix(half)), Mm = montecarlo(probMix(half));
ok(Math.abs(Mix.drift.f - Mf.drift) < 1e-9, 'Engine1 vs Engine2 disagree (mix drift)');
ok(Math.abs(Mix.drift.f - Mm.drift) < 2e-3, 'Engine3 (MC) off for mix drift');
console.log('RANDOM MIX  (each step: play A w.p. 1/2, else B):');
console.log('  stationary capital mod 3:  ' + Mix.pi.map((q) => q.f.toFixed(4)).join('  ') + '   (π0 dropped from ' + B.pi[0].f.toFixed(4) + ' → ' + Mix.pi[0].f.toFixed(4) + ')');
console.log('  exact drift  = ' + Mix.drift.s + ' = ' + Mix.drift.f.toExponential(4) + '   (WINNING: ' + (Mix.drift.f > 0) + ')');
console.log('  cross-check  — float = ' + Mf.drift.toExponential(4) + ' ; Monte-Carlo = ' + Mm.drift.toExponential(4));
console.log('  >>> two losers ('+A.drift.f.toExponential(2)+', '+B.drift.f.toExponential(2)+') average into a WINNER ('+Mix.drift.f.toExponential(2)+'). <<<\n');

// ---- Periodic patterns: an independent winning rule (no randomness at all) ----
console.log('DETERMINISTIC PATTERNS (no coin to pick the game — fixed schedule):');
for (const patStr of ['AB', 'AABB', 'AAABBB', 'ABBAB']) {
  const r = exactDriftPattern([...patStr]);
  console.log('  ' + patStr.padEnd(7) + ' drift = ' + r.drift.f.toExponential(4) + (r.drift.f > 0 ? '  (winning)' : '  (losing)') + '   capital mod3 ' + r.marg.map((q) => q.f.toFixed(3)).join('/'));
}
const aabb = exactDriftPattern([...'AABB']);
ok(aabb.drift.f > 0, 'the AABB schedule must also win');
console.log('  >>> AABB wins with NO randomness at all — the resource is the SWITCHING, not luck. <<<\n');

// ---- Control: kill the capital-dependence and the paradox VANISHES (honesty) ----
// Game B' = same two coins but chosen by an independent fair coin (capital-blind),
// so coin1 is used 1/2 the time, coin2 1/2 the time, regardless of capital.
const probBblind = (_s) => half.mul(p1).add(half.mul(p2));   // capital-independent
const Bb = exactDrift(probBblind);
const MixBlind = exactDrift((s) => half.mul(probA(s)).add(half.mul(probBblind(s))));
// if B' is losing, a capital-blind mix of two losers stays losing (no free lunch)
ok(Bb.drift.f < 0, 'capital-blind B′ should be losing too here');
ok(MixBlind.drift.f < 0, 'CONTROL: with capital-dependence removed, the mix is NOT winning');
console.log('CONTROL — remove the capital-dependence (choose B\'s coin by an independent fair flip):');
console.log('  capital-blind B′ drift = ' + Bb.drift.f.toExponential(4) + ' (losing) ; its mix with A = ' + MixBlind.drift.f.toExponential(4) + ' (still losing).');
console.log('  No paradox without the correlation through shared capital. This is where the "something from nothing" is paid for.\n');

// ---- Sweep ε: locate the paradox window where A,B lose but the mix wins ----
console.log('ε-SWEEP — for which biases do BOTH games lose yet the mix win?');
let windowLo = null, windowHi = null;
for (let k = 0; k <= 40; k++) {
  const e = new Q(BigInt(k), 1000n);                 // ε = 0.000 … 0.040
  const pa = fromFrac(1, 2).sub(e), q1 = fromFrac(1, 10).sub(e), q2 = fromFrac(3, 4).sub(e);
  const pAf = () => pa, pBf = (s) => (s % M === 0 ? q1 : q2);
  const dA = exactDrift(pAf).drift.f;
  const dB = exactDrift(pBf).drift.f;
  const dM = exactDrift((s) => half.mul(pAf(s)).add(half.mul(pBf(s)))).drift.f;
  const inWin = dA < 0 && dB < 0 && dM > 0;
  if (inWin) { if (windowLo === null) windowLo = e.f; windowHi = e.f; }
}
ok(windowLo !== null && windowLo <= 0.005 && 0.005 <= windowHi, 'ε = 0.005 should sit inside the paradox window');
console.log('  paradox window (coarse 0.001 grid): ε ∈ [' + windowLo + ', ' + windowHi + ']  — the classic ε = 0.005 sits inside.');

// ---- The EXACT window edges (the coarse grid above only sees the lattice) ----
// drift as exact functions of an arbitrary rational ε:
const driftAof = (e) => exactDrift(() => fromFrac(1, 2).sub(e));
const driftBof = (e) => { const q1 = fromFrac(1, 10).sub(e), q2 = fromFrac(3, 4).sub(e);
  return exactDrift((s) => (s % M === 0 ? q1 : q2)); };
const driftMof = (e) => { const q1 = fromFrac(1, 10).sub(e), q2 = fromFrac(3, 4).sub(e), pa = fromFrac(1, 2).sub(e);
  return exactDrift((s) => half.mul(pa).add(half.mul(s % M === 0 ? q1 : q2))); };

// EDGE 1 — at ε = 0 exactly: A and B are individually FAIR (drift 0), yet the MIX
// already WINS. This is the sharpest form of the paradox and corrects the page's
// old "at ε=0 every drift is zero" — the mix's is not.
const dA0 = driftAof(Q0), dB0 = driftBof(Q0), dM0 = driftMof(Q0);
ok(dA0.drift.isZero(), 'at ε=0, Game A is exactly fair');
ok(dB0.drift.isZero(), 'at ε=0, Game B is exactly fair');
ok(!dM0.drift.isZero() && dM0.drift.f > 0, 'at ε=0 the MIX is not fair — it already WINS');
ok(dM0.drift.eq(fromFrac(18, 709)), 'the ε=0 mix drift is exactly 18/709');

// EDGE 2 — lower edge is ε = 0 (open): for ANY ε>0, B already loses (drift<0).
// So the window starts at 0, not at the grid's 0.001.
ok(driftBof(fromFrac(1, 1000000)).drift.f < 0, 'B loses for arbitrarily small ε>0 — lower edge is 0');

// EDGE 3 — exact UPPER edge ε*: the unique ε in (0, 1/2) where the mix drift returns
// to 0 (B is still losing there). Certify it with a rational sign-change bracket and
// pin it by bisection over exact rationals.
const lo = fromFrac(131092, 10000000), hi = fromFrac(131093, 10000000);
ok(driftMof(lo).drift.f > 0, 'mix still wins at ε = 0.0131092');
ok(driftMof(hi).drift.f < 0, 'mix loses by ε = 0.0131093 — the edge is bracketed');
ok(driftBof(lo).drift.f < 0 && driftBof(hi).drift.f < 0, 'B is still losing across the upper edge');
// bisect over rationals for a high-precision value of ε*
let a = Q0, b = fromFrac(1, 2);                       // mix>0 at a→0+, mix<0 well before 1/2
for (let i = 0; i < 120; i++) {
  const m = a.add(b).div(new Q(2n));
  if (driftMof(m).drift.f > 0) a = m; else b = m;
}
const epsStar = a.add(b).div(new Q(2n)).f;
ok(epsStar > 0.0131092 && epsStar < 0.0131093, 'bisected ε* lands inside the certified bracket');
console.log('  EXACT window: ε ∈ (0, ε*),  ε* ≈ ' + epsStar.toFixed(9) +
            '   — lower edge is 0 (B loses for any ε>0), upper edge is the lone mix-drift zero.');
console.log('  At ε = 0 EXACTLY: Game A and Game B are both fair (drift 0), yet the mix drift = 18/709 = ' +
            (18 / 709).toFixed(6) + ' > 0 — two FAIR games average into a winner.\n');

console.log(`${fails === 0 ? '✓ ALL' : '✗ ' + (checks - fails) + '/'} ${checks} checks ${fails === 0 ? 'PASS' : 'FAIL (' + fails + ' failed)'}`);
process.exit(fails === 0 ? 0 : 1);
