// verify.mjs: selected birthday-problem results checked with several methods.
//
// CLAIMS the stratum makes:
//   1. With 365 equally likely birthdays, the probability that SOME pair in a room
//      of n people shares a birthday is
//          P(n) = 1 − ∏_{k=0}^{n-1} (365−k)/365
//      and it first crosses 1/2 at n = 23 (P(23) ≈ 0.5073) — far fewer than people
//      guess. P(57) ≈ 0.99, P(70) ≈ 0.9992, and P(366) = 1 exactly (pigeonhole).
//   2. The intuition trap: the probability that someone shares YOUR specific
//      birthday is a completely different, much slower curve,
//          P_you(n) = 1 − (364/365)^n,
//      which needs n = 253 to cross 1/2. People answer the second question (their
//      own birthday) when asked the first (any pair) — that's the whole illusion.
//   3. The mean number of people until the first collision is ≈ 24.6 (an exact
//      sum), and the 1/2-crossing scales as ≈ √(2 ln2 · 365) ≈ 22.5.
//
// CHECK COVERAGE (methods vary by result):
//   A. P(n) by the product formula AND by an independent log-sum (lgamma) route —
//      they must agree to machine precision.
//   B. the 23 / 57 / 70 / 366 landmarks, and that 23 is the FIRST crossing.
//   C. seeded Monte-Carlo rates for n=10,23,40 are compared with P(n).
//   D. the "your birthday" curve and its 253 crossing; the exact mean (≈24.6).
//
//   run:  node research/the-birthday-problem/verify.mjs

import { writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const here = dirname(fileURLToPath(import.meta.url));

let fails = 0;
const ok = (name, cond, extra = '') => { if (!cond) fails++; console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`); };

const N = 365; // days (no Feb 29; see honest apparatus)

// --- A1. the product formula (the canonical no-match-then-complement route) ---
function pAny(n) {
  let q = 1;
  for (let k = 0; k < n; k++) q *= (N - k) / N; // P(all distinct)
  return 1 - q;
}

// --- A2. independent route via log-gamma: P(distinct) = N!/((N−n)!·N^n) ---
// ln Γ via Lanczos; then ln P(distinct) = lnΓ(N+1) − lnΓ(N−n+1) − n·lnN
function lgamma(z) {
  const g = 7, c = [
    0.99999999999980993, 676.5203681218851, -1259.1392167224028,
    771.32342877765313, -176.61502916214059, 12.507343278686905,
    -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
  if (z < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * z)) - lgamma(1 - z);
  z -= 1; let x = c[0];
  for (let i = 1; i < g + 2; i++) x += c[i] / (z + i);
  const t = z + g + 0.5;
  return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
}
function pAnyLog(n) {
  if (n > N) return 1;
  const lnDistinct = lgamma(N + 1) - lgamma(N - n + 1) - n * Math.log(N);
  return 1 - Math.exp(lnDistinct);
}

console.log('— A. two independent computations of P(n) agree —');
let maxDiff = 0;
for (let n = 1; n <= 100; n++) maxDiff = Math.max(maxDiff, Math.abs(pAny(n) - pAnyLog(n)));
ok('product formula and log-gamma route agree to <1e-12 for n=1..100', maxDiff < 1e-12, `maxΔ=${maxDiff.toExponential(2)}`);

console.log('\n— B. the landmarks, and that 23 is the FIRST crossing of 1/2 —');
ok('P(23) ≈ 0.5073', Math.abs(pAny(23) - 0.5073) < 5e-4, `P(23)=${pAny(23).toFixed(4)}`);
ok('P(22) < 1/2 < P(23) (23 is the threshold)', pAny(22) < 0.5 && pAny(23) > 0.5, `P(22)=${pAny(22).toFixed(4)} P(23)=${pAny(23).toFixed(4)}`);
ok('P(57) ≈ 0.99', Math.abs(pAny(57) - 0.9901) < 5e-4, `P(57)=${pAny(57).toFixed(4)}`);
ok('P(70) ≈ 0.9992', Math.abs(pAny(70) - 0.99916) < 5e-4, `P(70)=${pAny(70).toFixed(5)}`);
ok('P(366) = 1 exactly (pigeonhole)', pAny(366) === 1, `P(366)=${pAny(366)}`);
// the first n with P(n) ≥ 1/2, found by scanning
let firstCross = 0; for (let n = 1; n <= N; n++) { if (pAny(n) >= 0.5) { firstCross = n; break; } }
ok('first n with P(n) ≥ 1/2 is exactly 23', firstCross === 23, `n=${firstCross}`);
// √(2 ln2 · N) approximation to the crossing
const approxCross = Math.sqrt(2 * Math.log(2) * N);
ok('crossing ≈ √(2 ln2 · 365) ≈ 22.5', Math.abs(approxCross - 22.49) < 0.1, `≈${approxCross.toFixed(2)}`);

console.log('\nC. seeded Monte-Carlo checks P(n) at n=10,23,40');
// mulberry32 — deterministic, so this check 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; }; }
function monteCarlo(n, trials, seed) {
  const rnd = mulberry32(seed); let hit = 0;
  for (let t = 0; t < trials; t++) {
    const seen = new Uint8Array(N); let coll = false;
    for (let i = 0; i < n; i++) { const d = (rnd() * N) | 0; if (seen[d]) { coll = true; break; } seen[d] = 1; }
    if (coll) hit++;
  }
  return hit / trials;
}
for (const n of [10, 23, 40]) {
  const est = monteCarlo(n, 200000, 12345 + n), exact = pAny(n);
  ok(`Monte-Carlo (200k rooms) matches P(${n}) within 0.005`, Math.abs(est - exact) < 0.005, `sim=${est.toFixed(4)} exact=${exact.toFixed(4)}`);
}

console.log('\n— D. the intuition trap: "someone shares YOUR birthday" needs 253 —');
const pYou = (n) => 1 - Math.pow(364 / 365, n);
ok('P_you(23) is only ≈ 6.1% (vs 50.7% for any pair)', Math.abs(pYou(23) - 0.0613) < 5e-4, `P_you(23)=${pYou(23).toFixed(4)}`);
ok('P_you crosses 1/2 first at n = 253', pYou(252) < 0.5 && pYou(253) > 0.5, `P_you(252)=${pYou(252).toFixed(4)} P_you(253)=${pYou(253).toFixed(4)}`);
// exact mean number of people until the first collision:  E = Σ_{n≥0} P(distinct in first n)
// = 1 + Σ_{k=1}^{N} N!/((N−k)!·N^k)   (a standard identity; ≈ 24.6 for N=365)
let mean = 1, term = 1;
for (let k = 1; k <= N; k++) { term *= (N - k + 1) / N; mean += term; }
ok('exact mean people until first collision ≈ 24.6', Math.abs(mean - 24.6166) < 0.01, `E=${mean.toFixed(4)}`);

// --- emit the curve the page plots (single source of truth for the landmarks) ---
const curve = [];
for (let n = 1; n <= 80; n++) curve.push({ n, pAny: +pAny(n).toFixed(6), pYou: +pYou(n).toFixed(6) });
writeFileSync(join(here, 'curve.json'), JSON.stringify({
  generatedBy: 'research/the-birthday-problem/verify.mjs',
  days: N,
  landmarks: { firstCross50: firstCross, p23: +pAny(23).toFixed(4), p57: +pAny(57).toFixed(4), p70: +pAny(70).toFixed(5), youCross50: 253, meanToFirst: +mean.toFixed(2) },
  curve,
}, null, 2));
console.log('\nwrote curve.json');

console.log(`\n${fails === 0 ? '✓ all checks passed' : '✗ ' + fails + ' FAILED'}`);
process.exit(fails === 0 ? 0 : 1);
