import assert from 'node:assert/strict';

const DEFAULT_R0 = 2;
const SARS_K = 0.16;
const SARS_K_CI90 = [0.11, 0.64];
const PAGE_SIMULATIONS = 2500;
const SIMULATIONS = 30000;
const OUTBREAK_CAP = 4096;
const GENERATION_CAP = 80;

function logGamma(z) {
  const p = [
    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.log(Math.sin(Math.PI * z)) - logGamma(1 - z);
  }
  z -= 1;
  let x = p[0];
  for (let i = 1; i < p.length; i += 1) x += p[i] / (z + i);
  const t = z + p.length - 1.5;
  return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
}

function regularizedGammaP(a, x) {
  if (!(a > 0) || x < 0) throw new RangeError('regularizedGammaP domain error');
  if (x === 0) return 0;
  if (!Number.isFinite(x)) return 1;
  const gln = logGamma(a);
  if (x < a + 1) {
    let ap = a;
    let sum = 1 / a;
    let del = sum;
    for (let n = 1; n <= 10000; n += 1) {
      ap += 1;
      del *= x / ap;
      sum += del;
      if (Math.abs(del) < Math.abs(sum) * 1e-14) {
        return sum * Math.exp(-x + a * Math.log(x) - gln);
      }
    }
  } else {
    let b = x + 1 - a;
    let c = 1 / Number.MIN_VALUE;
    let d = 1 / b;
    let h = d;
    for (let i = 1; i <= 10000; i += 1) {
      const an = -i * (i - a);
      b += 2;
      d = an * d + b;
      if (Math.abs(d) < Number.MIN_VALUE) d = Number.MIN_VALUE;
      c = b + an / c;
      if (Math.abs(c) < Number.MIN_VALUE) c = Number.MIN_VALUE;
      d = 1 / d;
      const del = d * c;
      h *= del;
      if (Math.abs(del - 1) < 1e-14) {
        return 1 - Math.exp(-x + a * Math.log(x) - gln) * h;
      }
    }
  }
  throw new Error('regularizedGammaP failed to converge');
}

function gammaQuantile(probability, shape, scale) {
  assert(probability > 0 && probability < 1);
  let lo = 0;
  let hi = Math.max(scale, shape * scale);
  while (regularizedGammaP(shape, hi / scale) < probability) hi *= 2;
  for (let i = 0; i < 100; i += 1) {
    const mid = (lo + hi) / 2;
    if (regularizedGammaP(shape, mid / scale) < probability) lo = mid;
    else hi = mid;
  }
  return (lo + hi) / 2;
}

function pgfNegativeBinomial(s, mean, k) {
  return Math.pow(1 + mean * (1 - s) / k, -k);
}

function pgfPoisson(s, mean) {
  return Math.exp(-mean * (1 - s));
}

function solveExtinction(pgf, mean) {
  if (mean <= 1) return 1;
  let q = 0;
  for (let i = 0; i < 100000; i += 1) {
    const next = pgf(q);
    if (Math.abs(next - q) < 1e-14) return next;
    q = next;
  }
  throw new Error('extinction fixed point failed to converge');
}

function negativeBinomialExtinction(mean, k) {
  return solveExtinction((s) => pgfNegativeBinomial(s, mean, k), mean);
}

function poissonExtinction(mean) {
  return solveExtinction((s) => pgfPoisson(s, mean), mean);
}

function topShare(topFraction, mean, k) {
  const scale = mean / k;
  const cutoff = gammaQuantile(1 - topFraction, k, scale);
  const lowerMeanShare = regularizedGammaP(k + 1, cutoff / scale);
  return {
    cutoff,
    share: 1 - lowerMeanShare
  };
}

function targetedPolicy(mean, k, effort) {
  assert(effort >= 0 && effort <= 0.4);
  const shape = k;
  const scale = mean / k;
  const rate = 1 / scale;
  const cutoff = gammaQuantile(0.8, shape, scale);
  const pBottom = effort / 1.6;
  const pTop = 4 * pBottom;
  const lowerMean = mean * regularizedGammaP(shape + 1, rate * cutoff);
  const upperMean = mean - lowerMean;
  const effectiveMean = mean - pBottom * lowerMean - pTop * upperMean;

  function pgf(s) {
    const t = 1 - s;
    const laplace = Math.pow(rate / (rate + t), shape);
    const lowerLaplace = laplace * regularizedGammaP(shape, (rate + t) * cutoff);
    return effort + (1 - pTop) * laplace + (pTop - pBottom) * lowerLaplace;
  }

  return { cutoff, pBottom, pTop, effectiveMean, pgf };
}

