#!/usr/bin/env node
// verify-does-dark-mode-save-battery.mjs
// Offline gate: recomputes the calibration and comparison-table values used on
//   public/strata/does-dark-mode-save-battery/index.html
// from the same illustrative OLED model. It compares selected outputs with
// results reported by Purdue (2021 press release and 2022 ECE account):
//   - 3-9%   dark-mode savings at 30-50% brightness (OLED, % of total device power)
//   - 39-47% at 100% brightness
//   - ~10x   reduction in OLED display power dimming 100% -> 50%
//   - LCD    ~0 (backlight-dominated)
// Where possible, key numbers are computed TWO independent ways.
// Exits 0 iff all checks pass; non-zero otherwise.

// ── the model (identical constants to the page) ──────────────────────────
const GAMMA  = Math.log(10) / Math.log(2);      // 3.321928...
const K_RES  = 0.05;
const F_LIGHT = 0.15, F_DARK = 0.90;
const D1 = 1.0;
const C_L = (1 - F_LIGHT) + F_LIGHT * K_RES;    // 0.8575
const C_D = (1 - F_DARK)  + F_DARK  * K_RES;    // 0.1450
const RHO = (C_L - C_D) / 0.43 - C_L;           // calibrated so Sav(1)=0.43
const R   = RHO * D1;

// LCD_PANEL chooses a small positive colour saving for illustration; its sign is not universal.
const BL1 = 1.0, R_LCD = 0.80, LCD_PANEL = 0.01;

const g = (b) => Math.pow(b, GAMMA);
const content = (f) => (1 - f) + f * K_RES;

function power(type, b, f) {
  if (type === 'LCD') {
    const disp = BL1 * b + LCD_PANEL * content(f);
    return { disp, rest: R_LCD, total: R_LCD + disp };
  }
  const d = D1 * g(b) * content(f);
  return { disp: d, rest: R, total: R + d };
}
function darkSavings(type, b) {
  const pl = power(type, b, F_LIGHT).total;
  const pd = power(type, b, F_DARK).total;
  return (pl - pd) / pl;
}
function dimDisplayRatio(type, f) {
  return power(type, 1.0, f).disp / power(type, 0.5, f).disp;
}

