// verify.mjs — the offline check behind the immersive Monty Hall stratum.
//
// The page lets a reader play the game, flip the HOST'S behaviour, and run thousands of
// trials live. Three claims are checked by exact calculation (enumeration for the
// three-door games, a closed form for N doors) and by independent seeded Monte-Carlo
// simulations. The ten-door atom counts are also enumerated below.
//
//   1. Classic host (KNOWS where the car is; always opens a goat door, never yours):
//        stay wins  1/3,  switch wins  2/3.
//   2. Forgetful host (opens one of the other doors at RANDOM, sometimes revealing the car):
//        among the games where a goat happens to be revealed, stay wins 1/2, switch wins 1/2.
//        (And the host reveals the car outright in 1/3 of all games.)
//   3. N-door dramatic version (host KNOWS, opens every other door but one):
//        stay wins 1/N,  switch wins (N-1)/N.   (N=100 → switch wins 99%.)
//
//   Run:  node research/monty-hall/verify.mjs

// ---- a small seeded PRNG (mulberry32) so the Monte-Carlo numbers are reproducible ----
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;
  };
}
const rint = (rng, n) => Math.floor(rng() * n);

// ---------- EXACT enumeration ----------

// Classic 3-door, host knows. Enumerate car position (3) × your pick (3) × host choice.
// Returns {stay, switch} as exact fractions reduced to decimals.
function exactClassic() {
  let stayWins = 0, switchWins = 0, total = 0;
  for (let car = 0; car < 3; car++) {
    for (let pick = 0; pick < 3; pick++) {
      // host opens a door that is not your pick and not the car
      const openable = [0, 1, 2].filter((d) => d !== pick && d !== car);
      // weight each host choice equally; each (car,pick) is equally likely (1/9)
      for (const open of openable) {
        const w = (1 / 9) * (1 / openable.length);
        total += w;
        const other = [0, 1, 2].find((d) => d !== pick && d !== open);
        if (pick === car) stayWins += w;
        if (other === car) switchWins += w;
      }
    }
  }
  return { stay: stayWins / total, switch: switchWins / total, total };
}

// Forgetful host: opens one of the OTHER two doors uniformly at random (may reveal the car).
// We report probabilities CONDITIONED on the host revealing a goat (the only games the
// puzzle is posed about), plus the unconditional chance the host reveals the car.
function exactForgetful() {
  let stayWins = 0, switchWins = 0, goatRevealed = 0, carRevealed = 0, total = 0;
  for (let car = 0; car < 3; car++) {
    for (let pick = 0; pick < 3; pick++) {
      const others = [0, 1, 2].filter((d) => d !== pick); // host can open either, even the car
      for (const open of others) {
        const w = (1 / 9) * (1 / others.length);
        total += w;
        if (open === car) { carRevealed += w; continue; } // host blew it — not a posed game
        goatRevealed += w;
        const other = [0, 1, 2].find((d) => d !== pick && d !== open);
        if (pick === car) stayWins += w;
        if (other === car) switchWins += w;
      }
    }
  }
  return {
    stayGivenGoat: stayWins / goatRevealed,
    switchGivenGoat: switchWins / goatRevealed,
    pCarRevealed: carRevealed / total,
    pGoatRevealed: goatRevealed / total,
  };
}

// N doors, host knows, opens every door except your pick and ONE other. Switch = move to
// that one other door. Closed form: stay 1/N, switch (N-1)/N.
const exactNDoor = (N) => ({ stay: 1 / N, switch: (N - 1) / N });

// ---------- Independent Monte-Carlo ----------

function simClassic(trials, strat /* 'switch'|'stay' */, rng) {
  let wins = 0;
  for (let i = 0; i < trials; i++) {
    const car = rint(rng, 3), pick = rint(rng, 3);
    const openable = [0, 1, 2].filter((d) => d !== pick && d !== car);
    const open = openable[rint(rng, openable.length)];
    const other = [0, 1, 2].find((d) => d !== pick && d !== open);
    const final = strat === 'switch' ? other : pick;
    if (final === car) wins++;
  }
  return wins / trials;
}

