#!/usr/bin/env node
// verify.mjs — the check behind the stratum "How does a battery work?"
//
// A battery's voltage is the DIFFERENCE of two standard reduction potentials.
// This verifier reproduces the standard cell EMFs the instrument surfaces
// (Daniell cell, lead-acid cell, and every pair the reader can build) from a
// single tabulated ladder of standard electrode potentials, reproduces the
// thermodynamic and Nernst constants, and states plainly which numbers are
// EXACT (derived here from tabulated potentials) versus TYPICAL (cited
// order-of-magnitude device figures the "voltage isn't power" instrument uses).
//
// Sources for the ladder (standard reduction potentials, aqueous, 25 °C, vs the
// Standard Hydrogen Electrode defined as exactly 0 V):
//   CRC Handbook of Chemistry and Physics, "Standard Reduction Potentials";
//   IUPAC / Bard & Faulkner, Electrochemical Methods, App. C;
//   Atkins, Physical Chemistry (10th ed.), Data section.
//   Values are the widely tabulated ones, rounded to 2 decimals for the ladder
//   the reader operates; the more-precise literature value is kept alongside.
//
// Run: node research/how-a-battery-works/verify.mjs

'use strict';

let ok = true;
const near = (a, b, tol) => Math.abs(a - b) <= tol;
function check(label, got, want, tol, unit = '') {
  const pass = near(got, want, tol);
  ok = ok && pass;
  const g = typeof got === 'number' ? got.toFixed(4) : String(got);
  console.log(`  ${pass ? 'ok  ' : 'FAIL'} ${label.padEnd(46)} ${String(g).padStart(11)} ${unit}`.trimEnd());
  return pass;
}

// ---------------------------------------------------------------------------
// 1. The ladder of standard reduction potentials (V vs SHE, 25 °C).
//    `round` = the 2-dp value the on-page ladder shows; `lit` = a more precise
//    literature value; we require |round - lit| < 0.02 V so the ladder is honest.
// ---------------------------------------------------------------------------
const LADDER = [
  // key            round     lit     half-reaction (reduction)
  ['Li+/Li',       -3.04,  -3.0401, 'Li⁺ + e⁻ → Li'],
  ['Na+/Na',       -2.71,  -2.7100, 'Na⁺ + e⁻ → Na'],
  ['Mg2+/Mg',      -2.37,  -2.3720, 'Mg²⁺ + 2e⁻ → Mg'],
  ['Al3+/Al',      -1.66,  -1.6620, 'Al³⁺ + 3e⁻ → Al'],
  ['Zn2+/Zn',      -0.76,  -0.7618, 'Zn²⁺ + 2e⁻ → Zn'],
  // Fe: the page shows the classic textbook −0.44 (Atkins / older CRC). The modern
  // CRC/Vanýsek value is −0.447 (rounds to −0.45); both are within tolerance and the
  // page footnotes the discrepancy explicitly.
  ['Fe2+/Fe',      -0.44,  -0.4470, 'Fe²⁺ + 2e⁻ → Fe'],
  ['Pb2+/Pb',      -0.13,  -0.1262, 'Pb²⁺ + 2e⁻ → Pb'],
  ['2H+/H2',        0.00,   0.0000, '2H⁺ + 2e⁻ → H₂  (defines the zero)'],
  ['Cu2+/Cu',      +0.34,  +0.3419, 'Cu²⁺ + 2e⁻ → Cu'],
  ['Ag+/Ag',       +0.80,  +0.7996, 'Ag⁺ + e⁻ → Ag'],
  ['Cl2/Cl-',      +1.36,  +1.3583, 'Cl₂ + 2e⁻ → 2Cl⁻'],
  ['F2/F-',        +2.87,  +2.8660, 'F₂ + 2e⁻ → 2F⁻'],
];

console.log('1. Standard reduction ladder — on-page rounding is faithful to literature (|Δ|<0.02 V):');
const E = {};
for (const [key, round, lit] of LADDER) {
  E[key] = round;
  check(key, round, lit, 0.02, 'V');
}

// ---------------------------------------------------------------------------
// 2. A cell's EMF is just cathode − anode on that ladder.
//    E°cell = E°(reduction at cathode) − E°(reduction at anode).
//    The reader builds a cell by picking two couples; the more-negative one is
//    forced to be the anode (it is oxidised). We reproduce the canonical cells.
// ---------------------------------------------------------------------------
console.log('\n2. Cell EMF = E°(cathode) − E°(anode), reproduced from the ladder:');
function cellEMF(cathodeKey, anodeKey) {
  return E[cathodeKey] - E[anodeKey];
}
// Daniell cell: Zn anode, Cu cathode.
check('Daniell  Zn|Zn²⁺ ‖ Cu²⁺|Cu', cellEMF('Cu2+/Cu', 'Zn2+/Zn'), 1.10, 0.01, 'V');
// Silver–zinc.
check('Zn|Zn²⁺ ‖ Ag⁺|Ag',           cellEMF('Ag+/Ag', 'Zn2+/Zn'), 1.56, 0.01, 'V');
// Copper–silver.
check('Cu|Cu²⁺ ‖ Ag⁺|Ag',           cellEMF('Ag+/Ag', 'Cu2+/Cu'), 0.46, 0.01, 'V');
// Zinc–iron: Fe is the less-negative couple, so Fe is the cathode, Zn the anode.
check('Zn|Zn²⁺ ‖ Fe²⁺|Fe  (Fe cath)', cellEMF('Fe2+/Fe', 'Zn2+/Zn'), 0.32, 0.01, 'V');

