// verify-the-banned-question.mjs — recompute the computed numbers shown on
// /strata/the-banned-question/ from first principles, all but the illustrative
// heart-rate swing in bpm, which it does not compute. Plain node, no deps.
// Figures quoted from the studies (917, 72%, 0.45/0.60, n=11 ...) are
// hard-coded constants copied from the papers; this script does not check them.
//
//   run:  node research/the-banned-question/verify-the-banned-question.mjs
//
// The page replaces the banned "origin of language" question with three
// checkable ones. This script regenerates the exact numbers each instrument
// displays, using the SAME functions the page's JavaScript uses:
//
//   1. bouba/kiki — the reader's score is scored against the exact binomial
//      null P(X >= k | n=6, p=0.5); the full N=6 table must sum to 1, and the
//      cohort line is a naive pooled z-test (72% of 917 vs chance, treating
//      all 917 as one sample; the paper's own model gives a 95% CrI of 56-82%).
//   2. cry contour — the German/French pitch envelopes' peaks (argmax) must
//      land at the reported 0.45 / 0.60 of the cry's length (Mampe's
//      normalised time, not seconds), German before the 0.5 midpoint and
//      French after it, each contour a single rise-then-fall arc.
//   3. entrainment — Vickhoff's 2/4/8-bar phrases, worked from the paper's
//      own bar length (5.156 s per two bars at 93 bpm), give 0.194/0.097/0.048
//      Hz, shown rounded as 0.2/0.1/0.05 Hz -> 12/6/3 bpm; the RSA resonance
//      gain peaks at 0.100 Hz.
//
// Plus internal-consistency checks that restate sourced constants (Mampe
// n=60=30+30, etc.); they do not check them against the sources.
// Citations for every constant are in README.md.

let pass = 0, total = 0;
const approx = (a, b, eps) => Math.abs(a - b) <= eps;
function ok(name, cond, extra = '') {
  total++;
  if (cond) pass++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
}

// ─────────────────────────────────────────────────────────────────────────
// shared math — identical to the page
// ─────────────────────────────────────────────────────────────────────────
function choose(n, k) {
  if (k < 0 || k > n) return 0;
  k = Math.min(k, n - k);
  let r = 1;
  for (let i = 0; i < k; i++) r = r * (n - i) / (i + 1);
  return r;
}
const binomPMF = (k, n, p) => choose(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);
function binomTailGE(k, n, p) { let s = 0; for (let i = k; i <= n; i++) s += binomPMF(i, n, p); return s; }
const zProp = (phat, n, p0) => (phat - p0) / Math.sqrt(p0 * (1 - p0) / n);

console.log('\n── 1 · bouba/kiki — binomial null (n=6, p=0.5) ─────────────────');

// full pmf table must sum to 1
let sum = 0;
for (let k = 0; k <= 6; k++) sum += binomPMF(k, 6, 0.5);
ok('binomial pmf table sums to 1', approx(sum, 1, 1e-12), `Σ = ${sum.toFixed(12)}`);

// exact /64 fractions the page prints
const denom = 64; // 2^6
const expect = { 6: 1, 5: 7, 4: 22, 3: 42, 2: 57, 1: 63, 0: 64 }; // numerators of P(X>=k)*64
for (let k = 6; k >= 0; k--) {
  const tail = binomTailGE(k, 6, 0.5);
  const num = Math.round(tail * denom);
  ok(`P(X>=${k}) = ${num}/64`, num === expect[k] && approx(tail, expect[k] / denom, 1e-12),
    `= ${tail.toFixed(4)}`);
}
// the two headline cases the page narrates
ok('perfect 6/6 tail = 1/64 ≈ 1.56%', approx(binomTailGE(6, 6, 0.5), 1 / 64, 1e-12),
  `${(binomTailGE(6,6,0.5)*100).toFixed(2)}%`);
ok('5/6 tail = 7/64 ≈ 10.9%', approx(binomTailGE(5, 6, 0.5), 7 / 64, 1e-12),
  `${(binomTailGE(5,6,0.5)*100).toFixed(2)}%`);

console.log('\n── 1b · Ćwiek 2022 cohort — naive pooled z-test vs chance ─────');
// Treats all 917 as one sample. The paper's mixed model (which allows for
// differences between languages) gives 72%, 95% CrI 56-82%, p(b0 > 0) = 0.99.
const zCohort = zProp(0.72, 917, 0.5);
ok('z(72% of 917 vs 50%) ≈ 13.3', approx(zCohort, 13.32, 0.05), `z = ${zCohort.toFixed(2)}`);
ok('cohort z is far beyond p<0.001 (|z|>3.29)', Math.abs(zCohort) > 3.29, `|z| = ${zCohort.toFixed(2)}`);
ok('Roman 75% and non-Roman 63% both above chance 50%', 0.75 > 0.5 && 0.63 > 0.5);
// internal consistency of reported cohort counts
ok('Ćwiek cohort integers (917 participants, 25 languages, 9 families, 10 scripts) are the shown values',
  917 === 917 && 25 === 25 && 9 === 9 && 10 === 10);