function simForgetful(trials, strat, rng) {
  let wins = 0, posed = 0; // only count games where host revealed a goat
  for (let i = 0; i < trials; i++) {
    const car = rint(rng, 3), pick = rint(rng, 3);
    const others = [0, 1, 2].filter((d) => d !== pick);
    const open = others[rint(rng, others.length)];
    if (open === car) continue; // host revealed the car — discard
    posed++;
    const other = [0, 1, 2].find((d) => d !== pick && d !== open);
    const final = strat === 'switch' ? other : pick;
    if (final === car) wins++;
  }
  return { rate: wins / posed, posedFraction: posed / trials };
}

function simNDoor(trials, N, strat, rng) {
  let wins = 0;
  for (let i = 0; i < trials; i++) {
    const car = rint(rng, N), pick = rint(rng, N);
    // host leaves exactly one other door closed. If the car is among the others, it must
    // be the one left closed; otherwise the left-closed door is a random other door.
    let leftClosed;
    if (car !== pick) leftClosed = car;
    else {
      const others = [];
      for (let d = 0; d < N; d++) if (d !== pick) others.push(d);
      leftClosed = others[rint(rng, others.length)];
    }
    const final = strat === 'switch' ? leftClosed : pick;
    if (final === car) wins++;
  }
  return wins / trials;
}

