// verify-is-synthetic-vanilla-the-same.mjs — the committed check for
// "Is Synthetic Vanilla the Same?" (/strata/is-synthetic-vanilla-the-same/).
//
// The claim the page makes: synthetic vanillin and the vanillin inside a real
// vanilla bean are the IDENTICAL molecule — 4-hydroxy-3-methoxybenzaldehyde,
// C8H8O3 (PubChem CID 1183, CAS 121-33-5). One defined structure, so no chemist
// can tell the two apart by the molecule itself. What differs is context (the
// several hundred other compounds a real extract carries) and, crucially, the
// ATOMS: the bulk carbon-13 ratio (delta13C) of vanilla-pod vanillin does not
// overlap the range of petroleum/lignin vanillin, which is why stable-isotope
// ratio analysis is the regulatory method for policing "natural vanilla."
//
// What this script proves, offline and from scratch (no dependencies):
//   1. The molar mass of C8H8O3 recomputed from IUPAC standard atomic weights is
//      152.149 g/mol, which rounds to the 152.15 g/mol PubChem reports.
//   2. The molecular formula parses to exactly C:8 H:8 O:3 — one structure,
//      identical regardless of origin (the whole point of the title).
//   3. The commercial production split (~85% petrochemical guaiacol + ~15%
//      lignin) sums to 100% of synthetic output; beans supply <1% of the market.
//   4. The delta13C bands DO NOT overlap: vanilla-pod natural [-22.0, -15.5]‰
//      sits entirely above petroleum/lignin synthetic [-36.2, -24.9]‰, leaving a
//      clean gap of 2.9‰ — the checkable classifier boundary the page draws.
//   5. The honest caveat: ex-glucose "biosynthetic natural" vanillin (~-12.5‰) is
//      MORE enriched than the pod band and synthetic is more depleted, so a blend
//      of the two can be tuned to read inside the pod band (the fraud PMC11858005
//      describes: "mixing synthetic/biosynthetic vanillin and ex-glucose
//      vanillin"). Bulk delta13C alone cannot catch the mixture, which is why
//      authorities add site-specific SNIF-NMR + delta2H + 14C. (Corrected
//      2026-10-13: this used to say pure ex-glucose passes, which the page's own
//      classifier contradicts.)
//   6. The sensory honesty guard: there is NO sourceable single discrimination
//      percentage; the scout's "54% / Hansen 2019" was fabricated and is dropped.
//
//   run:  node research/is-synthetic-vanilla-the-same/verify-is-synthetic-vanilla-the-same.mjs
//
// The arithmetic behind every number the page displays is redone here; the
// sourced figures themselves (85/15, the bands, -12.5) are copied from sources.

