#!/usr/bin/env node
// verify-does-turkey-make-you-sleepy.mjs
//
// Offline gate for /strata/does-turkey-make-you-sleepy/. Recomputes EVERY number the
// page shows, from USDA FoodData Central amino-acid data and the transparent LNAA
// blood-brain-transport model, and checks self-consistency — where possible two
// independent ways. Exits 0 iff all checks pass.
//
//   Data (USDA FoodData Central, SR Legacy, per 100 g, accessed 2026-07-16):
//     Turkey breast meat only roasted  FDC 171496
//     Chicken breast roasted           FDC 171477
//     Beef bottom round roasted        FDC 170224
//     Cheddar sharp                    FDC 170899
//     Egg white dried                  FDC 172204
//     Ham (cured, extra lean+regular)  FDC 168296
//     Egg whole hard-boiled            FDC 173424
//
//   Dose (raw USDA, no model):  Σ (food grams · trp per gram), vs 1 g threshold.
//   Ratio (stylized transport model — direction established, magnitude illustrative):
//     plasmaTrp  = TRP0  + ABSORB·mealTrp
//     plasmaLNAA = (LNAA0 + ABSORB·mealLNAA)·(1 − insulinClear(carbs))
//     ratio      = plasmaTrp / plasmaLNAA          (fasting baseline TRP0/LNAA0 = 0.10)
//
// These constants and formulas mirror the inline <script> in index.html exactly.

const FOOD = {
  turkey_breast:  { name: 'Turkey breast',  trp: 0.287, Leu: 1.869, Ile: 0.773, Val: 0.862, Phe: 0.869, Tyr: 0.801, prot: 30.13 },
  chicken_breast: { name: 'Chicken breast', trp: 0.362, Leu: 2.328, Ile: 1.638, Val: 1.539, Phe: 1.231, Tyr: 1.047, prot: 31.02 },
  beef_round:     { name: 'Beef round',     trp: 0.176, Leu: 2.129, Ile: 1.218, Val: 1.328, Phe: 1.057, Tyr: 0.853, prot: 26.76 },
  cheddar_sharp:  { name: 'Cheddar',        trp: 0.321, Leu: 2.434, Ile: 1.289, Val: 1.631, Phe: 1.259, Tyr: 1.317, prot: 24.25 },
  eggwhite_dried: { name: 'Egg white',      trp: 0.999, Leu: 6.838, Ile: 4.581, Val: 5.164, Phe: 4.736, Tyr: 3.153, prot: 81.10 },
  ham:            { name: 'Ham',            trp: 0.243, Leu: 1.585, Ile: 0.988, Val: 1.077, Phe: 0.812, Tyr: 0.450, prot: 21.97 },
  egg_whole:      { name: 'Egg (whole)',    trp: 0.153, Leu: 1.086, Ile: 0.671, Val: 0.858, Phe: 0.680, Tyr: 0.499, prot: 12.58 }
};
const lnaa = f => f.Leu + f.Ile + f.Val + f.Phe + f.Tyr;   // g per 100 g
const OZ = 28.3495;

const TRP0 = 0.012, LNAA0 = 0.120, ABSORB = 0.02, INS_K = 0.0035, INS_CAP = 0.6, THRESH = 1.0;
const insulinClear = carbG => Math.min(INS_CAP, carbG * INS_K);

function evalPlate(p) {
  const items = [];
  if (p.turkeyOz > 0) items.push([FOOD.turkey_breast, p.turkeyOz * OZ]);
  if (p.otherOz > 0) items.push([FOOD[p.otherKey], p.otherOz * OZ]);
  let mtrp = 0, mlnaa = 0;
  for (const [f, g] of items) { mtrp += f.trp / 100 * g; mlnaa += lnaa(f) / 100 * g; }
  const c = insulinClear(p.carbG);
  const pT = TRP0 + ABSORB * mtrp;
  const pL = (LNAA0 + ABSORB * mlnaa) * (1 - c);
  return { mtrp, mlnaa, clear: c, pT, pL, ratio: pT / pL, dosePct: mtrp / THRESH };
}
const trpPerG = k => FOOD[k].trp / FOOD[k].prot * 1000;   // mg per gram of protein

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

