// Verifier for "The Vowel in the Tube" — every claim the page makes, checked
// from first principles + the raw Peterson & Barney (1952) data.
// Run: node research/the-vowel-in-the-tube/verify.mjs   (exit 0 = all pass)
//
// The page and this file import the SAME physics (tube.mjs). What we check:
//   1. uniform tube closed-open -> schwa formants (2n-1)c/4L
//   2. the transfer-matrix engine reproduces that closed form
//   3. the two-tube closed form == the general N-section engine
//   4. formants scale exactly as 1/L (length = speaker size)
//   5. EMPIRICAL: women/men & child/men formant ratios (recomputed from the
//      1520-row source) are near-constant across F1/F2/F3 and recover sane
//      tract lengths -- the 1/L law, read out of real voices
//   6. one constriction already swings the tube toward a real corner vowel
//   7. the perturbation law: a squeeze near the glottis raises F1, near the
//      lips lowers it (Chiba-Kajiyama node/antinode rule)
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { m22, formants, uniformFormants, twoTube, C_DEFAULT } from './tube.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PB = JSON.parse(fs.readFileSync(path.join(HERE, 'pb_means.json'), 'utf8'));
const cm = (x) => x / 100;

let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function ok(name, cond, detail = '') {
  (cond ? pass++ : fail++);
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  — ' + detail : ''}`);
}

// ── 1. uniform tube -> the schwa ──────────────────────────────────────────
const L = cm(17.5), c = C_DEFAULT;
const schwa = uniformFormants(L, { n: 3 }).map((x) => Math.round(x));
ok('1. uniform 17.5cm tube -> ~490/1470/2450 (the schwa)',
   schwa[0] === 490 && schwa[1] === 1470 && schwa[2] === 2450,
   `predicted ${schwa.join('/')} Hz; measured neutral vowel ~500/1500/2500`);

// 1b. closeness to the MEASURED schwa-like vowels (P&B has no plain /ə/; the
// rhotic /ɝ/ "heard" 489/1360 and /ʌ/ "hud" are the nearest neutral tokens).
const er = PB.groups.men.vowels.find((v) => v.ipa === 'ɝ');
ok('1b. prediction sits among the measured central vowels',
   Math.abs(schwa[0] - er.f1) < 60,
   `predicted F1 ${schwa[0]} vs measured /ɝ/ F1 ${er.f1}`);

// ── 2. engine reproduces the closed form ──────────────────────────────────
let maxErr = 0;
for (const Lc of [0.12, 0.155, 0.175, 0.20]) {
  const eng = formants([{ l: Lc, A: 5 }], { n: 3, step: 0.5 });
  const cf = uniformFormants(Lc, { n: 3 });
  for (let i = 0; i < 3; i++) maxErr = Math.max(maxErr, Math.abs(eng[i] - cf[i]) / cf[i]);
}
ok('2. transfer-matrix engine == (2n-1)c/4L for uniform tubes',
   maxErr < 0.002, `max relative error ${(maxErr * 100).toFixed(3)}%`);

// ── 3. two-tube closed form == general engine ─────────────────────────────
// closed form M22 = cos(k lb)cos(k lf) - (Ab/Af) sin(k lb) sin(k lf)
let cfErr = 0;
const lb = cm(9), Ab = 1, lf = cm(8.5), Af = 7;
for (let f = 100; f <= 4000; f += 37) {
  const k = (2 * Math.PI * f) / c;
  const closed = Math.cos(k * lb) * Math.cos(k * lf)
               - (Ab / Af) * Math.sin(k * lb) * Math.sin(k * lf);
  const eng = m22([{ l: lb, A: Ab }, { l: lf, A: Af }], f, c);
  cfErr = Math.max(cfErr, Math.abs(closed - eng));
}
ok('3. two-tube closed form == general N-section engine',
   cfErr < 1e-9, `max |Δ M22| = ${cfErr.toExponential(2)}`);