// ── harness ──────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
const P = (x) => (x * 100);
function check(name, cond, detail) {
  const ok = !!cond;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ::  ' + detail : ''}`);
  ok ? pass++ : fail++;
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('== does-dark-mode-save-battery :: verifier ==');
console.log(`model: GAMMA=${GAMMA.toFixed(6)}  C_L=${C_L}  C_D=${C_D}  RHO=${RHO.toFixed(6)}  R=${R.toFixed(6)}W\n`);

// 1) The 10x dimming ratio — TWO independent ways.
const ratioA = g(1.0) / g(0.5);                 // direct
const ratioB = Math.pow(2, GAMMA);              // since GAMMA=log2(10) => 2^GAMMA=10
check('10x-A: OLED display g(1)/g(0.5) = 10', near(ratioA, 10, 1e-9), `ratio=${ratioA.toFixed(6)}`);
check('10x-B: 2^GAMMA = 10 (GAMMA=log2 10)', near(ratioB, 10, 1e-9), `2^GAMMA=${ratioB.toFixed(6)}`);
check('10x matches paper "~10x"', near(ratioA, 10, 0.5), 'Purdue: ~10x');

// 2) Full-brightness OLED savings = 43%, inside paper 39-47%. TWO ways.
const s100_A = darkSavings('OLED', 1.0);                              // formula
const dispShare100 = power('OLED', 1.0, F_LIGHT).disp / power('OLED', 1.0, F_LIGHT).total;
const s100_B = dispShare100 * ((C_L - C_D) / C_L);                   // displayShare * per-display saving
check('Sav(100%) = 43% (calibration target)', near(P(s100_A), 43, 0.2), `${P(s100_A).toFixed(2)}%`);
check('Sav(100%) two-way agreement', near(s100_A, s100_B, 1e-12), `A=${P(s100_A).toFixed(4)} B=${P(s100_B).toFixed(4)}`);
check('Sav(100%) inside Purdue 39-47%', P(s100_A) >= 39 && P(s100_A) <= 47, `${P(s100_A).toFixed(1)}%`);

// 3) Everyday brightness (40%) OLED savings inside paper 3-9%.
const s40 = darkSavings('OLED', 0.4);
check('Sav(40%) inside Purdue 3-9%', P(s40) >= 3 && P(s40) <= 9, `${P(s40).toFixed(2)}%`);

// 4) 30-50% band: single digits with partial overlap, not containment, of 3-9%.
const s30 = darkSavings('OLED', 0.3), s50 = darkSavings('OLED', 0.5);
check('Sav(30%) single digit', P(s30) < 9, `${P(s30).toFixed(2)}%`);
check('Sav(50%) <= 9% (top of everyday band)', P(s50) <= 9.05, `${P(s50).toFixed(2)}%`);
check('band 30-50% monotonic increasing', s30 < s40 && s40 < s50, `${P(s30).toFixed(1)} < ${P(s40).toFixed(1)} < ${P(s50).toFixed(1)}`);
check('band overlaps Purdue 3-9% without covering it',
  P(s30) < 3 && P(s50) >= 3 && P(s50) < 9, `[${P(s30).toFixed(1)}, ${P(s50).toFixed(1)}]%`);

// 5) LCD savings ~0 (backlight-dominated), not literally 0.
const lcd40 = darkSavings('LCD', 0.4), lcd100 = darkSavings('LCD', 1.0);
check('LCD Sav(40%) essentially nothing (<1%)', P(lcd40) < 1, `${P(lcd40).toFixed(3)}%`);
check('LCD Sav(100%) essentially nothing (<1%)', P(lcd100) < 1, `${P(lcd100).toFixed(3)}%`);
check('assumed LCD model savings > 0', lcd40 > 0 && lcd100 > 0, 'chosen positive term, not a measured panel result');
check('OLED >> LCD at full brightness', s100_A > 40 * lcd100, `OLED ${P(s100_A).toFixed(1)}% vs LCD ${P(lcd100).toFixed(3)}%`);

// 6) Device-spread: baseline RHO that reproduces the 39-47% band.
const rhoFor = (sav) => (C_L - C_D) / sav - C_L;    // invert Sav(1)=(C_L-C_D)/(RHO+C_L)
const rho47 = rhoFor(0.47), rho39 = rhoFor(0.39);
check('RHO(47%) reproduces 47% at full bright', near(P(darkSavings2(rho47, 1.0)), 47, 0.05), `RHO=${rho47.toFixed(3)}`);
check('RHO(39%) reproduces 39% at full bright', near(P(darkSavings2(rho39, 1.0)), 39, 0.05), `RHO=${rho39.toFixed(3)}`);
check('default RHO inside device band', RHO > rho47 && RHO < rho39, `${rho47.toFixed(3)} < ${RHO.toFixed(3)} < ${rho39.toFixed(3)}`);

function darkSavings2(rho, b) { // OLED savings for an alternate baseline rho (device variation)
  const rr = rho * D1;
  const pl = rr + D1 * g(b) * C_L;
  const pd = rr + D1 * g(b) * C_D;
  return (pl - pd) / pl;
}

// 7) Comparison-table cells (must equal what the page injects).
const tableRows = [['OLED',1.0],['OLED',0.5],['OLED',0.3],['LCD',1.0],['LCD',0.5],['LCD',0.3]];
console.log('\n  comparison table (dark-savings / display-share / dim-100->50 display ratio):');
for (const [type, b] of tableRows) {
  const sav = darkSavings(type, b);
  const pl = power(type, b, F_LIGHT);
  const share = pl.disp / pl.total;
  const ratio = dimDisplayRatio(type, F_LIGHT);
  const sane = sav >= 0 && sav < 0.5 && share > 0 && share < 1 && ratio >= 1;
  check(`table ${type} @${Math.round(b*100)}%`, sane,
    `dark ${P(sav).toFixed(1)}% | display ${P(share).toFixed(0)}% | dim ${ratio.toFixed(1)}x`);
}
// OLED dim ratio must be 10x; LCD dim ratio must be ~2x (backlight linear).
check('table OLED dim ratio = 10x', near(dimDisplayRatio('OLED', F_LIGHT), 10, 1e-6));
check('table LCD dim ratio ~2x (backlight linear, weaker lever)',
  dimDisplayRatio('LCD', F_LIGHT) > 1.9 && dimDisplayRatio('LCD', F_LIGHT) < 2.05,
  `${dimDisplayRatio('LCD', F_LIGHT).toFixed(3)}x`);

// 8) Sanity: illustrative full-white total draw shown in the readout.
const totalFull = power('OLED', 1.0, F_LIGHT).total;
check('readout total(light,100%) ~ 1.66 W (illustrative)', near(totalFull, 1.6575, 0.01), `${totalFull.toFixed(4)} W`);

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