#!/usr/bin/env node
// Offline gate for the "should you unplug chargers to save money" stratum.
// Recomputes EVERY number shown on the page from first principles, two independent
// ways where possible, and exits non-zero if any check fails.
//
// The single formula on the page:
//   annual cost ($/yr) = watts x 24 h x 365 d / 1000  x  rate ($/kWh)
//                      = watts x 8.76 (kWh per W-year) x rate
//
// Metered / typical anchors (sourced, see README):
//   bare phone charger 0.26 W, laptop charger 4.42 W  (LBNL Standby Power table)
//   Xbox One instant-on 12.5 W, cable/DVR ~22 W, whole-home idle 164 W / $165 (NRDC 2015)

const HRS = 8760;                              // hours per year
const kwhPerYear = (w) => (w * 24 * 365) / 1000;   // method A: explicit 24 x 365
const kwhPerYearB = (w) => w * 8.76;               // method B: the page's shorthand
const cost = (w, rate) => kwhPerYear(w) * rate;

let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, got, want, tol) {
  const ok = approx(got, want, tol);
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}  ->  got ${(+got).toFixed(4)}, want ${want} (+/-${tol})`);
  ok ? pass++ : fail++;
  return ok;
}
function assert(name, cond, detail = '') {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ->  ' + detail : ''}`);
  cond ? pass++ : fail++;
  return cond;
}

console.log('== two-way formula consistency ==');
// Method A (24 x 365) and method B (x 8.76) must agree for any watts/rate.
for (const w of [0.26, 4.42, 12.5, 22, 164]) {
  for (const r of [0.11, 0.13, 0.17, 0.229]) {
    if (!approx(kwhPerYear(w) * r, kwhPerYearB(w) * r, 1e-9)) {
      assert(`24x365 == x8.76 for ${w} W @ $${r}`, false);
    }
  }
}
assert('kWh-per-W-year factor is exactly 8.76', approx(kwhPerYear(1), 8.76, 1e-12), '24 x 365 / 1000 = 8.76');

console.log('\n== the charger (the myth) ==');
check('charger 0.26 W -> kWh/yr', kwhPerYear(0.26), 2.2776, 1e-4);
check('charger 0.26 W @ $0.17/kWh', cost(0.26, 0.17), 0.3872, 2e-3);            // ~$0.39 page verdict
check('charger @ $0.13 (low US rate)', cost(0.26, 0.13), 0.2961, 2e-3);
check('charger @ $0.229 (high US rate)', cost(0.26, 0.229), 0.5216, 2e-3);
assert('charger stays in the $0.30-0.52 "pennies" band across US rates',
  cost(0.26, 0.13) >= 0.29 && cost(0.26, 0.229) <= 0.53,
  `$${cost(0.26,0.13).toFixed(2)} .. $${cost(0.26,0.229).toFixed(2)}`);

console.log('\n== the honest edges (chargers that are not whispers) ==');
check('laptop brick 4.42 W @ $0.17', cost(4.42, 0.17), 6.582, 0.02);           // ~$6.5/yr
check('wireless pad 2 W @ $0.17', cost(2, 0.17), 2.978, 0.02);
assert('laptop brick is ~17x a bare charger (order of magnitude more)',
  approx(4.42 / 0.26, 17.0, 0.2), `4.42/0.26 = ${(4.42/0.26).toFixed(1)}x`);
assert('wireless pad is ~8x a bare charger (order of magnitude more)',
  (2 / 0.26) >= 5 && (2 / 0.26) <= 12, `2/0.26 = ${(2/0.26).toFixed(1)}x`);

console.log('\n== the cable box (the real vampire) ==');
check('DVR 22 W -> kWh/yr', kwhPerYear(22), 192.72, 1e-2);
check('DVR 22 W @ $0.17', cost(22, 0.17), 32.76, 0.02);                          // ~$30 verdict
check('Xbox instant-on 12.5 W @ $0.17', cost(12.5, 0.17), 18.62, 0.02);
check('DVR / charger watt ratio', 22 / 0.26, 84.6, 0.1);                         // "~85 chargers"
assert('one DVR is 80-90x a bare charger (the 85x headline)',
  (22 / 0.26) >= 80 && (22 / 0.26) <= 90, `${(22/0.26).toFixed(1)}x`);

console.log('\n== whole-home benchmark (NRDC 2015, CA-metered) ==');
const NRDC_W = 164, NRDC_COST = 165;
const NRDC_RATE = NRDC_COST / kwhPerYear(NRDC_W);   // implied rate that reproduces $165
check('NRDC 164 W -> kWh/yr', kwhPerYear(NRDC_W), 1436.64, 0.1);
check('implied NRDC rate reproducing $165', NRDC_RATE, 0.1149, 1e-3);
check('164 W @ implied rate = $165', cost(NRDC_W, NRDC_RATE), 165.0, 0.5);
assert('NRDC $165 is NOT the page-default result (must not be conflated with $0.17 rate)',
  Math.abs(cost(NRDC_W, 0.17) - 165) > 50,
  `164 W @ $0.17 = $${cost(NRDC_W, 0.17).toFixed(0)} (rate-dependent, not $165)`);
assert('unplugging chargers cannot reach $165 (whole-home is 60+ devices)',
  cost(0.26 * 4, 0.17) < 5, `4 chargers @ $0.17 = $${cost(0.26*4,0.17).toFixed(2)}/yr`);

console.log('\n== the ledger: default home totals (matches index.html DEFAULTS) ==');
const DEFAULTS = [
  { id:'phone',   w:0.26, qty:2, isCharger:true },
  { id:'laptop',  w:4.42, qty:1 },
  { id:'pad',     w:2,    qty:1 },
  { id:'tv',      w:1,    qty:2 },
  { id:'console', w:12.5, qty:1 },
  { id:'dvr',     w:22,   qty:1, isDvr:true },
  { id:'desktop', w:3,    qty:1 },
  { id:'speaker', w:2,    qty:2 },
  { id:'router',  w:6,    qty:1 },
];
const rate = 0.17;
const totalW = DEFAULTS.reduce((s, d) => s + d.w * d.qty, 0);
const totalCost = DEFAULTS.reduce((s, d) => s + cost(d.w * d.qty, rate), 0);
const chargerCost = DEFAULTS.filter(d => d.isCharger).reduce((s, d) => s + cost(d.w * d.qty, rate), 0);
const dvr = DEFAULTS.find(d => d.isDvr);
const dvrCost = cost(dvr.w * dvr.qty, rate);
check('default home total watts', totalW, 56.44, 1e-6);
check('default home total $/yr @ $0.17', totalCost, 84.05, 0.05);
assert('rows sum to the home total (ledger self-consistency)',
  approx(DEFAULTS.reduce((s, d) => s + cost(d.w * d.qty, rate), 0), totalCost, 1e-9));
console.log('\n== the recovery gap (the whole point) ==');
check('unplug all chargers recovers ($/yr)', chargerCost, 0.7744, 2e-3);
check('unplug the cable box recovers ($/yr)', dvrCost, 32.76, 0.02);
assert('unplugging every charger recovers well under $1',
  chargerCost < 1, `$${chargerCost.toFixed(2)}/yr`);
assert('unplugging one cable box recovers > $25 (dwarfs the chargers)',
  dvrCost > 25 && dvrCost / chargerCost > 30,
  `DVR $${dvrCost.toFixed(2)} vs chargers $${chargerCost.toFixed(2)} = ${(dvrCost/chargerCost).toFixed(0)}x`);

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