console.log('\n── 2 · newborn cry contour — peaks by argmax ──────────────────');
// Mampe 2009 reports t_norm(F0max): where the pitch peak falls once each melody
// arc is stretched to length 1 (medians 0.45 German, 0.60 French; < 0.5 is a
// "falling contour", > 0.5 a "rising contour"). These are fractions of the cry,
// not seconds, and every arc analysed rises and then falls.
const D = 1.2; // playback length of the synthesized cry (s), same as page; ours, not the study's
const PEAK = { de: 0.45, fr: 0.60 };
function env(lang, t) {
  const x = Math.min(Math.max(t / D, 0), 1), p = PEAK[lang], a = 3 * p, b = 3 * (1 - p);
  const base = 0.20, amp = 0.68;
  return base + amp * Math.pow(x, a) * Math.pow(1 - x, b) / (Math.pow(p, a) * Math.pow(1 - p, b));
}
function argmaxPeak(lang) {
  let best = -Infinity, bt = 0, steps = 600;
  for (let i = 0; i <= steps; i++) { const t = i / steps * D, v = env(lang, t); if (v > best) { best = v; bt = t; } }
  return bt;
}
const deFrac = argmaxPeak('de') / D, frFrac = argmaxPeak('fr') / D;
ok('German contour peaks 0.45 of the way through the cry', approx(deFrac, 0.45, 0.01), `argmax/D = ${deFrac.toFixed(3)}`);
ok('French contour peaks 0.60 of the way through the cry', approx(frFrac, 0.60, 0.01), `argmax/D = ${frFrac.toFixed(3)}`);
ok('German peak is EARLIER than French peak', deFrac < frFrac, `${deFrac.toFixed(2)} < ${frFrac.toFixed(2)}`);
// the paper's own split: peak before the midpoint = falling type, after = rising type
ok('German peak before the 0.5 midpoint (falling type), French after it (rising type)',
  deFrac < 0.5 - 0.02 && frFrac > 0.5 + 0.02, `${deFrac.toFixed(3)} < 0.5 < ${frFrac.toFixed(3)}`);
// each contour is a single rise-then-fall arc: non-decreasing to the peak, non-increasing after
function singleArc(lang) {
  const steps = 600, pk = Math.round(argmaxPeak(lang) / D * steps);
  for (let i = 0; i < steps; i++) {
    const d = env(lang, (i + 1) / steps * D) - env(lang, i / steps * D);
    if (i < pk && d < 0) return false;
    if (i >= pk && d > 0) return false;
  }
  return pk > 0 && pk < steps;
}
ok('both contours rise and then fall (one arc each, no net-trend model)', singleArc('de') && singleArc('fr'));
// n = 60 = 30 French + 30 German
ok('Mampe sample: 30 + 30 = 60 newborns', 30 + 30 === 60);

console.log('\n── 3 · respiratory entrainment — Vickhoff map & RSA resonance ─');
// phrase -> frequency -> bpm map, worked from the paper's own bar length:
// "The tempo 93 bpm means that two bars take 5.156 s, which invites singers to a
// 0.194 Hz respiration rate. Four bars take 10.312 (0.097 respiration rate)."
// The hymn was sung "with free, unguided breathing": the phrases invite these
// rates, they do not force them. The page shows them ROUNDED to 0.2/0.1/0.05 Hz.
const barSec = 5.156 / 2;                 // one bar at 93 bpm (Vickhoff 2013, Fig. 1)
const bars = [2, 4, 8];
const hzRounded = [0.2, 0.1, 0.05];       // as printed on the page
const bpmExpected = [12, 6, 3];
const paperHz = { 2: 0.194, 4: 0.097 };   // the paper's own figures
const phraseHz = (b) => 1 / (b * barSec);
bars.forEach((b, i) => {
  const hz = phraseHz(b);
  const matchesPaper = paperHz[b] === undefined || approx(hz, paperHz[b], 0.0005);
  ok(`${b}-bar phrase -> ${hz.toFixed(3)} Hz, shown rounded as ${hzRounded[i]} Hz -> ${bpmExpected[i]} breaths/min`,
    matchesPaper && approx(hz, hzRounded[i], 0.01) && approx(hzRounded[i] * 60, bpmExpected[i], 1e-9),
    `${(hz * 60).toFixed(2)}/min unrounded`);
});
ok('halving the phrase doubles the frequency (8→4→2 bars)',
  approx(phraseHz(4) / phraseHz(8), 2, 1e-12) && approx(phraseHz(2) / phraseHz(4), 2, 1e-12));

// RSA resonance gain — identical model to the page
const F0 = 0.10, Q = 1.9;
const rsaGain = (f) => 1 / Math.sqrt(1 + Q * Q * Math.pow(f / F0 - F0 / f, 2));
// argmax over the slider's bpm range (3..20 in 0.5 steps -> f = bpm/60)
let bestG = -Infinity, bestBpm = 0;
for (let bpm = 3; bpm <= 20; bpm += 0.5) { const g = rsaGain(bpm / 60); if (g > bestG) { bestG = g; bestBpm = bpm; } }
ok('RSA gain peaks at 6.0 breaths/min (0.100 Hz)', approx(bestBpm, 6.0, 1e-9), `argmax at ${bestBpm.toFixed(1)}/min`);
ok('RSA gain at resonance = 1.0 (normalised max)', approx(rsaGain(F0), 1, 1e-12), `gain(0.1 Hz) = ${rsaGain(F0).toFixed(4)}`);
ok('RSA gain falls off away from resonance (12/min < 6/min)', rsaGain(12/60) < rsaGain(6/60),
  `${rsaGain(12/60).toFixed(2)} < ${rsaGain(6/60).toFixed(2)}`);
// 0.1 Hz baroreflex resonance == 6 breaths/min (the six-breaths link)
ok('0.100 Hz baroreflex resonance = 6 breaths/min', approx(0.1 * 60, 6, 1e-9));

console.log('\n── 4 · sourced constants — internal consistency ───────────────');
ok('ban approved 8 March 1866; Descent of Man 1871 → 5 years later, inquiry continued',
  1871 - 1866 === 5);
ok('Vickhoff group analysis n=11 of 15 recorded (4 excluded)', 15 - 4 === 11);

// ─────────────────────────────────────────────────────────────────────────
console.log(`\n${pass}/${total} PASS`);
process.exit(pass === total ? 0 : 1);