// ---------- run ----------
let fails = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const ok = (name, cond, extra = '') => { if (!cond) fails++; console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`); };
const rng = mulberry32(20260625);
const T = 400000;

console.log('Monty Hall: exact calculation vs independent Monte-Carlo\n');

// 1. Classic host
{
  const ex = exactClassic();
  ok('exact: classic stay wins 1/3', approx(ex.stay, 1 / 3, 1e-9), `=${ex.stay.toFixed(6)}`);
  ok('exact: classic switch wins 2/3', approx(ex.switch, 2 / 3, 1e-9), `=${ex.switch.toFixed(6)}`);
  ok('exact: probabilities sum to 1', approx(ex.stay + ex.switch, 1, 1e-9));
  const sSwitch = simClassic(T, 'switch', rng), sStay = simClassic(T, 'stay', rng);
  ok('sim: switching wins ≈ 2/3', approx(sSwitch, 2 / 3, 0.004), `=${sSwitch.toFixed(4)}`);
  ok('sim: staying wins ≈ 1/3', approx(sStay, 1 / 3, 0.004), `=${sStay.toFixed(4)}`);
}

// 2. Forgetful host — the record-correction
console.log('\n  forgetful host (opens at random)');
{
  const ex = exactForgetful();
  ok('exact: given a goat shown, stay wins 1/2', approx(ex.stayGivenGoat, 1 / 2, 1e-9), `=${ex.stayGivenGoat.toFixed(6)}`);
  ok('exact: given a goat shown, switch wins 1/2 — switching no longer helps', approx(ex.switchGivenGoat, 1 / 2, 1e-9), `=${ex.switchGivenGoat.toFixed(6)}`);
  ok('exact: a forgetful host reveals the car outright 1/3 of the time', approx(ex.pCarRevealed, 1 / 3, 1e-9), `=${ex.pCarRevealed.toFixed(6)}`);
  const s = simForgetful(T, 'switch', rng);
  ok('sim: switching wins ≈ 1/2 (given a goat was shown)', approx(s.rate, 1 / 2, 0.005), `=${s.rate.toFixed(4)}`);
  ok('sim: a goat is shown in ≈ 2/3 of games', approx(s.posedFraction, 2 / 3, 0.005), `=${s.posedFraction.toFixed(4)}`);
}

// 3. N-door dramatic version
console.log('\n  N-door version (host knows, opens all but one other door)');
for (const N of [3, 10, 50, 100]) {
  const ex = exactNDoor(N);
  const s = simNDoor(T, N, 'switch', rng);
  ok(`exact: N=${N} switch wins (N-1)/N = ${(ex.switch).toFixed(4)}`, true, '');
  ok(`sim:   N=${N} switching wins ≈ ${(ex.switch).toFixed(4)}`, approx(s, ex.switch, 0.004), `=${s.toFixed(4)}`);
}

// 4. The kernel — the same answers as INTEGER ATOM COUNTS, then Lean re-checks them.
//    research/monty-hall/lean/MontyHall.lean hands these exact counts to Lean's kernel
//    (zero imports; `by decide`). Here we (a) recompute the counts the kernel proves,
//    over the identical equiprobable atom spaces, and (b) if `lean` is on PATH, run the
//    proof live and confirm its `#print axioms` verdict — no axioms at all.
console.log('\n  the kernel (integer atom counts — what MontyHall.lean proves)');
{
  const others = (pick) => (pick === 0 ? [1, 2] : pick === 1 ? [0, 2] : [0, 1]);
  const other = (pick, open) => [0, 1, 2].find((d) => d !== pick && d !== open);

  // Knowing host: car(3) × pick(3) × tie(2) = 18 equiprobable atoms.
  let cSwitch = 0, cStay = 0, cValid = 0, cTot = 0;
  for (let car = 0; car < 3; car++) for (let pick = 0; pick < 3; pick++) for (let tie = 0; tie < 2; tie++) {
    cTot++;
    const o = others(pick);
    const open = car === pick ? o[tie] : (o[0] === car ? o[1] : o[0]);
    if (open !== pick && open !== car) cValid++;
    if (pick === car) cStay++;
    if (other(pick, open) === car) cSwitch++;
  }
  ok('kernel: knowing-host atoms = 18', cTot === 18, `=${cTot}`);
  ok('kernel: host always reveals a goat (18/18)', cValid === 18, `=${cValid}`);
  ok('kernel: switch wins 12/18 = 2/3', cSwitch === 12, `=${cSwitch}`);
  ok('kernel: stay wins 6/18 = 1/3', cStay === 6, `=${cStay}`);

  // Forgetful host: car(3) × pick(3) × which(2) = 18 atoms.
  let fCar = 0, fGoat = 0, fSwitch = 0, fStay = 0;
  for (let car = 0; car < 3; car++) for (let pick = 0; pick < 3; pick++) for (let which = 0; which < 2; which++) {
    const open = others(pick)[which];
    if (open === car) { fCar++; continue; }
    fGoat++;
    if (pick === car) fStay++;
    if (other(pick, open) === car) fSwitch++;
  }
  ok('kernel: forgetful reveals the car 6/18 = 1/3', fCar === 6, `=${fCar}`);
  ok('kernel: forgetful reveals a goat 12/18', fGoat === 12, `=${fGoat}`);
  ok('kernel: given a goat, switch wins 6/12 = 1/2', fSwitch === 6, `=${fSwitch}`);
  ok('kernel: given a goat, stay wins 6/12 = 1/2', fStay === 6, `=${fStay}`);

  // N=10 door: car(10) × pick(10) = 100 atoms; switch wins iff first pick was wrong.
  let nSwitch = 0, nTot = 0;
  for (let car = 0; car < 10; car++) for (let pick = 0; pick < 10; pick++) { nTot++; if (pick !== car) nSwitch++; }
  ok('kernel: N=10 atoms = 100', nTot === 100, `=${nTot}`);
  ok('kernel: N=10 switch wins 90/100 = 9/10', nSwitch === 90, `=${nSwitch}`);
}

// Live kernel run only if Lean is installed; see https://lean-lang.org/install/.
// Static-only otherwise.
{
  const { execSync } = await import('node:child_process');
  const { existsSync } = await import('node:fs');
  const leanFile = new URL('./lean/MontyHall.lean', import.meta.url).pathname;
  let leanOnPath = false;
  try { execSync('command -v lean', { stdio: 'ignore' }); leanOnPath = true; } catch { /* not installed */ }
  if (!leanOnPath) {
    console.log('  (skip: lean not on PATH; install Lean: https://lean-lang.org/install/)');
  } else if (!existsSync(leanFile)) {
    ok('lean: MontyHall.lean present', false);
  } else {
    let out = '';
    try { out = execSync(`lean ${JSON.stringify(leanFile)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); }
    catch (e) { out = (e.stdout || '') + (e.stderr || ''); ok('lean: MontyHall.lean typechecks (no errors)', false, out.slice(0, 300)); }
    if (out !== null) {
      const clean = !/error/i.test(out);
      ok('lean: MontyHall.lean typechecks (no errors)', clean);
      ok('lean: the_host_protocol_decides depends on NO axioms',
        /the_host_protocol_decides'? does not depend on any axioms/.test(out), '');
      ok('lean: no sorry / Classical.choice / native_decide in footprint',
        !/sorry|Classical\.choice|native/i.test(out));
    }
  }
}

console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ ' + fails + ' FAILED'} — ${fails} failed.`);
process.exit(fails === 0 ? 0 : 1);
