#!/usr/bin/env node
// verify-does-msg-cause-headaches.mjs
// Offline gate: recomputes every number shown on
// public/strata/does-msg-cause-headaches/index.html from the digitized
// systematic-review table (Obayashi & Nagamura, J Headache Pain 2016;17:54),
// plus the Kwok 1968 origin and the FDA/FASEB caveat. Exits 0 iff all pass.
//
// Data are TRANSCRIBED from the review's own tables (no fabricated curve):
//   WITH FOOD  (5 papers / 6 studies): 0 found more headache than placebo
//     (Zanda 1973 had a positive female-only subgroup; overall null).
//   WITHOUT FOOD in a drink (5 papers / 7 studies): 4 found a signal.
//   Geha 2000: 5 g fasting drink, 54% (MSG) vs 28% (placebo), P<0.005.
//   MSG is taste-detectable at >= 1.3% (2 g / 150 mL).

'use strict';

// ── the digitized studies ───────────────────────────────────────────────
const STUDIES = [
  // WITH FOOD
  { id:'prawiro',  ctx:'food',  dose:2.25, pos:false, msg:null, pla:null },
  { id:'tara-cap', ctx:'food',  dose:2.25, pos:false, msg:null, pla:null },
  { id:'tara-drk', ctx:'food',  dose:3.15, pos:false, msg:null, pla:null },
  { id:'tanpha',   ctx:'food',  dose:3.0,  pos:false, msg:null, pla:null },
  { id:'zanda',    ctx:'food',  dose:3.0,  pos:false, femaleSub:true, msg:null, pla:null },
  { id:'morselli', ctx:'food',  dose:3.0,  pos:false, msg:null, pla:null },
  // WITHOUT FOOD, in a drink
  { id:'geha',     ctx:'drink', dose:5.0,  pos:true,  msg:54, pla:28 },
  { id:'yang1',    ctx:'drink', dose:5.0,  pos:false, msg:null, pla:null },
  { id:'yang2',    ctx:'drink', dose:3.75, pos:true,  msg:null, pla:null }, // sig at 2.5 & 5.0 g
  { id:'shimada',  ctx:'drink', dose:9.0,  pos:true,  msg:null, pla:null }, // P=0.041
  { id:'baad45',   ctx:'drink', dose:4.5,  pos:true,  msg:null, pla:null }, // P=0.045
  { id:'baad9',    ctx:'drink', dose:9.0,  pos:false, msg:null, pla:null },
  { id:'rosen',    ctx:'drink', dose:8.5,  pos:false, msg:17, pla:8 },
];

// ── constants (all sourced) ──────────────────────────────────────────────
const SERVING_ML = 150;   // fixed drink serving (Geha basis)
const TASTE_PCT  = 1.3;   // MSG detectable at >= 1.3% (2 g / 150 mL)
const FASEB_DOSE = 3.0;   // g without food, sensitive-subset threshold
const MEAL_MSG   = 0.5;   // g added MSG in a heavily seasoned portion
const KWOK_CAUSES = 3;    // Kwok 1968 named 3 speculative causes (MSG one of them)

const concPct   = (doseG) => doseG / SERVING_ML * 100;
const tasteable = (doseG) => concPct(doseG) >= TASTE_PCT - 1e-9;

const food  = STUDIES.filter(s => s.ctx === 'food');
const drink = STUDIES.filter(s => s.ctx === 'drink');
const foodPos  = food.filter(s => s.pos).length;
const drinkPos = drink.filter(s => s.pos).length;

// ── check harness ─────────────────────────────────────────────────────────
let passed = 0, failed = 0;
function ok(name, cond, detail = '') {
  const s = cond ? 'PASS' : 'FAIL';
  if (cond) passed++; else failed++;
  console.log(`[${s}] ${name}${detail ? '  ->  ' + detail : ''}`);
}
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;

console.log('MSG headache verifier -- digitized from Obayashi & Nagamura 2016\n');

// 1. Kwok origin: MSG is one of three speculative causes.
ok('Kwok 1968 named exactly 3 speculative causes (MSG one of them)', KWOK_CAUSES === 3,
   'MSG + high sodium + cooking wine');

// 2. WITH FOOD: 6 studies, 0 positive overall.
ok('with-food study count = 6', food.length === 6, `${food.length}`);
ok('with-food positive count = 0', foodPos === 0, `${foodPos}`);
ok('the one female subgroup is flagged but overall-null (Zanda 1973)',
   food.some(s => s.femaleSub) && food.every(s => !s.pos), 'subgroup positive, overall null');

