#!/usr/bin/env node
// research/the-fittest-cannot-breed-true/verify.mjs
//
// The slug-named entry point for the check behind /strata/the-fittest-cannot-breed-true/.
//
//   node research/the-fittest-cannot-breed-true/verify.mjs
//
// ─── WHY THIS FILE EXISTS, STATED HONESTLY ──────────────────────────────────
// The page "The Fittest Cannot Breed True" shipped 2026-07-12 with a check panel
// and a working verifier, but that verifier lives at
// research/heterozygote-advantage/verify.mjs, which does not match the page's
// slug. A later audit read the missing research/the-fittest-cannot-breed-true/
// directory as "this page has no verifier at all". It was not true. What was
// true is that the check was hard to find from the page's own name.
//
// So this file does two things:
//   (1) re-runs the original verifier in place, requiring it to exit 0, so the
//       slug-named path is a real entry point and not a stub; and
//   (2) adds the check the original could NOT make, because the original is
//       entirely deterministic and infinite-population: the FINITE-population
//       statement that the heterozygote's fixation probability is exactly zero.
//
// (2) is the substantive addition. The deterministic recursion shows the
// population converges to a polymorphism, which tells you the heterozygote does
// not take over IN THAT MODEL. It cannot tell you what happens in a finite
// population, where anything with positive probability eventually happens. The
// finite answer turns out to be sharper, not weaker: for a finite population the
// genotype counts form a Markov chain whose absorbing set can be enumerated in
// full, and no absorbing state contains a heterozygote. Not "unlikely". Zero.
//
// Built for the portal /strata/what-selection-cannot-do/, which walks this page
// alongside the drift and Muller's ratchet under one engine.

'use strict';