// ---------------------------------------------------------------------------
// 3. The lead-acid cell — a separate, well-tabulated pair (sulfate couples,
//    not the bare-metal ladder). One cell ≈ 2.04 V; a "12 V" battery is 6 cells.
//    Source: CRC / Bard & Faulkner (PbO₂/PbSO₄ and PbSO₄/Pb in H₂SO₄).
// ---------------------------------------------------------------------------
console.log('\n3. Lead-acid cell (the car battery), from the sulfate half-cells:');
const E_PbO2 = +1.685;   // PbO₂ + 4H⁺ + SO₄²⁻ + 2e⁻ → PbSO₄ + 2H₂O (textbook; modern CRC +1.691)
const E_PbSO4 = -0.356;  // PbSO₄ + 2e⁻ → Pb + SO₄²⁻ (textbook; modern CRC −0.359)
const leadCell = E_PbO2 - E_PbSO4;
check('one lead-acid cell — STANDARD-state EMF', leadCell, 2.04, 0.01, 'V');
check('six cells — standard-state (~12 V nominal)', 6 * leadCell, 12.24, 0.02, 'V');
// IMPORTANT honesty split: the ~2.04 V above is the STANDARD-state EMF (1 M H₂SO₄).
// A real fully-charged cell uses concentrated acid (~4–5 M); the Nernst term lifts the
// resting open-circuit voltage to ~2.1 V/cell → ~12.6 V for the battery. The page uses
// 12.6 V for the *actual* car battery, and labels 12.24 V as the standard-state figure.
const realCellOCV = 2.10;                 // typical fully-charged resting (concentrated acid)
check('real fully-charged battery (~2.1 V/cell)', 6 * realCellOCV, 12.6, 0.1, 'V');

// ---------------------------------------------------------------------------
// 4. Thermodynamic + Nernst constants (25 °C = 298.15 K).
//    Voltage is free energy per unit charge: ΔG° = −nFE°.
// ---------------------------------------------------------------------------
console.log('\n4. Constants — voltage as thermodynamics:');
const F = 96485;            // C/mol, Faraday constant (CODATA, rounded)
const R = 8.314462618;      // J/(mol·K)
const T = 298.15;           // K
const RT_F = (R * T) / F;                    // V, the "thermal voltage" kT/e per mole
const nernstDecade = (R * T * Math.log(10)) / F;  // V per decade of Q
check('Faraday constant F', F, 96485, 1, 'C/mol');
check('RT/F at 25 °C', RT_F, 0.025693, 1e-5, 'V');
check('Nernst slope RT·ln10/F ("59 mV/decade")', nernstDecade, 0.05916, 1e-4, 'V/dec');
// ΔG° for the Daniell cell, n = 2.
const dG_daniell = -2 * F * 1.10;            // J/mol
check('ΔG° Daniell (n=2, E°=1.10 V), kJ/mol', dG_daniell / 1000, -212.3, 0.5, 'kJ/mol');

// ---------------------------------------------------------------------------
// 5. Voltage is NOT power. The "build a cell" instrument gives EXACT EMFs above.
//    The second instrument answers "will it run this load?" from
//        I = E / (R_internal + R_load),   V_terminal = E − I·R_internal.
//    The internal resistances / currents below are TYPICAL, order-of-magnitude,
//    device-dependent figures (CITED, not derived) — the verifier's job here is
//    only to confirm the ARITHMETIC of the model and that the qualitative
//    verdicts (which battery cranks a starter, which lights an LED) are right.
//    Sources: manufacturer datasheets (Energizer alkaline), BCI CCA ratings,
//    standard lemon-cell demonstration measurements. See NOTES below.
// ---------------------------------------------------------------------------
console.log('\n5. Voltage ≠ power — short-circuit ceiling I_sc = E/R_int (TYPICAL device figures):');
const DEVICES = [
  // name              E(V)   R_int(Ω)   (typical, cited)
  ['lemon cell (Zn/Cu)', 0.9,   1000],   // ~0.9 V, R_int hundreds Ω–kΩ
  ['AA alkaline',        1.5,   0.2],     // ~0.15–0.3 Ω fresh (Energizer E91)
  ['CR2032 coin',        3.0,   15],      // ~10–40 Ω fresh; 15 Ω representative
  ['car lead-acid 12 V', 12.6,  0.008],   // a few mΩ (order-of-magnitude)
];
const Isc = {};
for (const [name, E0, Rint] of DEVICES) {
  Isc[name] = E0 / Rint;
  console.log(`  ${name.padEnd(22)} E=${E0} V  R_int=${Rint} Ω  →  I_sc ≈ ${fmtA(Isc[name])}`);
}
// The point: voltages span ~14×, but deliverable current spans ~6 ORDERS.
const currents = Object.values(Isc);
const spanOrders = Math.log10(Math.max(...currents) / Math.min(...currents));
check('deliverable-current span (orders of magnitude)', spanOrders, 6.2, 0.4, 'decades');