// 3. WITHOUT FOOD: 7 studies, 4 positive.
ok('without-food study count = 7', drink.length === 7, `${drink.length}`);
ok('without-food positive count = 4', drinkPos === 4, `${drinkPos}`);

// 4. Paper vs study bookkeeping: 5 papers each side.
//    with food: Tarasoff = 2 studies (1 paper) -> 5 papers; without food: Yang & Baad-Hansen = 2 studies each -> 5 papers.
const foodPapers  = new Set(food.map(s => s.id.split('-')[0].replace(/[0-9]/g,''))).size;
ok('with-food = 5 distinct papers, 6 studies', foodPapers === 5 && food.length === 6, `${foodPapers} papers`);
const drinkPapers = new Set(drink.map(s => s.id.replace(/[0-9]/g,''))).size; // baad,geha,rosen,shimada,yang
ok('without-food = 5 distinct papers, 7 studies', drinkPapers === 5 && drink.length === 7, `${drinkPapers} papers`);

// 5. Taste / blinding threshold, two ways.
//    (a) 2 g / 150 mL as a percent.
ok('2 g / 150 mL = 1.333% (matches review 1.3%)', approx(concPct(2), 1.3333, 0.005), `${concPct(2).toFixed(4)}%`);
//    (b) inverse: the dose that hits exactly 1.3% in 150 mL.
const doseAtThreshold = TASTE_PCT / 100 * SERVING_ML;
ok('threshold dose in 150 mL ≈ 1.95 g (≈ the review 2 g)', approx(doseAtThreshold, 1.95, 1e-9), `${doseAtThreshold} g`);

// 6. THE KEY CLAIM: every positive drink study is taste-detectable -> blinding broken.
const posDrink = drink.filter(s => s.pos);
const allPosTasteable = posDrink.every(s => tasteable(s.dose));
ok('EVERY positive drink study is taste-detectable (blinding compromised)', allPosTasteable,
   posDrink.map(s => `${s.id}:${concPct(s.dose).toFixed(2)}%`).join(' '));
//   two-way cross-check: the minimum positive-study dose still clears the taste line.
const minPosDose = Math.min(...posDrink.map(s => s.dose));
ok('smallest positive-study dose clears the taste line', concPct(minPosDose) >= TASTE_PCT,
   `min ${minPosDose} g = ${concPct(minPosDose).toFixed(2)}%`);

// 7. Geha 2000 gap, two ways: difference and ratio.
const geha = STUDIES.find(s => s.id === 'geha');
ok('Geha excess = 26 percentage points', (geha.msg - geha.pla) === 26, `${geha.msg} - ${geha.pla}`);
ok('Geha rate ratio = 1.93x', approx(geha.msg / geha.pla, 1.9286, 0.01), `${(geha.msg/geha.pla).toFixed(3)}x`);
ok('Geha was a fasting drink above the taste line', geha.ctx === 'drink' && tasteable(geha.dose),
   `${concPct(geha.dose).toFixed(2)}%`);

// 8. Rosenblum 1971 null gap (the published null with rates).
const rosen = STUDIES.find(s => s.id === 'rosen');
ok('Rosenblum excess = 9 pts but NOT significant (null)', (rosen.msg - rosen.pla) === 9 && !rosen.pos,
   `${rosen.msg} vs ${rosen.pla}`);

// 9. Dietary reality: a real meal dose is below the FASEB fasting threshold.
ok('a ~0.5 g meal dose is below the 3 g FASEB threshold', MEAL_MSG < FASEB_DOSE,
   `${MEAL_MSG} g < ${FASEB_DOSE} g`);
ok('at a dietary dose the drink would be sub-threshold (not tasteable)', !tasteable(MEAL_MSG),
   `${concPct(MEAL_MSG).toFixed(2)}% < ${TASTE_PCT}%`);

// 10. Honesty guards: the null is not a proof of safety.
ok('claim is a NULL, not "MSG proven inert" (positives are real, count = 4)', drinkPos > 0, `${drinkPos} real positives`);
ok('the honest split holds: with-food 0/6, without-food 4/7',
   foodPos === 0 && food.length === 6 && drinkPos === 4 && drink.length === 7,
   '0/6 vs 4/7');

// ── summary ─────────────────────────────────────────────────────────────
console.log(`\n${passed} passed, ${failed} failed.`);
process.exit(failed === 0 ? 0 : 1);
