#!/usr/bin/env node
// ============================================================================
// The Two-Envelope Problem — offline verifier (show the check).
//
// Two claims, one false and one true, both settled here in exact arithmetic
// and cross-checked against Monte Carlo. Nothing prints on the live page that
// isn't reproduced here first.
//
//   PART A — the FALSE argument. "You hold X; the other envelope is 2X or X/2
//            with equal odds, so E[other] = 1.25X > X — always switch." We show
//            that under ANY proper prior the OVERALL gain from always-switching
//            is exactly 0 (envelopes are symmetric), and we exhibit the exact
//            place the per-value argument breaks: on a bounded 'powers of two'
//            prior the interior values do each favour switching, but the single
//            largest value (where switching must lose) cancels them EXACTLY.
//
//   PART B — the TRUE edge (Thomas Cover's switching strategy, 1987). No prior,
//            two DISTINCT reals a<b sealed by an adversary. You open one at
//            random, draw a threshold T from any fixed distribution, and keep
//            iff X >= T. Then
//                 P(you end holding the larger) = 1/2 + p2/2,   p2 = P(a<T<b) > 0.
//            A random number you invented, knowing nothing, beats the coin.
//
// Run:  node research/two-envelope/verify.mjs
// Exit code 0 iff every check passes.
// ============================================================================

'use strict';