function controlComparison(mean, k, effort) {
  const basePgf = (s) => pgfNegativeBinomial(s, mean, k);
  const populationMean = (1 - effort) * mean;
  const qPopulationAfterControl = solveExtinction(
    (s) => pgfNegativeBinomial(s, populationMean, k),
    populationMean
  );
  const targeted = targetedPolicy(mean, k, effort);
  const qTargetedAfterControl = solveExtinction(targeted.pgf, targeted.effectiveMean);

  return {
    populationMean,
    targetedMean: targeted.effectiveMean,
    pBottom: targeted.pBottom,
    pTop: targeted.pTop,
    qPopulation: basePgf(qPopulationAfterControl),
    qTargeted: basePgf(qTargetedAfterControl)
  };
}

function mulberry32(seed) {
  let a = seed >>> 0;
  return function random() {
    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 sampleNormal(random) {
  let u = 0;
  let v = 0;
  while (u === 0) u = random();
  while (v === 0) v = random();
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}

function sampleGamma(shape, scale, random) {
  if (shape < 1) {
    return sampleGamma(shape + 1, scale, random) * Math.pow(random(), 1 / shape);
  }
  const d = shape - 1 / 3;
  const c = 1 / Math.sqrt(9 * d);
  for (;;) {
    let x;
    let v;
    do {
      x = sampleNormal(random);
      v = 1 + c * x;
    } while (v <= 0);
    v *= v * v;
    const u = random();
    if (u < 1 - 0.0331 * x * x * x * x) return scale * d * v;
    if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return scale * d * v;
  }
}

function samplePoisson(lambda, random) {
  if (lambda < 30) {
    const limit = Math.exp(-lambda);
    let product = 1;
    let count = 0;
    do {
      count += 1;
      product *= random();
    } while (product > limit);
    return count - 1;
  }
  const sqrt = Math.sqrt(lambda);
  const b = 0.931 + 2.53 * sqrt;
  const a = -0.059 + 0.02483 * b;
  const inverseAlpha = 1.1239 + 1.1328 / (b - 3.4);
  const vr = 0.9277 - 3.6224 / (b - 2);
  for (;;) {
    const u = random() - 0.5;
    const v = random();
    const us = 0.5 - Math.abs(u);
    const k = Math.floor((2 * a / us + b) * u + lambda + 0.43);
    if (us >= 0.07 && v <= vr) return k;
    if (k < 0 || (us < 0.013 && v > us)) continue;
    const lhs = Math.log(v * inverseAlpha / (a / (us * us) + b));
    const rhs = -lambda + k * Math.log(lambda) - logGamma(k + 1);
    if (lhs <= rhs) return k;
  }
}

function sampleNegativeBinomial(mean, k, random) {
  return samplePoisson(sampleGamma(k, mean / k, random), random);
}

function simulateExtinction(mean, k, trials, seed) {
  const random = mulberry32(seed);
  let extinct = 0;
  let capped = 0;
  let totalSum = 0;
  for (let trial = 0; trial < trials; trial += 1) {
    let active = 1;
    let total = 1;
    for (let generation = 0; generation < GENERATION_CAP; generation += 1) {
      if (active === 0 || total >= OUTBREAK_CAP) break;
      active = sampleNegativeBinomial(active * mean, active * k, random);
      total += active;
    }
    if (active === 0) extinct += 1;
    else capped += 1;
    totalSum += Math.min(total, OUTBREAK_CAP);
  }
  return {
    estimate: extinct / trials,
    extinct,
    capped,
    meanViewedSize: totalSum / trials
  };
}

function close(actual, expected, tolerance, label) {
  assert(
    Math.abs(actual - expected) <= tolerance,
    `${label}: expected ${expected} within ${tolerance}, got ${actual}`
  );
}

console.log('The Average That Hides the Outbreak: independent verifier');
console.log(`Model mean R0 = ${DEFAULT_R0}`);
console.log('Offspring model: gamma mixed Poisson, exactly NegB(mean R0, dispersion k)');
console.log(`Variance formula at k = ${SARS_K}: ${DEFAULT_R0 + DEFAULT_R0 ** 2 / SARS_K}`);

const anchorKs = [50, 10, 1, 0.5, SARS_K, 0.1, 0.05];
const anchors = anchorKs.map((k) => ({
  k,
  p0: pgfNegativeBinomial(0, DEFAULT_R0, k),
  q: negativeBinomialExtinction(DEFAULT_R0, k)
}));
const poissonQ = poissonExtinction(DEFAULT_R0);

console.log(`Poisson limit extinction q: ${poissonQ.toFixed(9)}`);
for (const row of anchors) {
  console.log(`k=${row.k.toFixed(2)}  p0=${row.p0.toFixed(9)}  q=${row.q.toFixed(9)}`);
}

close(poissonQ, 0.20318786998, 1e-11, 'Poisson-limit fixed point');
close(anchors[0].q, 0.21181902745, 1e-9, 'k=50 fixed point');
close(anchors[4].q, 0.83730922030, 1e-9, 'k=0.16 fixed point');
close(anchors[6].q, 0.94146200724, 1e-9, 'k=0.05 fixed point');
for (let i = 1; i < anchors.length; i += 1) {
  assert(
    anchors[i].q > anchors[i - 1].q,
    `extinction must rise as k falls: ${anchors[i - 1].k} to ${anchors[i].k}`
  );
}
close(anchors[0].q, poissonQ, 0.01, 'k=50 should be close to the Poisson limit');

const tail = topShare(0.2, DEFAULT_R0, SARS_K);
console.log(
  `At R0=${DEFAULT_R0}, k=${SARS_K}, top 20% latent infectiousness cutoff: ${tail.cutoff.toFixed(9)}`
);
console.log(`At R0=${DEFAULT_R0}, k=${SARS_K}, top 20% share of expected transmission: ${(100 * tail.share).toFixed(6)}%`);
close(tail.cutoff, 2.289880700, 1e-9, 'top-20 cutoff');
close(tail.share, 0.88251921, 1e-8, 'top-20 expected transmission share');
assert(tail.share > 0.8, 'the top 20% should carry more than 80% at k=0.16');

const effort = 0.2;
const control = controlComparison(DEFAULT_R0, SARS_K, effort);
console.log(`Nominal control parameter c: ${(100 * effort).toFixed(0)}%`);
console.log('Population-wide delivery: every infected case has latent infectiousness multiplied by (1-c)');
console.log(`Targeted delivery: ${(100 * effort).toFixed(0)}% of infected cases are fully controlled on average`);
console.log(`Population-wide: R=${control.populationMean.toFixed(9)}, delayed extinction=${control.qPopulation.toFixed(9)}`);
console.log(`Fourfold top-20 targeting: p(bottom)=${control.pBottom.toFixed(9)}, p(top)=${control.pTop.toFixed(9)}`);
console.log(`Fourfold top-20 targeting: R=${control.targetedMean.toFixed(9)}, delayed extinction=${control.qTargeted.toFixed(9)}`);
close(control.populationMean, 1.6, 1e-12, 'population-wide effective R');
close(control.targetedMean, 1.088110596, 1e-9, 'targeted effective R');
close(control.qPopulation, 0.866576703, 1e-9, 'population-wide delayed extinction');
close(control.qTargeted, 0.975350597, 1e-9, 'targeted delayed extinction');
assert(control.targetedMean < control.populationMean, 'targeting must lower effective R more at the same nominal c');
assert(control.qTargeted > control.qPopulation, 'targeting must raise extinction probability at the same nominal c');

const controlGrid = [0.05, 0.1, 0.2, 0.3, 0.4].map((c) =>
  controlComparison(DEFAULT_R0, SARS_K, c)
);
for (let i = 1; i < controlGrid.length; i += 1) {
  assert(controlGrid[i].qPopulation >= controlGrid[i - 1].qPopulation - 1e-13);
  assert(controlGrid[i].qTargeted >= controlGrid[i - 1].qTargeted - 1e-13);
}

const simulations = [];
const pageSample = simulateExtinction(DEFAULT_R0, SARS_K, PAGE_SIMULATIONS, 0x51a7);
assert.equal(pageSample.extinct, 2096, 'default browser sample extinct count');
assert.equal(pageSample.capped, 404, 'default browser sample escaped count');
console.log(
  `Default browser sample: ${pageSample.extinct}/${PAGE_SIMULATIONS} extinct, estimate=${pageSample.estimate.toFixed(6)}, capped=${pageSample.capped}`
);
for (const [index, k] of [50, SARS_K, 0.05].entries()) {
  const simulated = simulateExtinction(DEFAULT_R0, k, SIMULATIONS, 0x51a7 + index);
  const exact = negativeBinomialExtinction(DEFAULT_R0, k);
  console.log(
    `Simulation k=${k}: ${simulated.extinct}/${SIMULATIONS} extinct, estimate=${simulated.estimate.toFixed(6)}, exact=${exact.toFixed(6)}, capped=${simulated.capped}`
  );
  close(simulated.estimate, exact, 0.012, `seeded simulation at k=${k}`);
  simulations.push(simulated);
}
assert(simulations[0].estimate < simulations[1].estimate);
assert(simulations[1].estimate < simulations[2].estimate);

assert.equal(SARS_K, 0.16);
assert.deepEqual(SARS_K_CI90, [0.11, 0.64]);
console.log(
  'Source-locked empirical value, not recomputed here: SARS Singapore full-data MLE k=0.16, bias-corrected non-parametric bootstrap 90% CI 0.11 to 0.64.'
);
console.log(
  `Simulation definition: extinction before ${OUTBREAK_CAP.toLocaleString('en-US')} viewed cases or ${GENERATION_CAP} generations; analytic q has no such cap.`
);
console.log('PASS: fixed points, monotonicity, tail share, both control curves, and seeded simulations agree.');
