#!/usr/bin/env node
/**
 * verify-the-evening-you-could-afford.mjs — the offline check behind
 * /strata/the-evening-you-could-afford/.
 *
 *   node verify-the-evening-you-could-afford.mjs
 *
 * WHAT IT CHECKS, and why each one can actually fail.
 *
 *  A. THE PAGE'S OWN ARITHMETIC. The <script id="evening-model"> block is lifted out of
 *     the shipped HTML bytes and run in a Node vm, then required to agree with the
 *     independent implementation in research/light-labour-price/light.mjs across a sweep
 *     of inputs. The page recomputes its readouts live; if its formulas drift from the
 *     ones that built the tables it prints, this goes red.
 *
 *  B. THE TRANSCRIPTION. The printed tables were typed in by hand from page images. Three
 *     of them overlap, so they can be played off each other: Table 1.5's price column has
 *     to reappear in Table 1.6, and Table 1.3's two efficiency columns are the same
 *     quantity in different units. A typo in the transcription breaks these.
 *
 *  C. THE REPRODUCTION. Every row of the labour-price table, recomputed from its own
 *     printed price and wage on interval arithmetic (a printed 0.124 is an interval, not
 *     a number). This is the paper's central claim and it either follows from its inputs
 *     or it does not.
 *
 *  D. THE RECOVERED CONSTANTS. Three numbers recovered or cross-checked, each pinned by a
 *     second independent route: 13 lumens per candlepower (nine 1855 price rows), a
 *     200-hour Babylonian month (two separately printed answers), and the electricity
 *     price inside every electric row (checked at 1883 against Edison's own quoted price
 *     list, and from 1960 against EIA's published series).
 *
 *  E. THE FOUR INCONSISTENCIES the page claims to have found. Each is asserted here as a
 *     positive fact, so if one of them is not real, or stops being real, this goes red
 *     rather than silently standing as an accusation.
 *
 *  F. THE PHYSICAL AUDIT. The engineering assumptions against measurements published
 *     after 1996 (NIST's candle, Mills's wick lamps, IPCC calorific values). Both the
 *     vindications and the misses are asserted.
 *
 *  G. THE 2026 ROW, rebuilt from the four committed data snapshots, plus the method check
 *     that matters more than the row: running the same arithmetic on 1992's inputs has to
 *     land on 1992's printed answer.
 *
 *  H. STALENESS. The data block the page inlines is re-derived from the committed sources
 *     and required to equal the shipped bytes exactly (the failure mode documented in
 *     scripts/check-inlined-data.mjs).
 */
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

import * as L from './research/light-labour-price/light.mjs';
import * as M from './research/light-labour-price/modern.mjs';
import { CONSTANTS } from './research/light-labour-price/constants.mjs';
import { buildData, MARK_OPEN, MARK_CLOSE } from './research/light-labour-price/build-page-data.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const R = (p) => path.join(ROOT, p);
const PAGE_PATH = R('public/strata/the-evening-you-could-afford/index.html');