import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok    ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${extra ? '   ' + extra : ''}`); }
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');

// ── (1) the original verifier, re-run in place ──────────────────────────────
console.log('\n1. THE ORIGINAL DETERMINISTIC CHECK (research/heterozygote-advantage/verify.mjs)');
{
  const target = path.join(REPO, 'research/heterozygote-advantage/verify.mjs');
  const r = spawnSync(process.execPath, [target], { encoding: 'utf8' });
  const tail = (r.stdout || '').trim().split('\n').slice(-2).join(' | ').trim();
  ok('the page\'s original verifier still passes', r.status === 0, tail.slice(0, 80));
}

// ── the free choices, named ─────────────────────────────────────────────────
// s = cost of malaria to AA, t = cost of anaemia to SS, heterozygote fixed at 1.
// Textbook estimates for holoendemic falciparum malaria. NOT constants of
// nature: malaria pressure varies enormously by region and era, and every
// equilibrium number below moves when these move. The zero does not.
const s = 0.12, t = 0.86;
const W = [1 - s, 1, 1 - t];

// ── (2) the finite-population statement, exact ──────────────────────────────
// State = (nAA, nAS, nSS) with nAA + nAS + nSS = N. Each of N offspring is drawn
// independently, so the next state is Multinomial(N; probs), where
//   Mendelian: parents are drawn proportional to fitness, each contributes ONE
//     random allele, so the gamete pool has A-frequency x and offspring
//     genotypes are (x², 2x(1-x), (1-x)²);
//   Clonal:    offspring are copies, so genotypes are (f_AA, f_AS, f_SS).
// Everything else is identical between the two.
console.log('\n2. THE FINITE-POPULATION STATEMENT (exact, by full enumeration)');

const lnF = [0];
const lnFact = (n) => { for (let i = lnF.length; i <= n; i++) lnF[i] = lnF[i - 1] + Math.log(i); return lnF[n]; };
function multinom(N, probs, cell) {
  let lp = lnFact(N);
  for (let j = 0; j < 3; j++) {
    if (cell[j] === 0) continue;
    if (probs[j] <= 0) return 0;
    lp += cell[j] * Math.log(probs[j]) - lnFact(cell[j]);
  }
  return Math.exp(lp);
}
function offspringProbs(st, mendelian) {
  const [a, h, b] = st;
  const T = a * W[0] + h * W[1] + b * W[2];
  if (T <= 0) return null;
  const f = [a * W[0] / T, h * W[1] / T, b * W[2] / T];
  if (!mendelian) return f;
  const x = f[0] + f[1] / 2;
  return [x * x, 2 * x * (1 - x), (1 - x) * (1 - x)];
}
function buildChain(N, mendelian) {
  const list = [], index = new Map();
  for (let a = 0; a <= N; a++) for (let h = 0; h + a <= N; h++) {
    index.set(a * (N + 1) + h, list.length); list.push([a, h, N - a - h]);
  }
  const M = list.map((st) => {
    const probs = offspringProbs(st, mendelian);
    const row = new Float64Array(list.length);
    if (!probs) { row[index.get(st[0] * (N + 1) + st[1])] = 1; return row; }
    for (let j = 0; j < list.length; j++) row[j] = multinom(N, probs, list[j]);
    return row;
  });
  return { list, index, M };
}
const absorbing = (c) => c.M.map((row, i) => (row[i] > 1 - 1e-12 ? i : -1)).filter((i) => i >= 0);

for (const N of [5, 10, 15, 20]) {
  const men = buildChain(N, true);
  const abs = absorbing(men);
  const allAS = men.index.get(0 * (N + 1) + N);
  const names = abs.map((i) => {
    const st = men.list[i]; return st[0] === N ? 'all AA' : st[1] === N ? 'all AS' : 'all SS';
  });
  ok(`N=${String(N).padStart(2)}: absorbing set = {${names.join(', ')}}; heterozygotes in each = 0`,
     abs.length === 2 && abs.every((i) => men.list[i][1] === 0) && !abs.includes(allAS));
}
// each row of the chain is a genuine probability distribution (the enumeration is complete)
{
  const men = buildChain(12, true);
  let worst = 0;
  for (const row of men.M) { let sum = 0; for (let j = 0; j < row.length; j++) sum += row[j]; worst = Math.max(worst, Math.abs(sum - 1)); }
  ok(`N=12: every transition row sums to 1 (max deviation ${worst.toExponential(2)}), so no state is missing`, worst < 1e-12);
}
// the all-heterozygote state is transient, and its exit law is the Punnett square
for (const N of [4, 10, 20]) {
  const probs = offspringProbs([0, N, 0], true);
  ok(`N=${String(N).padStart(2)}: from all-AS the offspring law is exactly (1/4, 1/2, 1/4)`,
     near(probs[0], 0.25, 1e-15) && near(probs[1], 0.5, 1e-15) && near(probs[2], 0.25, 1e-15));
}
{
  const N = 10, men = buildChain(N, true);
  const allAS = men.index.get(0 * (N + 1) + N);
  let eHet = 0;
  for (let j = 0; j < men.list.length; j++) eHet += men.M[allAS][j] * men.list[j][1];
  ok(`N=${N}: one generation of the fittest x the fittest leaves E[AS] = ${(eHet / N).toFixed(6)} = exactly 1/2`,
     near(eHet / N, 0.5, 1e-12));
  ok(`N=${N}: P(an all-AS population survives one generation) = 2^-N = ${Math.pow(2, -N).toExponential(3)}`,
     near(men.M[allAS][allAS], Math.pow(2, -N), 1e-15));
}
// the ceiling: 2pq never exceeds 1/2
{
  let best = 0;
  for (let i = 0; i <= 200000; i++) { const p = i / 200000; best = Math.max(best, 2 * p * (1 - p)); }
  ok(`max heterozygote frequency under random mating = ${best.toFixed(6)} (exactly 1/2)`, near(best, 0.5, 1e-9));
}
// and the counterfactual that isolates the culprit: clone instead of mate, and
// the SAME fitnesses make the all-AS state absorbing.
{
  const N = 10, clo = buildChain(N, false);
  const abs = absorbing(clo);
  const allAS = clo.index.get(0 * (N + 1) + N);
  ok(`N=${N} clonal: the same fitnesses give 3 absorbing states, INCLUDING all-AS`,
     abs.length === 3 && abs.includes(allAS));
  ok('so the obstruction is segregation, not selection: only the transmission rule changed',
     true);
}

// ── (3) the numbers the page displays, at the named free choice ─────────────
console.log(`\n3. THE PAGE'S DISPLAYED NUMBERS at s = ${s}, t = ${t}`);
{
  const q = s / (s + t), p = 1 - q;
  const L = (s * t) / (s + t);
  ok(`q* = s/(s+t) = ${q.toFixed(6)} (page says "about 0.12")`, near(q, 0.122449, 1e-6));
  ok(`carriers 2p*q* = ${(2 * p * q).toFixed(6)} (page says "about one in five")`, near(2 * p * q, 0.214910, 1e-5));
  ok(`SS births q*^2 = ${(q * q).toFixed(6)} = 1 in ${Math.round(1 / (q * q))} (page says "one birth in 67")`,
     Math.round(1 / (q * q)) === 67);
  ok(`segregation load st/(s+t) = ${L.toFixed(6)} (page says "10.5%")`, near(L, 0.105306, 1e-6));
  ok(`mean fitness at q* = ${(1 - L).toFixed(6)}`, near(1 - L, 0.894694, 1e-6));
  ok('a clonal all-AS population would have mean fitness exactly 1, so the load is the price of meiosis',
     W[1] === 1);
}

console.log('\n' + '─'.repeat(66));
console.log(`${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('FAILED.'); process.exit(1); }
console.log('All checks passed.');
process.exit(0);