console.log('── turkey / tryptophan / LNAA transport — does-turkey-make-you-sleepy ──\n');

// 1) The headline dose: a 3-oz (85 g) serving of turkey breast, two ways.
{
  const viaOz = 3 * OZ * FOOD.turkey_breast.trp / 100;   // method A: 3 oz → g → Trp
  const via85 = 85 * FOOD.turkey_breast.trp / 100;       // method B: 85 g → Trp
  check('3-oz turkey ≈ 0.24 g Trp, and < 1/3 of the 1 g dose',
    Math.abs(viaOz - 0.244) < 0.003 && viaOz < 1 / 3 && Math.abs(via85 - 0.244) < 0.003,
    `3oz=${viaOz.toFixed(3)} g, 85g=${via85.toFixed(3)} g`);
}

// 2) Per gram of protein, turkey is ~9.5 mg/g and mid-pack (below chicken/cheddar/egg-white),
//    above lean beef round — "not special."
{
  const t = trpPerG('turkey_breast');
  check('turkey ≈ 9.5 mg Trp/g protein, below chicken/cheddar/egg-white, above beef',
    Math.abs(t - 9.53) < 0.1 &&
    t < trpPerG('chicken_breast') && t < trpPerG('cheddar_sharp') && t < trpPerG('eggwhite_dried') &&
    t > trpPerG('beef_round'),
    `turkey=${t.toFixed(1)}, chicken=${trpPerG('chicken_breast').toFixed(1)}, ` +
    `cheddar=${trpPerG('cheddar_sharp').toFixed(1)}, eggwhite=${trpPerG('eggwhite_dried').toFixed(1)}, ` +
    `beef=${trpPerG('beef_round').toFixed(1)}`);
}

// 3) To reach the 1 g threshold from turkey alone: 1/(trp per gram) grams, two ways.
{
  const need = 1 / (FOOD.turkey_breast.trp / 100);   // method A: from per-100g
  const needB = 100 / FOOD.turkey_breast.trp;        // method B: algebraically identical rearrangement
  check('1 g Trp needs ~348 g (~12 oz) of turkey breast',
    approx(need, needB, 1e-6) && need > 300 && Math.abs(need / OZ - 12.3) < 0.3,
    `${need.toFixed(0)} g = ${(need / OZ).toFixed(1)} oz`);
}

// 4) Fasting baseline ratio is exactly 0.10 by construction (TRP0/LNAA0).
check('fasting baseline ratio TRP0/LNAA0 = 0.10', approx(TRP0 / LNAA0, 0.10),
  `${(TRP0 / LNAA0).toFixed(3)}`);

// 5) THE REVEAL, part A: adding turkey RAISES the dose but LOWERS the ratio.
{
  const a = evalPlate({ turkeyOz: 2, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 0, wine: 0 });
  const b = evalPlate({ turkeyOz: 8, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 0, wine: 0 });
  check('more turkey ⇒ dose up, ratio down (dose & ratio move opposite ways)',
    b.mtrp > a.mtrp && b.ratio < a.ratio,
    `dose ${a.mtrp.toFixed(2)}→${b.mtrp.toFixed(2)} g, ratio ${a.ratio.toFixed(3)}→${b.ratio.toFixed(3)}`);
}

// 6) Ratio is monotone decreasing in turkey amount across the whole slider (0..16 oz, no carbs).
{
  let ok = true, prev = Infinity;
  for (let oz = 0.5; oz <= 16 + 1e-9; oz += 0.5) {
    const r = evalPlate({ turkeyOz: oz, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 0, wine: 0 }).ratio;
    if (r > prev + 1e-12) ok = false;
    prev = r;
  }
  check('ratio strictly decreasing as turkey rises (protein crowds the transporter)', ok);
}