let passed = 0, failed = 0;
const fails = [];
function head(s) { console.log('\n' + s); console.log('-'.repeat(s.length)); }
function check(name, ok, detail) {
  if (ok) { passed++; console.log(`  ok   ${name}${detail ? '  (' + detail + ')' : ''}`); }
  else { failed++; fails.push(name); console.log(`  FAIL ${name}${detail ? '  (' + detail + ')' : ''}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const rel = (a, b) => Math.abs(a - b) / Math.abs(b);

const pub = JSON.parse(fs.readFileSync(R('research/light-labour-price/published/nordhaus-1996.json'), 'utf8'));
const res = JSON.parse(fs.readFileSync(R('research/light-labour-price/results.json'), 'utf8'));
const html = fs.readFileSync(PAGE_PATH, 'utf8');

/* ===================================================== A. the page's own arithmetic */
head("A. the page's own arithmetic, lifted out of the shipped bytes");

const mStart = html.indexOf('<script id="evening-model">');
const mEnd = html.indexOf('</' + 'script>', mStart);
check('page ships an #evening-model block', mStart > 0 && mEnd > mStart);
const modelSrc = html.slice(html.indexOf('>', mStart) + 1, mEnd);
const sandbox = { Math, Object, Array, JSON, Number, console };
sandbox.globalThis = sandbox;
vm.createContext(sandbox);
vm.runInContext(modelSrc, sandbox, { filename: 'evening-model' });
const P = sandbox.EVENING;
check('the block defines the model API',
  !!(P && P.labourPrice && P.luxAt && P.sourcesForLux && P.onePercentYear && P.electricRow));

{
  let bad = 0, n = 0, worst = 0;
  for (let price = 0.05; price < 200; price *= 1.7) {
    for (let wage = 5; wage < 4000; wage *= 2.3) {
      n++;
      const d = rel(P.labourPrice(price, wage), L.labourPrice(price, wage));
      if (d > 1e-12) bad++;
      worst = Math.max(worst, d);
    }
  }
  check('page labour price agrees with light.mjs', bad === 0, `${n} pairs, worst ${worst.toExponential(1)}`);
}
{
  // The page assumes isotropy nowhere the source gives a candlepower, so compare in candela.
  let bad = 0, n = 0, worst = 0;
  for (const I of [0.135, 0.75, 1.0, 16, 67.6]) {
    for (let h = 0.02; h < 1.5; h *= 1.4) {
      for (const r of [0, 0.05, 0.1373, 0.3]) {
        n++;
        const a = P.luxAt(I, h, r);
        const b = (I * h) / Math.pow(h * h + r * r, 1.5);
        const d = rel(a, b); if (d > 1e-12) bad++; worst = Math.max(worst, d);
      }
    }
  }
  check('page illuminance is the inverse square with cosine of incidence', bad === 0, `${n} points, worst ${worst.toExponential(1)}`);
}
{
  // luxAt at r = 0 must equal luxBelow, and light.mjs's luxAt(flux,d) must equal the
  // page's luxAt(flux/4pi, d, 0). Two implementations, one geometry.
  let ok = true;
  for (const flux of [1.7, 9.75, 850]) {
    for (const d of [0.1, 0.3, 1.0]) {
      if (rel(P.luxBelow(flux / P.SPHERE_SR, d), L.luxAt(flux, d)) > 1e-12) ok = false;
      if (rel(P.luxAt(flux / P.SPHERE_SR, d, 0), L.luxAt(flux, d)) > 1e-12) ok = false;
    }
  }
  check('page and engine agree on flux-to-illuminance', ok);
}
{
  // The best-height result: h = r/sqrt(2), and the centre-to-corner ratio there is
  // 3*sqrt(3) for every lamp. Checked by brute force against a scan over h.
  const r = 0.1373, I = 0.75;
  let bestH = 0, bestE = -1;
  for (let h = 0.001; h < 1; h += 0.0001) {
    const E = P.luxAt(I, h, r);
    if (E > bestE) { bestE = E; bestH = h; }
  }
  check('the best height is r/sqrt(2)', near(bestH, P.bestHeightFor(r), 2e-4), `scan ${bestH.toFixed(4)} vs ${P.bestHeightFor(r).toFixed(4)}`);
  check('best corner illuminance closed form matches the scan', rel(P.bestCornerLux(I, r), bestE) < 1e-3);
  const ratio = P.luxBelow(I, P.bestHeightFor(r)) / P.bestCornerLux(I, r);
  check('centre-to-corner ratio at the best height is 3*sqrt(3)',
    rel(ratio, 3 * Math.sqrt(3)) < 1e-9 && rel(ratio, P.CENTRE_CORNER_RATIO) < 1e-12, ratio.toFixed(6));
  // and it really is lamp-independent
  const ratio2 = P.luxBelow(999, P.bestHeightFor(r)) / P.bestCornerLux(999, r);
  check('and it does not depend on the lamp', rel(ratio, ratio2) < 1e-12);
  // sourcesForLux inverts bestCornerLux
  const n = P.sourcesForLux(500, I, r);
  check('sourcesForLux inverts the corner illuminance', rel(P.bestCornerLux(n * I, r), 500) < 1e-9, `${n.toFixed(2)} candles`);
}
{
  // The wage cancels in the one-per-cent instrument. If it does not, the section is wrong.
  const a = P.onePercentYear(5.37, 9.75, 2000);
  const b = P.onePercentYear(5.37, 9.75, 2000);
  check('one per cent of a working year takes no wage at all',
    P.onePercentYear.length === 3 && a.deviceHoursPerNight === b.deviceHoursPerNight,
    `${a.deviceHoursPerNight.toFixed(3)} candle-hours a night in 1800`);
  const e = P.electricRow(19.8, 170, 3764);
  const e2 = L.electricRow({ centsPerKWh: 19.8, lumensPerWatt: 170, wageCentsPerHour: 3764 });
  check('page electric row agrees with light.mjs', rel(e.hoursPer1000LumenHours, e2.hoursPer1000LumenHours) < 1e-12);
}

/* ============================================================ B. the transcription */
head('B. the transcription, played off itself');

{
  const x = L.crossTable15vs16(pub);
  const disagree = x.filter((r) => !r.agree);
  // Every price in the labour table must reappear in the price table. The only figure that
  // is not character-identical is 1875-85 town gas, printed 5.035 in one and 5.0345 in the
  // other, which is the same number to one more digit and inside the 0.001 tolerance.
  check('Table 1.5 and Table 1.6 print the same prices', disagree.length === 0,
    `${x.length} device-date groups agree; the only non-identical figure is 5.0345 against 5.035`);
  const gas = x.find((g) => g.key === 'Town gas|1875-85');
  check('and that one difference really is only the last digit',
    near(gas.table16[0], 5.0345, 1e-9) && near(gas.table15[0], 5.035, 1e-9));
  const n = x.reduce((a, g) => a + g.n, 0);
  check('and between them they carry every priced row', n === 27, `${n} prices in ${x.length} groups`);
}
{
  const t13 = L.reproduceTable13Columns(pub);
  const worst = Math.max(...t13.map((r) => r.relErr));
  check("Table 1.3's two efficiency columns are one quantity", worst < 0.006,
    `${t13.length} rows, worst ${(worst * 100).toFixed(2)}% at ${L.WH_PER_1000BTU.toFixed(4)} Wh per 1,000 Btu`);
}
check('every Table 1.6 row with a price has that price in Table 1.5',
  pub.table_1_6.rows.filter((r) => r[5] != null).length === 27);
check('the three prehistoric rows carry no price and no wage',
  pub.table_1_6.rows.slice(0, 3).every((r) => r[3] === null && r[5] === null));

/* ================================================================ C. the reproduction */
head('C. the labour-price table, recomputed from its own printed inputs');

const t16 = L.reproduceTable16(pub);
{
  const bad = t16.filter((r) => !r.consistent);
  check('every row lies inside the interval its printed inputs allow', bad.length === 0,
    `${t16.length - bad.length}/${t16.length}` + (bad.length ? ' failing: ' + bad.map((b) => b.date).join(', ') : ''));
  const exact = t16.filter((r) => r.exactAtPrintedPrecision).length;
  check('and more than half are exact at the printed precision', exact >= 14, `${exact}/${t16.length}`);
  // The claim this section rests on is that a POINT comparison would flag rows that are in
  // fact perfectly consistent with their own printed inputs. That count was prose until
  // 2026-08-03; it is now asserted, so it cannot drift.
  const intervalOnly = t16.filter((r) => r.consistent && !r.exactAtPrintedPrecision);
  check('twelve rows pass on intervals and would fail a point comparison',
    intervalOnly.length === 12, `${intervalOnly.length}: ` +
    intervalOnly.map((r) => `${r.date} ${r.stage}`).join('; '));
  // The interval test would be vacuous if the intervals were wide, so bound them, and name
  // the widest correctly. CORRECTED 2026-08-03: this comment used to attribute the widest
  // window to the 1916 Welsbach row "printed to two decimals (0.012)", which is wrong three
  // ways: 0.012 is three decimals, that row's window is 0.65%, and the widest window is the
  // 1990 filament row at 16.7% because its price is recorded here as 0.6, to one decimal.
  // See the note in published/nordhaus-1996.json: whether the page prints 0.6 or 0.600 is an
  // open question that needs the page images, and if it prints 0.600 this window is 60 times
  // too wide.
  const widths = t16.map((r) => (r.interval[1] - r.interval[0]) / r.printedHours).sort((a, b) => a - b);
  const median = widths[Math.floor(widths.length / 2)];
  const widest = widths[widths.length - 1];
  const widestRow = t16.reduce((a, r) =>
    ((r.interval[1] - r.interval[0]) / r.printedHours > (a.interval[1] - a.interval[0]) / a.printedHours ? r : a));
  check('the intervals are tight enough for the test to bite', median < 0.02 && widest < 0.2,
    `median ${(median * 100).toFixed(2)}%, widest ${(widest * 100).toFixed(1)}% of the printed value`);
  check('and the widest window is the row whose price carries the fewest decimals',
    widestRow.date === '1990', `${widestRow.date} ${widestRow.stage}, price recorded as ${widestRow.printedCents}`);
  // and a deliberate falsification: perturbing one price by 5% must break its row
  const row = t16.find((r) => r.date === '1800' && r.stage === 'Tallow');
  const lo = (row.printedCents * 1.05 - 0.0005) / (row.wage + 0.05);
  check('a 5% error in one price would be caught', lo > row.printedHours + 0.005);
}

/* ========================================================= D. the recovered constants */
head('D. three constants recovered or cross-checked');

{
  const lpc = L.impliedLumensPerCandlepower(pub).map((r) => r.lumensPerCandlepower);
  const mean = lpc.reduce((a, b) => a + b, 0) / lpc.length;
  check('13 lumens per candlepower, from nine 1855 price rows',
    Math.min(...lpc) > 12.5 && Math.max(...lpc) < 13.1 && near(mean, 12.93, 0.05),
    `mean ${mean.toFixed(3)}, range ${Math.min(...lpc).toFixed(2)} to ${Math.max(...lpc).toFixed(2)}`);
  check('and it is not 4*pi, but close to it', mean > L.SPHERE_SR && mean / L.SPHERE_SR < 1.04,
    `${(100 * (mean / L.SPHERE_SR - 1)).toFixed(1)}% above 4*pi`);
}
{
  const m1 = L.solveBabylonMonthHours(pub, 41.50);
  const m2 = L.solveBabylonMonthHours(pub, 42, { lumenHours: 28.6 });
  check('a 200-hour Babylonian month reproduces both printed answers',
    near(m1, 200, 0.5) && near(m2, 200, 0.5), `${m1.toFixed(1)} and ${m2.toFixed(1)} hours`);
  check('it is not the 250-hour month used for US farm workers', Math.abs(m1 - 250) > 40);
  const b = L.reproduceBabylon(pub, { monthHours: 200 });
  check('the 1750 BC labour price rebuilds from oil, price and wage', near(b.hoursPer1000LumenHours, 41.50, 0.05),
    `${b.hoursPer1000LumenHours.toFixed(3)} against a printed 41.50`);
}
{
  const el = L.impliedElectricityPrice(pub);
  const e1883 = el.find((e) => e.date === '1883');
  check("1883 inverts to Edison's own quoted price", near(e1883.centsPerKWh, 24, 0.5),
    `${e1883.centsPerKWh.toFixed(2)} cents per kWh against "approximately twenty-four"`);
  const eia = M.readEiaResidential();
  // Table 1.5 note i states that the 1990 row's price of electricity is "as of 1992", so it
  // is tested against 1992's published price rather than 1990's. Honouring the footnote is
  // the point: without it the row looks 9% out, and with it the whole comparison holds.
  const yearFor = (d) => (d === '1990' ? 1992 : Number(d));
  const cmp = el.filter((e) => eia.has(yearFor(e.date)))
    .map((e) => ({ date: e.date, d: rel(e.centsPerKWh, eia.get(yearFor(e.date))) }));
  const worst = Math.max(...cmp.map((c) => c.d));
  check('1960 to 1992 land within 6% of EIA published residential prices', worst < 0.06,
    `${cmp.length} years, worst ${(worst * 100).toFixed(1)}% at ${cmp.find((c) => c.d === worst).date}`);
  check("and the 1990 row really does carry 1992's price, as its footnote says",
    /Price of electricity as of 1992/.test(pub.table_1_5.rows ? JSON.stringify(pub.table_1_5) : '') ||
    rel(el.find((e) => e.date === '1990').centsPerKWh, el.find((e) => e.date === '1992').centsPerKWh) < 0.01,
    `1990 inverts to ${el.find((e) => e.date === '1990').centsPerKWh.toFixed(2)}, 1992 to ${el.find((e) => e.date === '1992').centsPerKWh.toFixed(2)}`);
}
{
  const f = L.reproduceFire(pub);
  check('the open fire rebuilds from the appendix measurements',
    near(f.lumenHoursPerPound, 1.7, 0.01) && near(f.lumenHoursPer1000Btu, 0.69, 0.011) && near(f.hoursPer1000LumenHours, 58, 0.9),
    `${f.lumenHoursPerPound.toFixed(2)} lm-h/lb, ${f.lumenHoursPer1000Btu.toFixed(3)} per 1,000 Btu, ${f.hoursPer1000LumenHours.toFixed(1)} hours`);
}

/* ==================================================== E. the four inconsistencies */
head('E. the four internal inconsistencies the page claims');

{
  const n = L.reproduceNeolithic(pub);
  check('1. the Neolithic lamp has two footnote definitions that disagree',
    near(n.fromTallow, n.printed, 1e-4) && !near(n.fromBabylon, n.printed, 1e-3),
    `one-fifth of tallow gives ${n.fromTallow} (= printed ${n.printed}); one-third of Babylon gives ${n.fromBabylon}`);
  check('   and only the second reproduces the printed labour price of 50',
    near(n.viaBabylonThird, 50, 0.5) && Math.abs(n.viaTallowFifth - 50) > 10,
    `${n.viaBabylonThird.toFixed(1)} vs ${n.viaTallowFifth.toFixed(1)}`);
}
{
  const t14 = pub.table_1_4.rows.find((r) => r[0] === '1800')[4];
  const t16v = pub.table_1_6.rows.find((r) => r[2] === '1800' && r[1] === 'Tallow')[4];
  check('2. Table 1.4 and Table 1.6 print different 1800 labour prices',
    t14 === 5.387 && t16v === 5.37, `${t14} vs ${t16v}, though 1.4 col (4) says "From table 1.6"`);
  check('   and the difference is a wage, not a typo',
    near(40.293 / t14, 7.479, 0.002), `1.4 implies a wage of ${(40.293 / t14).toFixed(3)} where 1.6 prints 7.5`);
}
{
  const rows1855 = pub.table_1_6.rows.filter((r) => r[2] === '1855');
  const wages = rows1855.map((r) => r[3]);
  const kero = rows1855.find((r) => r[0] === 'Kerosene lamp');
  check('3. the 1855 kerosene row uses a wage the other 1855 rows do not',
    kero[3] === 17.5 && wages.filter((w) => w === 10).length === 3,
    `kerosene at 17.5, the other three at 10`);
  check('   which the experiment table explains: its kerosene price is 1870s',
    /kerosene refers to 1870/i.test(pub.table_1_2.note_a));
}
{
  // Town gas: 500 Btu per cubic foot in note g, but Table 1.2's Btu column needs 550.
  const noteG = pub.table_1_3.notes.g;
  check('4. the gas footnote says 500 Btu per cubic foot', /500 Btu per cubic foot/.test(noteG));
  const gasRows = L.impliedFuelEnergy(pub, { lumensPerCandlepower: 13 }).filter((r) => r.kind === 'gas');
  const implied = gasRows.map((r) => r.impliedBtuPerCubicFoot);
  const mean = implied.reduce((a, b) => a + b, 0) / implied.length;
  check('   but its own Btu column only reproduces near 550', near(mean, 550, 15) && !near(mean, 500, 15),
    `four gas rows imply ${mean.toFixed(0)} Btu per cubic foot`);
}

/* ============================================================== F. the physical audit */
head('F. the engineering, against measurements published after 1996');

const phys = res.physical;
{
  check("the candle's implied fuel energy is within 1% of NIST's paraffin",
    Math.abs(phys.candle.relToParaffin) < 0.01,
    `${phys.candle.impliedMJPerKg.toFixed(2)} MJ/kg against ${CONSTANTS.paraffinWax.netMJPerKg} +/- ${CONSTANTS.paraffinWax.netSD}`);
  check('and comfortably above the published gross value for beef tallow',
    phys.candle.relToTallow > 0.05 && phys.candle.relToTallow < 0.15,
    `+${(phys.candle.relToTallow * 100).toFixed(0)}% over ${CONSTANTS.beefTallow.grossMJPerKg}`);
}
{
  const band = CONSTANTS.wickLampEfficacy.lumensPerWatt;
  check("Nordhaus's sperm-candle efficacy is inside the range derived from Mills's four lamps",
    phys.candleEfficacy.nordhaus >= band[0] && phys.candleEfficacy.nordhaus <= band[1],
    `${phys.candleEfficacy.nordhaus} lm/W in [${band[0]}, ${band[1]}]`);
  check("and so is his whale-oil lamp",
    phys.candleEfficacy.whaleOil >= band[0] && phys.candleEfficacy.whaleOil <= band[1],
    `${phys.candleEfficacy.whaleOil} lm/W`);
  check('the illustrative isotropic comparison uses NIST heat release, not Nordhaus thermal power',
    near(phys.candleEfficacy.naiveIsotropic, 4 * Math.PI / CONSTANTS.candleFlame.heatReleaseW, 1e-12) &&
    near(phys.candle.thermalW, 13 / phys.candleEfficacy.nordhaus, 1e-9) &&
    Math.abs(phys.candle.thermalW - CONSTANTS.candleFlame.heatReleaseW) > 1,
    `${phys.candleEfficacy.naiveIsotropic.toFixed(4)} lm/W uses ${CONSTANTS.candleFlame.heatReleaseW} W; Nordhaus implies ${phys.candle.thermalW.toFixed(2)} W`);
  const ab = phys.candleEfficacy.anisotropyCorrectedBand;
  check('Nordhaus is below the illustrative NIST/Mills band without uncertainty propagation',
    ab.every((value, i) => near(value, 4 * Math.PI * CONSTANTS.wickFlameAnisotropy.sphericalReductionFactor[i] / CONSTANTS.candleFlame.heatReleaseW, 1e-12)) &&
    phys.candleEfficacy.nordhaus < ab[0],
    `${phys.candleEfficacy.nordhaus} below ${ab[0].toFixed(4)} to ${ab[1].toFixed(4)}`);
}
{
  check("the firewood assumption sits below the IPCC's lower bound",
    phys.firewood.belowIpccLowerBound,
    `${phys.firewood.impliedMJPerKg.toFixed(2)} MJ/kg against a default ${CONSTANTS.firewood.netMJPerKg} and a range ${CONSTANTS.firewood.rangeMJPerKg.join(' to ')}`);
  check('but it cannot move the labour price of a fire, which never uses Btu',
    (() => {
      const f = L.reproduceFire(pub);
      // the labour price is lumen-hours per pound times pounds per hour; energy never enters
      return near(1000 / (f.lumenHoursPerPound * pub.appendix.fire.poundsForagedPerHour), f.hoursPer1000LumenHours, 1e-9);
    })());
  check('the sesame lamp implies an oil about a fifth thin',
    phys.sesameLamp.relToPublished < -0.15 && phys.sesameLamp.relToPublished > -0.30,
    `${phys.sesameLamp.impliedMJPerKg.toFixed(2)} MJ/kg against ${CONSTANTS.sesameOil.rangeMJPerKg.join(' to ')}`);
  check('but the 1750 BC labour price never uses Btu either',
    near(L.reproduceBabylon(pub, { monthHours: 200 }).hoursPer1000LumenHours, 41.50, 0.05));
}
check('the total luminous flux of a candle is recorded as not measured',
  CONSTANTS.candleTotalFlux.confidence === 'none' && CONSTANTS.spermOil.confidence === 'none');

/* ================================================================== G. the 2026 row */
head('G. the row after 1992, and the method that produced it');

{
  const m = M.methodCheck1992(pub);
  // Same interval logic as section C: the printed price 0.124 and wage 1,049.6 are each
  // known only to their last digit, so the test is whether the printed labour price lies
  // in the window they allow.
  const lo = (m.printedPrice - L.halfULP(m.printedPrice)) / (m.printedWage + L.halfULP(m.printedWage));
  const hi = (m.printedPrice + L.halfULP(m.printedPrice)) / (m.printedWage - L.halfULP(m.printedWage));
  const aHalf = L.halfULP(m.printedHours);
  check("the modern method lands on 1992's printed answer",
    m.printedHours + aHalf >= lo && m.printedHours - aHalf <= hi,
    `${m.row.hoursPer1000LumenHours.toExponential(4)} against a printed ${m.printedHours}, window ${lo.toExponential(3)} to ${hi.toExponential(3)}`);
  check('and the electricity price it implies is what was being charged',
    near(m.impliedCentsPerKWh, 8.2, 0.4), `${m.impliedCentsPerKWh.toFixed(2)} cents per kWh in 1992`);
}
{
  const mod = M.modernRows();
  check('the wage snapshot parses', mod.wageDollarsPerHour > 20 && mod.wageDollarsPerHour < 100,
    `$${mod.wageDollarsPerHour}/hour, ${mod.asOf.wage}`);
  check('the electricity snapshot parses', mod.electricityDollarsPerKWh > 0.05 && mod.electricityDollarsPerKWh < 1,
    `$${mod.electricityDollarsPerKWh}/kWh, ${mod.asOf.electricity}`);
  check('every certified lamp record parses', mod.population.totalRecords === 8659,
    `${mod.population.totalRecords} records, ${mod.population.bandRecords} in the 400 to 1,600 lumen band`);
  check('the certified efficacy column is the certified lumens over the certified watts',
    mod.population.medianAbsResidual < 0.5 && mod.population.residualsOver2 / mod.population.bandRecords < 0.02,
    `median |residual| ${mod.population.medianAbsResidual.toFixed(3)} lm/W, ${mod.population.residualsOver2} rows over 2`);
  check('the median certified lamp is near 100 lumens per watt', near(mod.population.p[50], 100, 3),
    `${mod.population.p[50].toFixed(1)} lm/W`);
  check('the selected lamp is internally consistent',
    near(M.LAMPS_2026.frontier.lumens / M.LAMPS_2026.frontier.watts, M.LAMPS_2026.frontier.lumensPerWatt, 0.5),
    `${M.LAMPS_2026.frontier.lumens} lm / ${M.LAMPS_2026.frontier.watts} W = ${M.LAMPS_2026.frontier.lumensPerWatt}`);
  check('and it is not above the physical limit for white light',
    M.LAMPS_2026.frontier.lumensPerWatt < CONSTANTS.whiteLightEfficacyLimit.lumensPerWatt[0],
    `170 lm/W against a ${CONSTANTS.whiteLightEfficacyLimit.lumensPerWatt.join(' to ')} ceiling`);
  const led = res.series.find((s) => s.key === 'led');
  check('the 2026 row is a real improvement on 1992, not a rounding',
    0.000119 / led.hours > 3 && 0.000119 / led.hours < 5,
    `a factor of ${(0.000119 / led.hours).toFixed(2)} since the compact fluorescent`);
  check('Babylon to now is between one and two million',
    res.ratios.babylonToLed > 1e6 && res.ratios.babylonToLed < 2e6,
    `a factor of ${Math.round(res.ratios.babylonToLed).toLocaleString('en-US')}`);
}
{
  const rc = res.readingCost;
  check('the reading cost is 33 tallow candles', near(rc.tallow.candles, 32.6, 0.6), `${rc.tallow.candles.toFixed(1)}`);
  check('an hour of reading cost about an hour and three quarters of work in 1800',
    near(rc.tallow.workHoursPerReadingHour, 1.71, 0.03), `${rc.tallow.workHoursPerReadingHour.toFixed(3)} hours`);
  check('and about a thirtieth of a second in 2026',
    rc.led2026.workSecondsPerReadingHour > 0.02 && rc.led2026.workSecondsPerReadingHour < 0.06,
    `${rc.led2026.workSecondsPerReadingHour.toFixed(4)} seconds`);
  check('spermaceti candles cost more per hour of reading, not less',
    rc.sperm.workHoursPerReadingHour > rc.tallow.workHoursPerReadingHour,
    `${rc.sperm.workHoursPerReadingHour.toFixed(2)} against ${rc.tallow.workHoursPerReadingHour.toFixed(2)} hours`);
}
{
  // The scale anchors the page prints must be the ones the sources give.
  check('the reading standard on the page is the one ISO 8995 prints',
    CONSTANTS.readingStandardLux.lux === 500 && /ISO 8995/.test(CONSTANTS.readingStandardLux.source));
  const tallowLux = 0.75 / (0.3 * 0.3);
  check('a tallow candle at 30 cm is 8.3 lux', near(tallowLux, 8.333, 0.01), tallowLux.toFixed(3));
  // The page claims the candle sits about at the geometric mean of moonlight and the
  // reading standard. Geometric mean of 0.1 and 500 is 7.07 lux; the candle is 8.33.
  const gm = Math.sqrt(CONSTANTS.fullMoonLux.typical[1] * CONSTANTS.readingStandardLux.lux);
  check('and sits within 20% of the geometric mean of moonlight and the standard',
    tallowLux > CONSTANTS.fullMoonLux.typical[1] && tallowLux < CONSTANTS.readingStandardLux.lux &&
    rel(tallowLux, gm) < 0.2,
    `${tallowLux.toFixed(2)} lux against a geometric mean of ${gm.toFixed(2)}; ` +
    `${Math.round(tallowLux / CONSTANTS.fullMoonLux.typical[1])}x the moon, 1/${Math.round(CONSTANTS.readingStandardLux.lux / tallowLux)} of the standard`);
  // the two routes to a candle's intensity, which must agree if 13 stands in for 4*pi
  check('candlepower and total flux give the same candle, within 4%',
    rel(0.75, 9.75 / L.SPHERE_SR) < 0.04, `${0.75} cd against ${(9.75 / L.SPHERE_SR).toFixed(4)} cd`);
}

/* ==================================================================== H. staleness */
head('H. the page renders today, not a frozen yesterday');

{
  const i = html.indexOf(MARK_OPEN);
  const j = html.indexOf(MARK_CLOSE, i);
  check('the page carries an #evening-data block', i > 0 && j > i);
  const shipped = html.slice(i + MARK_OPEN.length, j);
  const rebuilt = '\n' + JSON.stringify(buildData(), null, 1) + '\n';
  check('and it equals the block rebuilt from the committed sources', shipped === rebuilt,
    shipped === rebuilt ? `${shipped.length} bytes` : `shipped ${shipped.length} bytes, rebuilt ${rebuilt.length}`);
}
{
  const data = JSON.parse(html.slice(html.indexOf(MARK_OPEN) + MARK_OPEN.length, html.indexOf(MARK_CLOSE, html.indexOf(MARK_OPEN))));
  // The blob rounds to six significant figures on the way in, so compare at that precision.
  check('the page prints the same 2026 row the engine computed',
    rel(data.series.find((s) => s.key === 'led').hours, res.series.find((s) => s.key === 'led').hours) < 1e-5,
    `${data.series.find((s) => s.key === 'led').hours.toExponential(5)}`);
  check('the page prints the same audit counts',
    data.audit.table16.consistent === res.reproduction.table16.consistent &&
    data.audit.table16.rows === res.reproduction.table16.rows);
  check('the page names what could not be sourced', Array.isArray(data.notFound) && data.notFound.length >= 4,
    `${data.notFound.length} named gaps`);
}
check('the closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
check('the page has no leftover template marks', !html.includes('✎'));

/* ======================================================================== summary */
const total = passed + failed;
console.log(`\n${'='.repeat(60)}`);
console.log(`${passed}/${total} checks green`);
if (failed) { console.log(`FAILED: ${fails.join(' · ')}`); }
// Only a fully green run stamps the count. The page's data block embeds this file, so a
// red run that wrote its own lower count would make the NEXT run fail the staleness check
// for a reason that has nothing to do with staleness, and the failure would look real.
if (!failed) {
  fs.writeFileSync(R('research/light-labour-price/check-count.json'),
    JSON.stringify({ passed, total, when: 'regenerated by verify-the-evening-you-could-afford.mjs, green runs only' }, null, 2) + '\n');
} else {
  console.log('(check-count.json left alone: only a green run stamps it)');
}
process.exit(failed ? 1 : 0);
