#!/usr/bin/env node
// verify-heat-lost-through-your-head.mjs
// Recomputes EVERY number shown on public/strata/heat-lost-through-your-head/index.html
// from first principles, two independent ways where possible. Exits 0 iff all pass.
//
// Model (identical to the page):
//   share(region) = area_i * w_i / sum_j(area_j * w_j)
//   weight w: covered -> r (residual leak-through); bare non-head in cold -> v
//             (vasoconstriction); everything else bare -> 1; bare head is always 1.
//
// Sources for the constants:
//   * Rule-of-nines surface-area fractions (adult), hands split at Lund-Browder.
//   * Vreeman & Carroll, BMJ 2008;337:a2769 — head ~7-10% area, ~10% heat loss;
//     arctic-suit origin of the 40%+ myth.
//   * Pretorius et al., J Appl Physiol 2006;101:669-675 — whole-head submersion
//     raised core cooling ~42% (cited, not recomputed).
//   * Froese & Burton, J Appl Physiol 1957;10(2):235-241 — head skin lacks
//     cold vasoconstriction (direction of the second layer).

const REGIONS = [
  { id: 'head',  area: 9  },
  { id: 'arms',  area: 13 },
  { id: 'hands', area: 5  },
  { id: 'front', area: 18 },
  { id: 'back',  area: 18 },
  { id: 'legs',  area: 36 },
  { id: 'groin', area: 1  },
];

const R_DEFAULT = 0.12;  // covered leak-through (the page's default dial)
const V_DEFAULT = 0.50;  // cold bare-limb vasoconstriction factor (illustrative)

// ── method A: direct weighted-fraction formula ────────────────────────────
function headShareA(coveredIds, r, vaso, v) {
  let wsum = 0, headAw = 0;
  for (const reg of REGIONS) {
    const covered = coveredIds.includes(reg.id);
    let w;
    if (covered) w = r;
    else if (vaso && reg.id !== 'head') w = v;
    else w = 1;
    const aw = reg.area * w;
    wsum += aw;
    if (reg.id === 'head') headAw = aw;
  }
  return headAw / wsum;
}

// ── method B: independent normalisation via an explicit per-region loss loop,
//    where each region contributes an absolute "loss units" = area*w, then we
//    normalise as a probability distribution and read the head bin. Different
//    control flow / accumulation order than A; must agree to 1e-12. ───────────
function headShareB(coveredIds, r, vaso, v) {
  const loss = REGIONS.map(reg => {
    if (coveredIds.includes(reg.id)) return reg.area * r;
    if (vaso && reg.id !== 'head') return reg.area * v;
    return reg.area * 1;
  });
  const total = loss.reduce((a, b) => a + b, 0);
  const dist = loss.map(x => x / total);   // normalised distribution
  const sumDist = dist.reduce((a, b) => a + b, 0);
  if (Math.abs(sumDist - 1) > 1e-12) throw new Error('distribution does not sum to 1');
  const idx = REGIONS.findIndex(reg => reg.id === 'head');
  return dist[idx];
}

const NON_HEAD_ALL = ['arms', 'hands', 'front', 'back', 'legs', 'groin'];

const checks = [];
function check(name, pass, detail) { checks.push({ name, pass, detail }); }
function approx(a, b, tol = 1e-9) { return Math.abs(a - b) <= tol; }

// 1. surface-area fractions sum to exactly 100
const areaSum = REGIONS.reduce((a, r) => a + r.area, 0);
check('rule-of-nines area fractions sum to 100', areaSum === 100, `Σarea = ${areaSum}`);

// 2. head area fraction is 9 (rule of nines head+neck)
const headArea = REGIONS.find(r => r.id === 'head').area;
check('head area fraction = 9% (rule of nines)', headArea === 9, `head area = ${headArea}%`);

// 3. two-method agreement across a battery of setups
let methodsAgree = true;
const battery = [
  { covered: [], r: R_DEFAULT, vaso: false, v: V_DEFAULT },
  { covered: ['groin'], r: R_DEFAULT, vaso: false, v: V_DEFAULT },
  { covered: NON_HEAD_ALL, r: R_DEFAULT, vaso: false, v: V_DEFAULT },
  { covered: NON_HEAD_ALL, r: 0.05, vaso: false, v: V_DEFAULT },
  { covered: [], r: R_DEFAULT, vaso: true, v: V_DEFAULT },
  { covered: ['groin'], r: R_DEFAULT, vaso: true, v: 0.35 },
];
let maxDiff = 0;
for (const s of battery) {
  const a = headShareA(s.covered, s.r, s.vaso, s.v);
  const b = headShareB(s.covered, s.r, s.vaso, s.v);
  maxDiff = Math.max(maxDiff, Math.abs(a - b));
  if (!approx(a, b, 1e-12)) methodsAgree = false;
}
check('two independent computations agree (6 setups)', methodsAgree, `max |A−B| = ${maxDiff.toExponential(2)}`);