let PASS = 0, FAIL = 0;
const results = [];
function check(name, cond, detail) {
  if (cond) { PASS++; results.push(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else      { FAIL++; results.push(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); }
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// ---- a small, seedable PRNG so runs are reproducible ----------------------
function mulberry32(seed) {
  let s = seed >>> 0;
  return function () {
    s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// ---- exact rational arithmetic (BigInt) -----------------------------------
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function rat(n, d = 1n) { if (d < 0n) { n = -n; d = -d; } const g = gcd(n, d) || 1n; return { n: n / g, d: d / g }; }
function rAdd(x, y) { return rat(x.n * y.d + y.n * x.d, x.d * y.d); }
function rMul(x, y) { return rat(x.n * y.n, x.d * y.d); }
function rEq(x, y) { return x.n * y.d === y.n * x.d; }
function rToNum(x) { return Number(x.n) / Number(x.d); }

console.log('============================================================');
console.log(' THE TWO-ENVELOPE PROBLEM — offline verifier');
console.log('============================================================\n');

// ===========================================================================
// PART A — the false argument, and where exactly it breaks
// ===========================================================================
console.log('PART A — "always switch" gains nothing (the paradox dissolved)\n');

// A1. Symmetry: for ANY distribution of the pair, always-switching nets 0.
//     We test three different proper priors for the smaller amount s; the pair
//     is {s, 2s}; a fair coin decides which envelope you are handed.
function alwaysSwitchGain(drawSmaller, trials, rng) {
  let sum = 0;
  for (let i = 0; i < trials; i++) {
    const s = drawSmaller(rng);          // smaller amount
    const pair = [s, 2 * s];
    const handedIdx = rng() < 0.5 ? 0 : 1;
    const mine = pair[handedIdx];
    const other = pair[1 - handedIdx];   // you always switch
    sum += (other - mine);               // realised gain from switching
  }
  return sum / trials;                   // -> 0
}
{
  const rng = mulberry32(12345);
  const N = 2_000_000;
  const priors = {
    'uniform s∈[1,100]': (r) => 1 + 99 * r(),
    'lognormal s':       (r) => Math.exp(2 * (r() + r() + r() - 1.5)), // rough normal→exp
    'powers of two 2^k, k∈0..9': (r) => Math.pow(2, Math.floor(10 * r())),
  };
  for (const [label, draw] of Object.entries(priors)) {
    const g = alwaysSwitchGain(draw, N, rng);
    // gains are O(scale)/sqrt(N); tolerance scaled to each prior's magnitude.
    const scale = label.startsWith('uniform') ? 100 : label.startsWith('powers') ? 512 : 20;
    check(`A1 always-switch gain ≈ 0  [${label}]`,
      approx(g, 0, 0.05 * scale), `mean realised gain = ${g.toFixed(4)} (→0)`);
  }
}

// A2. The exact resolution on a BOUNDED prior (powers of two), done in exact
//     rationals — no sampling. Pair is {2^k, 2^{k+1}}, k uniform on {0..K-1}.
//     Observe X = 2^j. The per-value "expected other" and the naive +25% story:
//       - j = 0        : other is forced to be 2X   → switching gains +X
//       - j = K        : other is forced to be X/2  → switching gains -X/2
//       - 0 < j < K     : other is 2X or X/2 with equal prob → naive +X/4
//     Claim: summed over the true distribution of X, E[gain from switching] = 0.
{
  const K = 12; // pair index k in {0..K-1}; pair = {2^k, 2^{k+1}}; observed exponents j in {0..K}
  const two = (e) => rat(1n << BigInt(e), 1n); // 2^e as an exact rational
  const w = rat(1n, 2n * BigInt(K));           // each (pair, envelope) atom has prob 1/(2K)

  // Enumerate all 2K atoms; accumulate exact E[gain] = E[other - mine].
  let acc = rat(0n, 1n);
  for (let k = 0; k < K; k++) {
    // handed the small envelope -> switch to large: gain = +2^k
    // handed the large envelope -> switch to small: gain = -2^k
    acc = rAdd(acc, rMul(w, two(k)));
    acc = rAdd(acc, rMul(w, rat(-(1n << BigInt(k)), 1n)));
  }
  check('A2 exact E[always-switch gain] = 0 on bounded 2^k prior',
    rEq(acc, rat(0n, 1n)), `exact rational = ${acc.n}/${acc.d}`);

  // A2b. The illusion, dissected in exact arithmetic. Group the SAME total by the
  //      value X=2^j you observe. Every interior value really does favour
  //      switching (conditional gain +X/4, the seductive "+25%"), and the bottom
  //      value forces a win — yet the single largest value, where switching must
  //      halve your money, deficit-cancels the entire pile to exactly zero.
  //      Contributions to E[gain] (weight already folded in):
  //        j=0        : (1/2K)·(+2^0)              [forced switch up]
  //        interior j : (1/2K)·(2^j) + (1/2K)·(-2^{j-1})  [up from below, down from above]
  //        j=K        : (1/2K)·(-2^{K-1})          [forced switch down]
  let bottom = rMul(w, two(0));
  let interior = rat(0n, 1n);
  for (let j = 1; j < K; j++) {
    interior = rAdd(interior, rMul(w, two(j)));                       // handed small of {2^j,2^{j+1}}
    interior = rAdd(interior, rMul(w, rat(-(1n << BigInt(j - 1)), 1n))); // handed large of {2^{j-1},2^j}
  }
  let top = rMul(w, rat(-(1n << BigInt(K - 1)), 1n));
  const total = rAdd(rAdd(bottom, interior), top);
  const upside = rAdd(bottom, interior); // everything that says "switch": bottom win + interior surplus
  check('A2b interior "+25%" + bottom win  ==  −(top loss)  (exact, cancels to 0)',
    rEq(total, rat(0n, 1n)) && rEq(upside, rat(top.n * -1n, top.d)),
    `switch-side = +${rToNum(upside).toFixed(2)}, top value alone = ${rToNum(top).toFixed(2)}  →  sum ${total.n}/${total.d}`);
}

// A3. The per-value conditional P(other = 2X | observe X) is NOT 1/2 for all X
//     under a proper prior — that false premise is the whole illusion. On the
//     bounded 2^k prior it is 1 at the bottom, 1/2 in the interior, 0 at the top.
{
  const K = 8;
  const rng = mulberry32(999);
  const N = 1_500_000;
  const two = (e) => Math.pow(2, e);
  const countDouble = new Map(), countTotal = new Map();
  for (let i = 0; i < N; i++) {
    const k = Math.floor(K * rng());          // pair {2^k, 2^{k+1}}
    const pair = [two(k), two(k + 1)];
    const handed = rng() < 0.5 ? 0 : 1;
    const X = pair[handed], other = pair[1 - handed];
    countTotal.set(X, (countTotal.get(X) || 0) + 1);
    if (other === 2 * X) countDouble.set(X, (countDouble.get(X) || 0) + 1);
  }
  const pDouble = (X) => (countDouble.get(X) || 0) / (countTotal.get(X) || 1);
  check('A3 bottom value: P(other=2X) = 1', approx(pDouble(two(0)), 1, 0.01), `= ${pDouble(two(0)).toFixed(3)}`);
  check('A3 top value:    P(other=2X) = 0', approx(pDouble(two(K)), 0, 0.01), `= ${pDouble(two(K)).toFixed(3)}`);
  check('A3 interior:     P(other=2X) = 1/2', approx(pDouble(two(4)), 0.5, 0.02), `= ${pDouble(two(4)).toFixed(3)}`);
}

// ===========================================================================
// PART B — Cover's threshold strategy: the real, prior-free edge
// ===========================================================================
console.log('\nPART B — a random threshold beats the coin (Cover 1987)\n');

// The keep/switch rule: open X in {a,b}, draw T ~ F, KEEP iff X >= T else SWITCH.
// Claim: P(end holding larger) = 1/2 + p2/2, p2 = P(a < T < b) = F(b) - F(a).

// B1. UNIFORM threshold on [lo,hi] with a,b strictly inside → fully EXACT.
//     p2 = (b-a)/(hi-lo). Predicted P(correct) = 1/2 + p2/2, checked vs MC.
function coverTrial(a, b, drawT, keepIfGE, rng) {
  // hand a uniformly-random envelope; value X in {a,b}
  const X = rng() < 0.5 ? a : b;
  const T = drawT(rng);
  const keep = keepIfGE ? (X >= T) : (X > T);
  const ended = keep ? X : (X === a ? b : a);
  return ended === b; // true iff ended holding the larger
}
{
  const cases = [
    { a: 3, b: 8, lo: 0, hi: 10 },
    { a: 1, b: 2, lo: -5, hi: 5 },
    { a: 100, b: 101, lo: 0, hi: 1000 },
    { a: -4, b: 9, lo: -20, hi: 20 },
  ];
  const rng = mulberry32(24680);
  const N = 3_000_000;
  for (const c of cases) {
    const p2 = rat(BigInt(c.b - c.a), BigInt(c.hi - c.lo)); // exact rational
    const predicted = rat(p2.n + p2.d, 2n * p2.d);          // 1/2 + p2/2 = (p2+1)/2
    const drawT = (r) => c.lo + (c.hi - c.lo) * r();
    let win = 0;
    for (let i = 0; i < N; i++) if (coverTrial(c.a, c.b, drawT, true, rng)) win++;
    const emp = win / N;
    check(`B1 uniform-T  a=${c.a},b=${c.b} on [${c.lo},${c.hi}]`,
      approx(emp, rToNum(predicted), 0.003),
      `predicted 1/2+p2/2 = ${rToNum(predicted).toFixed(4)} (exact ${predicted.n}/${predicted.d}), MC = ${emp.toFixed(4)}`);
  }
}

// B2. NORMAL threshold (standard normal) — p2 = Φ(b) - Φ(a). Uses a high-quality
//     erf; predicted vs MC. Shows the edge holds for a smooth full-support law.
function erf(x) { // Abramowitz & Stegun 7.1.26, |err| < 1.5e-7
  const t = 1 / (1 + 0.3275911 * Math.abs(x));
  const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
  return x >= 0 ? y : -y;
}
const Phi = (x) => 0.5 * (1 + erf(x / Math.SQRT2));
function randn(rng) { // Box–Muller
  let u = 0, v = 0;
  while (u === 0) u = rng();
  while (v === 0) v = rng();
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
{
  const cases = [ { a: -1, b: 0.5 }, { a: 0, b: 2 }, { a: -3, b: -1 }, { a: 1.2, b: 1.25 } ];
  const rng = mulberry32(1357);
  const N = 3_000_000;
  for (const c of cases) {
    const p2 = Phi(c.b) - Phi(c.a);
    const predicted = 0.5 + p2 / 2;
    const drawT = (r) => randn(r);
    let win = 0;
    for (let i = 0; i < N; i++) if (coverTrial(c.a, c.b, drawT, true, rng)) win++;
    const emp = win / N;
    check(`B2 normal-T   a=${c.a},b=${c.b}`,
      approx(emp, predicted, 0.003),
      `predicted 1/2+p2/2 = ${predicted.toFixed(4)}, MC = ${emp.toFixed(4)}`);
  }
}

// B3. The edge is STRICTLY above 1/2 and lives ENTIRELY in the middle region.
//     Decompose the win rate by which region T fell in; only the middle beats 1/2.
{
  const a = 2, b = 7, lo = 0, hi = 10;
  const rng = mulberry32(4242);
  const N = 3_000_000;
  let below = { n: 0, win: 0 }, mid = { n: 0, win: 0 }, above = { n: 0, win: 0 };
  for (let i = 0; i < N; i++) {
    const X = rng() < 0.5 ? a : b;
    const T = lo + (hi - lo) * rng();
    const keep = X >= T;
    const ended = keep ? X : (X === a ? b : a);
    const w = ended === b ? 1 : 0;
    if (T < a) { below.n++; below.win += w; }
    else if (T > b) { above.n++; above.win += w; }
    else { mid.n++; mid.win += w; }
  }
  check('B3 region T<a  → win rate = 1/2', approx(below.win / below.n, 0.5, 0.01), `= ${(below.win/below.n).toFixed(3)}`);
  check('B3 region T>b  → win rate = 1/2', approx(above.win / above.n, 0.5, 0.01), `= ${(above.win/above.n).toFixed(3)}`);
  check('B3 region a<T<b → win rate = 1  (the whole edge)', approx(mid.win / mid.n, 1.0, 0.005), `= ${(mid.win/mid.n).toFixed(3)}`);
}

// B4. The honest caveat: the edge = p2/2 is STRICTLY positive for any full-support
//     F, but the ADVERSARY controls its size. Push the pair into the tail of your
//     fixed threshold law and your invented number rarely lands between a and b,
//     so the (still real) edge shrinks toward 0. There is no universal lower bound
//     without a hint about scale. We verify the edge MATCHES p2/2 across three
//     nested regimes and DECAYS monotonically as the pair moves outward.
{
  const rng = mulberry32(31415);
  const N = 4_000_000;
  const pairs = [
    { a: -0.5, b: 0.5, tag: 'centred' },
    { a: 1.5,  b: 2.5, tag: 'shoulder' },
    { a: 2.5,  b: 3.5, tag: 'tail' },
  ];
  const edges = [];
  for (const c of pairs) {
    const p2 = Phi(c.b) - Phi(c.a);
    let win = 0;
    for (let i = 0; i < N; i++) if (coverTrial(c.a, c.b, (r) => randn(r), true, rng)) win++;
    const emp = win / N;
    edges.push(emp - 0.5);
    check(`B4 ${c.tag} pair a=${c.a},b=${c.b}: edge matches p2/2 and > 0`,
      emp > 0.5 && approx(emp, 0.5 + p2 / 2, 0.003),
      `predicted +${(p2/2).toFixed(4)}, MC edge +${(emp-0.5).toFixed(4)}`);
  }
  check('B4 edge decays as the pair moves into the tail (adversary caveat)',
    edges[0] > edges[1] && edges[1] > edges[2] && edges[2] > 0,
    `edges = [${edges.map((e) => '+' + e.toFixed(4)).join(', ')}] — positive but shrinking`);
}

// ===========================================================================
console.log('\n' + results.join('\n'));
console.log('\n------------------------------------------------------------');
console.log(` ${PASS}/${PASS + FAIL} checks pass` + (FAIL ? `  —  ${FAIL} FAILED` : '  —  all green'));
console.log('------------------------------------------------------------');
process.exit(FAIL ? 1 : 0);