// ── 4. exact 1/L scaling ──────────────────────────────────────────────────
const fL = formants([{ l: cm(15), A: 4 }], { n: 3, step: 0.5 });
const f2L = formants([{ l: cm(30), A: 4 }], { n: 3, step: 0.5 });
let scaleErr = 0;
for (let i = 0; i < 3; i++) scaleErr = Math.max(scaleErr, Math.abs(fL[i] - 2 * f2L[i]) / fL[i]);
ok('4. halving tube length doubles every formant (f ∝ 1/L)',
   scaleErr < 0.002, `max deviation ${(scaleErr * 100).toFixed(3)}%`);

// ── 5. the 1/L law, read out of real voices ───────────────────────────────
const groups = PB.groups;
function ratio(aV, bV) {
  const r = [];
  aV.forEach((v, i) => { r.push(bV[i].f1 / v.f1, bV[i].f2 / v.f2, bV[i].f3 / v.f3); });
  return r.reduce((x, y) => x + y, 0) / r.length;
}
function spread(aV, bV) { // are F1/F2/F3 ratios near-equal? (uniform-scaling test)
  const m = (sel) => aV.reduce((s, v, i) => s + bV[i][sel] / v[sel], 0) / aV.length;
  const rs = [m('f1'), m('f2'), m('f3')];
  return (Math.max(...rs) - Math.min(...rs)) / (rs.reduce((a, b) => a + b) / 3);
}
const rW = ratio(groups.men.vowels, groups.women.vowels);
const rC = ratio(groups.men.vowels, groups.children.vowels);
const spW = spread(groups.men.vowels, groups.women.vowels);
ok('5a. women/men formant ratio ≈ 1.16 (women tract ~15cm)',
   approx(rW, 1.165, 0.03), `ratio ${rW.toFixed(3)} → tract ${(17.5 / rW).toFixed(1)}cm`);
ok('5b. child/men formant ratio ≈ 1.35 (child tract ~13cm)',
   approx(rC, 1.356, 0.04), `ratio ${rC.toFixed(3)} → tract ${(17.5 / rC).toFixed(1)}cm`);
ok('5c. the ratio is near-constant across F1/F2/F3 (the scaling IS uniform-ish)',
   spW < 0.05, `women F1..F3 spread ${(spW * 100).toFixed(1)}% (residual = tract isn\'t perfectly scaled)`);

// ── 6. one squeeze swings toward a real corner vowel (/ɑ/ "hod") ───────────
const aTube = twoTube(lb, Ab, lf, Af, { n: 3 }); // back-narrow, front-wide
const A = PB.groups.men.vowels.find((v) => v.ipa === 'ɑ');
ok('6. a back constriction lands the tube near measured /ɑ/',
   approx(aTube[0], A.f1, 0.10 * A.f1) && approx(aTube[1], A.f1 + (A.f2 - A.f1), 0.20 * A.f2),
   `two-tube ${Math.round(aTube[0])}/${Math.round(aTube[1])} vs measured /ɑ/ ${A.f1}/${A.f2}`);

// ── 7. Chiba-Kajiyama perturbation direction ──────────────────────────────
const base = formants(Array.from({ length: 7 }, () => ({ l: cm(2.5), A: 8 })), { n: 1 })[0];
const narrowAt = (idx) => {
  const s = Array.from({ length: 7 }, () => ({ l: cm(2.5), A: 8 })); s[idx].A = 1;
  return formants(s, { n: 1 })[0];
};
const f1Glottis = narrowAt(0), f1Lips = narrowAt(6);
ok('7. squeeze near glottis raises F1; squeeze near lips lowers it',
   f1Glottis > base && f1Lips < base,
   `F1: lips ${Math.round(f1Lips)} < neutral ${Math.round(base)} < glottis ${Math.round(f1Glottis)}`);

// ── the honest gap (stated, not tested) ───────────────────────────────────
console.log('\nNOTE (not machine-checkable): whether a rendered tone *sounds like*');
console.log('the intended vowel is a judgement only an ear can make. The verifier');
console.log('checks the physics and the data; your ear closes the loop.');

console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