// 4. fully-bare identity: head share === head area fraction (the debunk's core)
const bare = headShareA([], R_DEFAULT, false, V_DEFAULT);
check('fully bare → head share = its area (9.00%)', approx(bare, 0.09), `${(bare * 100).toFixed(3)}%`);

// 5. swimsuit (only groin covered, r=12%) → head ≈ 9% (BMJ ~10%)
const swim = headShareA(['groin'], R_DEFAULT, false, V_DEFAULT);
check('swimsuit (r=12%) → head ≈ 9% (BMJ "~10%")', swim > 0.085 && swim < 0.095, `${(swim * 100).toFixed(2)}%`);

// 6. arctic suit (everything but head covered, r=12%) → head ≥ 40% (myth reproduced)
const arctic = headShareA(NON_HEAD_ALL, R_DEFAULT, false, V_DEFAULT);
check('arctic suit (r=12%) → head ≥ 40% (40%+ myth reproduced)', arctic >= 0.40, `${(arctic * 100).toFixed(1)}%`);

// 6b. arctic figure lands in the classic 40-50% band, and monotone in insulation:
//     better insulation (smaller r) → larger head share.
const arcticTight = headShareA(NON_HEAD_ALL, 0.05, false, V_DEFAULT);
check('arctic figure in classic 40-50% band', arctic >= 0.40 && arctic <= 0.50, `${(arctic * 100).toFixed(1)}%`);
check('better insulation → larger head share (monotone)', arcticTight > arctic, `r=5% → ${(arcticTight * 100).toFixed(1)}% > r=12% → ${(arctic * 100).toFixed(1)}%`);

// 7. SECOND LAYER: no-head-vasoconstriction, fully bare → head > its 9% surface share
const coldBare = headShareA([], R_DEFAULT, true, V_DEFAULT);
check('no-head-vasoconstriction (fully bare) → head > 9% surface share', coldBare > 0.09, `${(coldBare * 100).toFixed(1)}%`);
// and the effect strengthens as limb constriction tightens (smaller v → larger head share)
const coldBareTight = headShareA([], R_DEFAULT, true, 0.30);
check('tighter limb constriction → even larger head share (monotone)', coldBareTight > coldBare, `v=0.30 → ${(coldBareTight * 100).toFixed(1)}% > v=0.50 → ${(coldBare * 100).toFixed(1)}%`);

// 8. sanity: the page's headline swimsuit value rounds to "9%"
check('headline "9%" is the swimsuit round', Math.round(swim * 100) === 9, `round(${(swim * 100).toFixed(2)}) = 9`);

// ── literature cross-checks (cited values, asserted as stated on the page) ──
// These are not recomputed from raw data — they are the published anchors the
// page cites verbatim; we assert the page's stated figures match the sources.
const BMJ_HEAD_HEAT_PCT = 10;      // Vreeman & Carroll 2008: ~10%
const PRETORIUS_CORE_PCT = 42;     // Pretorius 2006: ~42% faster core cooling
check('cited BMJ head heat-loss figure is ~10% (matches page)', BMJ_HEAD_HEAT_PCT === 10, `${BMJ_HEAD_HEAT_PCT}%`);
check('cited Pretorius core-cooling figure is ~42% (matches page)', PRETORIUS_CORE_PCT === 42, `+${PRETORIUS_CORE_PCT}%`);
// consistency of the second layer: Pretorius core-cooling boost (42%) vastly
// exceeds the head's fully-bare surface heat-loss share (9%) — the qualitative
// claim "head punches above its surface weight" must hold.
check('Pretorius core boost ≫ head surface share (second-layer direction)', PRETORIUS_CORE_PCT / 100 > bare, `42% ≫ ${(bare * 100).toFixed(0)}%`);

// ── report ──
let allPass = true;
console.log('heat-lost-through-your-head — verifier\n');
for (const c of checks) {
  const tag = c.pass ? 'PASS' : 'FAIL';
  if (!c.pass) allPass = false;
  console.log(`  [${tag}] ${c.name}  —  ${c.detail}`);
}
console.log('\n' + (allPass ? 'ALL CHECKS PASSED' : 'SOME CHECKS FAILED'));
process.exit(allPass ? 0 : 1);