// 7) THE REVEAL, part B: a protein-heavy plate pushes the ratio BELOW fasting 0.10;
//    a protein-free carb snack pushes it ABOVE. Both directions from the same model.
{
  const prot = evalPlate({ turkeyOz: 6, otherKey: 'ham', otherOz: 3, carbG: 0, wine: 0 });
  const carb = evalPlate({ turkeyOz: 0, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 150, wine: 0 });
  check('protein-only ratio < 0.10 < carb-snack ratio (levers push opposite ways)',
    prot.ratio < 0.10 && carb.ratio > 0.10,
    `protein=${prot.ratio.toFixed(3)}, carb=${carb.ratio.toFixed(3)}`);
}

// 8) Carbohydrate monotonically raises the ratio (insulin clears LNAAs), up to the cap.
{
  let ok = true, prev = -Infinity;
  const base = { turkeyOz: 4, otherKey: 'cheddar_sharp', otherOz: 1 };
  for (let cg = 0; cg <= 400; cg += 10) {
    const r = evalPlate({ ...base, carbG: cg, wine: 0 }).ratio;
    if (r < prev - 1e-12) ok = false;
    prev = r;
  }
  check('more carbohydrate ⇒ higher ratio (insulin raises brain Trp share)', ok);
}

// 9) The irony: a carb snack delivers a HIGHER transport ratio than a turkey dinner
//    with the SAME turkey — tryptophan reaches the brain better from the snack.
{
  const dinner = evalPlate({ turkeyOz: 4, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 0, wine: 0 });
  const snack = evalPlate({ turkeyOz: 0, otherKey: 'cheddar_sharp', otherOz: 0, carbG: 150, wine: 0 });
  check('carb snack ratio > turkey dinner ratio (Fernstrom irony)',
    snack.ratio > dinner.ratio,
    `snack=${snack.ratio.toFixed(3)} > dinner=${dinner.ratio.toFixed(3)}`);
}

// 10) insulinClear is bounded in [0, 0.6] for all non-negative carbohydrate.
{
  let ok = true;
  for (let cg = 0; cg <= 1000; cg += 5) {
    const c = insulinClear(cg);
    if (c < 0 || c > INS_CAP + 1e-12) ok = false;
  }
  check('insulin clearance stays within [0, 0.6] for all carb loads', ok);
}

// 11) Default plate the page shows on load (turkey 4 oz, cheddar 1 oz, carbs 150 g):
//     dose ≈ 0.42 g (≈42% of 1 g), and every quantity is finite & positive.
{
  const r = evalPlate({ turkeyOz: 4, otherKey: 'cheddar_sharp', otherOz: 1, carbG: 150, wine: 1 });
  console.log(`      [default plate] dose=${r.mtrp.toFixed(3)} g (${Math.round(r.dosePct * 100)}% of 1 g), ` +
              `ratio=${r.ratio.toFixed(3)}`);
  check('default-plate readouts finite, dose ≈ 0.42 g (< 1 g), ratio > 0',
    Math.abs(r.mtrp - 0.416) < 0.01 && r.mtrp < THRESH && r.ratio > 0 && Number.isFinite(r.ratio));
}

// 12) Dose is exactly additive across foods (no model, pure USDA arithmetic).
{
  const p = { turkeyOz: 4, otherKey: 'ham', otherOz: 3, carbG: 0, wine: 0 };
  const combined = evalPlate(p).mtrp;
  const parts = 4 * OZ * FOOD.turkey_breast.trp / 100 + 3 * OZ * FOOD.ham.trp / 100;
  check('total dose = sum of per-food doses (additive, USDA only)',
    approx(combined, parts, 1e-12), `${combined.toFixed(4)} = ${parts.toFixed(4)}`);
}

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