let passed = 0, total = 0, guards = 0;
const ok = (name, cond, extra = '') => {
  total++;
  if (cond) passed++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
// A "guard" is a documentation / honesty assertion on a *sourced constant* or an
// editorial decision — not an independent recomputation. It still must pass, but we
// label it [guard] so the "recomputed" framing stays honest about what is derived
// vs merely asserted. The load-bearing quantities (molar mass, the delta13C gap and
// the classifier) go through ok() and ARE recomputed from scratch.
const guard = (name, cond, extra = '') => {
  total++; guards++;
  if (cond) passed++;
  console.log(`${cond ? '  ok' : 'FAIL'}  [guard] ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── 1. Molar mass of vanillin from IUPAC standard atomic weights ─────────────
// Conventional (2021 IUPAC) standard atomic weights used for a single-value mass.
const AW = { C: 12.011, H: 1.008, O: 15.999 };
const FORMULA = { C: 8, H: 8, O: 3 };
const subC = FORMULA.C * AW.C; // 96.088
const subH = FORMULA.H * AW.H; // 8.064
const subO = FORMULA.O * AW.O; // 47.997
const molar = subC + subH + subO; // 152.149
console.log('\n— molar mass of C8H8O3 recomputed from atomic weights —');
console.log(`  C: 8 x 12.011 = ${subC.toFixed(3)}`);
console.log(`  H: 8 x 1.008  = ${subH.toFixed(3)}`);
console.log(`  O: 3 x 15.999 = ${subO.toFixed(3)}`);
console.log(`  sum           = ${molar.toFixed(3)}  ->  ${molar.toFixed(2)} g/mol`);
ok('C subtotal = 96.088',  approx(subC, 96.088, 1e-9), subC.toFixed(3));
ok('H subtotal = 8.064',   approx(subH, 8.064, 1e-9),  subH.toFixed(3));
ok('O subtotal = 47.997',  approx(subO, 47.997, 1e-9), subO.toFixed(3));
ok('sum = 152.149',        approx(molar, 152.149, 1e-9), molar.toFixed(3));
ok('rounds to PubChem 152.15 g/mol (CID 1183)', molar.toFixed(2) === '152.15');

// ── 2. Formula parse — one structure, identical for both origins ─────────────
function parseFormula(s) {
  const out = {};
  const re = /([A-Z][a-z]?)(\d*)/g;
  let m;
  while ((m = re.exec(s)) !== null) {
    if (!m[1]) continue;
    out[m[1]] = (out[m[1]] || 0) + (m[2] ? parseInt(m[2], 10) : 1);
  }
  return out;
}
console.log('\n— molecular formula: one PubChem entry regardless of source —');
const parsed = parseFormula('C8H8O3');
ok('C8H8O3 parses to C:8 H:8 O:3',
   parsed.C === 8 && parsed.H === 8 && parsed.O === 3,
   JSON.stringify(parsed));
// synthetic and bean-derived share ONE structure => one molar mass, by definition
ok('synthetic and bean-derived vanillin have identical mass (same formula)',
   molar === (parsed.C * AW.C + parsed.H * AW.H + parsed.O * AW.O));

// ── 3. Commercial production split ───────────────────────────────────────────
// NOTE (normalization): the source (Wikipedia) frames ~85% guaiacol and ~15% lignin
// as shares of TOTAL world production. Because natural beans are <1% of the market,
// those two shares already sum to ~100%, and we normalize them here to "synthetic
// output" — the <1% bean share is stated separately below and hedged as approximate.
// This is a labeling normalization of the source figures, not a recomputation.
console.log('\n— commercial vanillin production split —');
const GUAIACOL = 85, LIGNIN = 15, BEANS = 0.9; // beans <~1% (approximate, widely reported)
ok('petrochemical guaiacol (85%) + lignin (15%) = 100% of synthetic output',
   GUAIACOL + LIGNIN === 100, `${GUAIACOL}+${LIGNIN}`);
guard('actual beans supply under ~1% of the market (sourced constant)', BEANS < 1, `${BEANS}%`);

// ── 4. Composition contrast: vanillin is a small slice of a cured pod ────────
console.log('\n— composition: single molecule vs a mixture —');
const VANILLIN_PCT = 2;                 // ~2% of a cured pod by dry weight
const REST_PCT = 100 - VANILLIN_PCT;    // ~98% is everything else
const VOLATILE_MIN = 200, AROMA_ACTIVE_MIN = 60; // >200 volatile, >60 aroma-active
guard('vanillin ~2% + rest ~98% = 100% of a cured pod (dry weight)',
   VANILLIN_PCT + REST_PCT === 100, `${VANILLIN_PCT}% + ${REST_PCT}%`);
guard('natural extract carries several hundred other compounds (>200 volatile, >60 aroma-active)',
   VOLATILE_MIN >= 200 && AROMA_ACTIVE_MIN >= 60, `${VOLATILE_MIN} / ${AROMA_ACTIVE_MIN}`);

// ── 5. delta13C isotope fingerprint — the checkable core ─────────────────────
// Bands from PMC11858005. Higher (less negative) = more enriched.
const POD    = { lo: -22.0, hi: -15.5 };   // vanilla-pod natural
const SYN    = { lo: -36.2, hi: -24.9 };   // petroleum / lignin synthetic
const EXGLUC = -12.5;                       // ex-glucose "biosynthetic natural"

// classifier used verbatim on the page
function classifyDelta(d) {
  if (d > POD.hi)  return 'above-pod';   // more enriched than a pod: ex-glucose territory
  if (d >= POD.lo) return 'pod';         // [-22.0, -15.5] vanilla-pod natural
  if (d > SYN.hi)  return 'gap';         // (-24.9, -22.0) no reference sample lands here
  if (d >= SYN.lo) return 'synthetic';   // [-36.2, -24.9] petro/lignin
  return 'below-synthetic';
}

console.log('\n— delta13C bands (per-mil) and the classifier —');
console.log(`  vanilla-pod natural:      ${POD.lo}  to  ${POD.hi}`);
console.log(`  petro/lignin synthetic:   ${SYN.lo}  to  ${SYN.hi}`);
console.log(`  ex-glucose biosynthetic:  ~${EXGLUC}`);
const gap = POD.lo - SYN.hi; // -22.0 - (-24.9) = 2.9
ok('the two bands do NOT overlap (pod low > synthetic high)', POD.lo > SYN.hi,
   `${POD.lo} > ${SYN.hi}`);
ok('non-overlap gap = 2.9 per-mil', approx(gap, 2.9, 1e-9), `${gap.toFixed(1)}‰`);
ok('classify -19.0  -> pod (natural)',       classifyDelta(-19.0) === 'pod');
ok('classify -30.0  -> synthetic',           classifyDelta(-30.0) === 'synthetic');
ok('classify -23.4  -> gap (between bands)', classifyDelta(-23.4) === 'gap');
ok('classify -12.5  -> above-pod (ex-glucose caveat)', classifyDelta(EXGLUC) === 'above-pod');

// the caveat, quantified: pure ex-glucose sits ABOVE the pod band (so on its own
// it is flagged), but it brackets the band with synthetic vanillin, so a blend
// can be tuned into it. Same molecule, same carbon count, so the blend's delta13C
// is the mass-weighted mean: d = f*EXGLUC + (1-f)*dSyn for an ex-glucose share f.
ok('ex-glucose (-12.5) is more enriched than pod max (-15.5)', EXGLUC > POD.hi, `${EXGLUC} > ${POD.hi}`);
const blendRange = (dSyn) => [(POD.lo - dSyn) / (EXGLUC - dSyn), (POD.hi - dSyn) / (EXGLUC - dSyn)];
const everySynCanHide = [SYN.lo, (SYN.lo + SYN.hi) / 2, SYN.hi].every((dSyn) => {
  const [a, b] = blendRange(dSyn);
  const mid = (a + b) / 2, d = mid * EXGLUC + (1 - mid) * dSyn;
  return a > 0 && b < 1 && classifyDelta(d) === 'pod';
});
const [fa, fb] = blendRange(-30.0);
ok('a blend of ex-glucose with any synthetic in the band can be tuned to classify as pod => bulk delta13C alone is fooled',
   everySynCanHide, `e.g. synthetic at -30.0: ${(100 * fa).toFixed(0)}% to ${(100 * fb).toFixed(0)}% ex-glucose reads as pod`);

// ── 6. Sensory honesty guard — no fabricated discrimination percentage ───────
console.log('\n— sensory honesty guard —');
const DISCRIMINATION_PCT = null; // NO sourceable single value exists
guard('no single blind-taste discrimination percentage is claimed (Hansen-2019 dropped)',
   DISCRIMINATION_PCT === null);

// ── tally ────────────────────────────────────────────────────────────────────
console.log(`\n${passed}/${total} checks passed  (${total - guards} recomputed, ${guards} sourced-constant / honesty guards)\n`);
process.exit(passed === total ? 0 : 1);