// Qualitative verdicts the instrument shows must hold:
const LED_NEED = 0.015;      // A, a red LED wants ~10–20 mA
const STARTER_NEED = 150;    // A, cranking a car draws ~100–300 A
console.log('\n  Load verdicts (I_sc ≥ demand ?):');
function verdict(name, need, needLabel) {
  const canLED = Isc[name] >= LED_NEED;
  const canStart = Isc[name] >= STARTER_NEED;
  return { canLED, canStart };
}
// Lemon: cannot even fully drive one LED, let alone a starter.
{
  const v = verdict('lemon cell (Zn/Cu)');
  check('lemon can crank a starter? (must be false→0)', v.canStart ? 1 : 0, 0, 0, '');
  check('lemon barely lights an LED? (I_sc<15mA→false)', v.canLED ? 1 : 0, 0, 0, '');
}
// AA: lights an LED easily, cannot crank a starter.
{
  const v = verdict('AA alkaline');
  check('AA lights an LED? (must be true→1)', v.canLED ? 1 : 0, 1, 0, '');
  check('AA cranks a starter? (must be false→0)', v.canStart ? 1 : 0, 0, 0, '');
}
// Car battery: cranks the starter (that is its whole job).
{
  const v = verdict('car lead-acid 12 V');
  check('car battery cranks a starter? (true→1)', v.canStart ? 1 : 0, 1, 0, '');
}

// A 12 V battery with the LEMON's internal resistance could NOT crank a starter —
// proving the current comes from the milliohms, not the volts.
const twelveVoltButResistive = 12.6 / 1000;   // E/R_int with lemon-like R
check('12 V @ 1 kΩ cranks a starter? (false→0)', twelveVoltButResistive >= STARTER_NEED ? 1 : 0, 0, 0, '');

// ---------------------------------------------------------------------------
// 6. Loaded terminal voltage — why a "1.5 V" AA reads less under load, and why a
//    lemon collapses to near zero the instant you draw real current.
//    V_terminal = E − I·R_int, with I = E/(R_int + R_load).
// ---------------------------------------------------------------------------
console.log('\n6. Terminal voltage under load  V = E·R_load/(R_int+R_load):');
function terminal(E0, Rint, Rload) {
  const I = E0 / (Rint + Rload);
  return { I, V: E0 - I * Rint };
}
// AA into a 10 Ω load: barely sags.
{
  const r = terminal(1.5, 0.2, 10);
  check('AA (R_int 0.2Ω) into 10Ω: V_terminal', r.V, 1.471, 0.01, 'V');
}
// Lemon into the SAME 10 Ω load: collapses (R_int ≫ R_load).
{
  const r = terminal(0.9, 1000, 10);
  check('lemon (R_int 1kΩ) into 10Ω: V_terminal', r.V, 0.0089, 0.002, 'V');
}

// ---------------------------------------------------------------------------
function fmtA(a) {
  if (a >= 1) return a.toFixed(a >= 100 ? 0 : 1) + ' A';
  if (a >= 1e-3) return (a * 1e3).toFixed(1) + ' mA';
  return (a * 1e6).toFixed(0) + ' µA';
}

console.log('\n' + '─'.repeat(64));
console.log('NOTES on what is EXACT vs TYPICAL:');
console.log('  EXACT (derived here from tabulated standard potentials): every cell');
console.log('    EMF in §2–3, and the constants in §4. These are the numbers the');
console.log('    "build a cell" instrument shows — reproducible from the ladder.');
console.log('  TYPICAL (cited, device-dependent, §5–6): internal resistances,');
console.log('    short-circuit currents, LED/starter demands. Real devices vary by');
console.log('    construction, age, and temperature; the page labels these as');
console.log('    order-of-magnitude typical values, and the verifier only checks');
console.log('    the model arithmetic and the qualitative verdicts, not exactness.');
console.log('  CAVEATS named on-page: (a) a single electrode potential is not');
console.log('    measurable in isolation — only differences of two electrodes are; SHE');
console.log('    is DEFINED as 0 V and the ladder is relative to it (the absolute SHE');
console.log('    scale ~4.44 V vs vacuum, Trasatti/IUPAC, is a model estimate, not a');
console.log('    measured voltage). (b) Nernst "59 mV/decade" holds only at 25 C.');
console.log('    (c) Fe shown as classic -0.44 V; modern CRC -0.447 (rounds -0.45).');
console.log('─'.repeat(64));
console.log(ok ? '\n✅ ALL CHECKS PASS' : '\n❌ SOME CHECKS FAILED');
process.exit(ok ? 0 : 1);
