#!/usr/bin/env node
//
// verify-the-hour-nobody-spends.mjs
//
// Re-derives every load-bearing number in /strata/the-hour-nobody-spends/ from
// the committed records, and checks three separate things agree:
//
//   (a) an INDEPENDENT re-derivation written here, sharing no code with the
//       analysis in research/the-hour-that-did-not-move/;
//   (b) the committed artifacts that analysis produced;
//   (c) the page's OWN aggregation code, lifted out of the bytes the page ships
//       and run in a node:vm against the same shipped binary, so a reader moving
//       the controls sees the numbers this file computed.
//
//   node verify-the-hour-nobody-spends.mjs [--verbose]
//
// The raw BLS microdata is 1.1 GB and is not committed. The committed record is
// data/diaries.bin: 252,808 rows of ten bytes, which is what the page ships and
// what this file recomputes from. Everything downstream of it is checkable from a
// clean checkout with no network.
//
// Nine families of assertion:
//   1. artifacts and shape                6. Europe, re-read from the API dump
//   2. the packed diaries, re-derived     7. quotations, byte for byte
//   3. the page's own code, in a vm       8. what the page ships
//   4. errors, standardisation, identity  9. the page's prose and head
//   5. England, re-parsed from the .ods

import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const RES = path.join(ROOT, 'research', 'the-hour-that-did-not-move');
const DATA = path.join(RES, 'data');
const PUB = path.join(ROOT, 'public', 'strata', 'the-hour-nobody-spends');
const PAGE = path.join(PUB, 'index.html');
const MD = path.join(ROOT, 'src', 'content', 'strata', 'the-hour-nobody-spends.md');
const VERBOSE = process.argv.includes('--verbose');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; if (VERBOSE) console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const eq = (name, got, want) => ok(name, got === want, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (name, got, want, tol) => ok(name, Math.abs(got - want) <= tol, `got ${got}, want ${want} +-${tol}`);

// ---------------------------------------------------------------------------
console.log('1. artifacts and shape');

const need = ['findings.json', 'standardised.json', 'errors.json', 'nts.json', 'hetus.json', 'quotes.json', 'diaries.bin', 'nts0101.ods', 'hetus_tus00age.json'];
for (const f of need) {
  if (!fs.existsSync(path.join(DATA, f))) { console.log(`  FAIL missing artifact: research/the-hour-that-did-not-move/data/${f}`); process.exit(1); }
}
for (const f of [PAGE, MD, path.join(PUB, 'data.json'), path.join(PUB, 'diaries.bin')]) {
  if (!fs.existsSync(f)) { console.log(`  FAIL missing: ${path.relative(ROOT, f)}`); process.exit(1); }
}

const J = (f) => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));
const F = J('findings.json'), S = J('standardised.json'), E = J('errors.json');
const NT = J('nts.json'), HE = J('hetus.json'), QU = J('quotes.json');
const PD = JSON.parse(fs.readFileSync(path.join(PUB, 'data.json'), 'utf8'));
const html = fs.readFileSync(PAGE, 'utf8');
const flat = html.replace(/\s+/g, ' ');
const md = fs.readFileSync(MD, 'utf8');

const bin = fs.readFileSync(path.join(DATA, 'diaries.bin'));
eq('diaries.bin is a whole number of 10-byte rows', bin.length % 10, 0);
const NROWS = bin.length / 10;
eq('252,808 diaries', NROWS, 252808);
eq('findings agrees on the record count', F.source.records, 252808);
eq('53 travel columns were summed', F.source.travelColumns, 53);

// ---------------------------------------------------------------------------
console.log('2. the packed diaries, re-derived independently');

// its own reader for the packed record, written from the layout comment alone
const row = (i) => {
  const o = i * 10, a = bin[o], b = bin[o + 1];
  return {
    year: 2003 + (a & 31),
    day: a >> 5,
    sex: b & 1,
    employed: (b >> 1) & 1,
    ageLo: 15 + 5 * (b >> 3),
    total: bin.readUInt16LE(o + 2),
    work: bin.readUInt16LE(o + 4),
    weight: bin.readFloatLE(o + 6),
  };
};

const acc = () => ({ n: 0, w: 0, wx: 0, wxx: 0, wz: 0, wt: 0, wxt: 0, wOver: 0 });
const push = (a, x, w) => {
  a.n++; a.w += w; a.wx += w * x; a.wxx += w * x * x;
  if (x === 0) a.wz += w; else { a.wt += w; a.wxt += w * x; }
  if (x > 120) a.wOver += w;
};
const byYear = new Map(), pooled = acc();
let badWeight = 0, badDay = 0, badTotal = 0;
for (let i = 0; i < NROWS; i++) {
  const r = row(i);
  if (!(r.weight > 0)) badWeight++;
  if (r.day < 1 || r.day > 7) badDay++;
  if (r.total > 1440) badTotal++;
  if (!byYear.has(r.year)) byYear.set(r.year, acc());
  push(byYear.get(r.year), r.total, r.weight);
  if (r.year !== 2020) push(pooled, r.total, r.weight);
}
eq('every diary carries a positive weight', badWeight, 0);
eq('every diary day is 1 to 7', badDay, 0);
eq('no diary reports more than 1440 travel minutes', badTotal, 0);
eq('22 calendar years present', byYear.size, 22);

const mean = (a) => a.wx / a.w;
const p0 = (a) => a.wz / a.w;
const cond = (a) => a.wxt / a.wt;

near('pooled mean matches findings.json', mean(pooled), F.variance.grandMeanMin, 5e-3);
near('pooled sd matches findings.json', Math.sqrt(pooled.wxx / pooled.w - mean(pooled) ** 2), F.variance.sdMin, 5e-3);

let yearsChecked = 0;
for (const s of F.series) {
  const a = byYear.get(s.year);
  near(`${s.year} mean`, mean(a), s.meanMin, 5e-3);
  near(`${s.year} share with no travel`, p0(a), s.shareZero, 5e-6);
  near(`${s.year} share over two hours`, a.wOver / a.w, s.shareOver120, 5e-6);
  eq(`${s.year} unweighted n`, a.n, s.n);
  yearsChecked++;
}
eq('21 standard-weight years re-derived', yearsChecked, 21);
ok('2020 is excluded from the standard-weight series', !F.series.some((s) => s.year === 2020));

// the pandemic pair, which uses the other weight and must not be pooled
near('2020 mean under the pandemic weight', mean(byYear.get(2020)), F.pandemic.y2020.meanMin, 5e-3);
near('2020 share with no travel', p0(byYear.get(2020)), F.pandemic.y2020.shareZero, 5e-6);

// the conditional mean, and the identity the whole argument rests on
for (const y of [2003, 2019, 2024]) {
  const a = byYear.get(y);
  near(`${y}: mean equals (1 - p0) x conditional mean`, (1 - p0(a)) * cond(a), mean(a), 1e-9);
}

// ---------------------------------------------------------------------------
console.log("3. the page's own aggregation code, lifted and run");

const scriptSrc = /<script>([\s\S]*?)<\/script>\s*<\/body>/.exec(html)[1];
const startAt = scriptSrc.indexOf('// ---- row accessors');
const endAt = scriptSrc.indexOf('// ---- boot');
ok('the page ships the aggregation block this check needs', startAt > 0 && endAt > startAt);
const lifted = scriptSrc.slice(startAt, endAt);

// YEAR0 is declared once at the top of the page's IIFE, above the lifted block,
// so it is read out of the page's own source rather than assumed here.
const YEAR0_PAGE = Number(/var YEAR0 = (\d+);/.exec(scriptSrc)[1]);
eq('the page bases its year field on 2003', YEAR0_PAGE, 2003);

const ctx = { ROWS: new Uint8Array(bin.buffer, bin.byteOffset, bin.length), N: NROWS, YEAR0: YEAR0_PAGE, out: null };
ctx.WVBUF = new DataView(bin.buffer, bin.byteOffset, bin.length);
vm.createContext(ctx);
vm.runInContext(
  lifted +
  '\nWV = WVBUF;\n' +
  'var A = aggregate(STANDARD);\n' +
  'var byY = {};\n' +
  'for (var y = 2003; y <= 2024; y++) { (function(yy){ byY[yy] = aggregate(function(i){ return rYear(i) === yy; }); })(y); }\n' +
  'var young19 = aggregate(function(i){ return rYear(i) === 2019 && ageGroup(i) === 0; });\n' +
  'out = { pooledMean: A.mean, pooledP0: A.p0, pooledCond: A.cond, over120: A.over120, n: A.n,\n' +
  '        y2003: byY[2003].mean, y2019: byY[2019].mean, y2024: byY[2024].mean, y2020: byY[2020].mean,\n' +
  '        p2003: byY[2003].p0, p2019: byY[2019].p0, p2024: byY[2024].p0,\n' +
  '        c2003: byY[2003].cond, c2019: byY[2019].cond,\n' +
  '        young19Mean: young19.mean, young19N: young19.n, histSum: Array.prototype.reduce.call(A.hist, function(a,b){return a+b;}, 0) };',
  ctx, { timeout: 120000 }
);
const P = ctx.out;

near("page code: pooled mean equals this file's", P.pooledMean, mean(pooled), 1e-9);
near('page code: pooled share with no travel', P.pooledP0, p0(pooled), 1e-12);
near('page code: pooled conditional mean', P.pooledCond, cond(pooled), 1e-9);
eq('page code: same unweighted count', P.n, pooled.n);
near('page code: 2003 mean', P.y2003, mean(byYear.get(2003)), 1e-9);
near('page code: 2019 mean', P.y2019, mean(byYear.get(2019)), 1e-9);
near('page code: 2024 mean', P.y2024, mean(byYear.get(2024)), 1e-9);
near('page code: 2020 mean', P.y2020, mean(byYear.get(2020)), 1e-9);
near('page code: histogram sums to the total weight', P.histSum, pooled.w, pooled.w * 1e-12);
ok('page code: the 15-24 slice in 2019 is non-empty', P.young19N > 500, `n=${P.young19N}`);

// The page prints the decomposition lever from its own aggregates. Check the
// arithmetic it will do, against the offline decomposition.
const dec = S.decomposition['2003to2019'].crude;
const dP = -(P.p2019 - P.p2003) * ((P.c2003 + P.c2019) / 2);
const dMu = (1 - (P.p2003 + P.p2019) / 2) * (P.c2019 - P.c2003);
near('decomposition: the going-out term', dP, dec.fromGoingOutLessOftenMin, 5e-3);
near('decomposition: the shorter-days term', dMu, dec.fromShorterDaysMin, 5e-3);
near('decomposition: the two terms sum to the whole change', dP + dMu, P.y2019 - P.y2003, 1e-9);
ok('decomposition: the offline residual is zero to machine precision',
  Math.abs(dec.residualMin) < 1e-12, `residual ${dec.residualMin}`);
ok('decomposition: most of the fall is fewer outings, not shorter days',
  dec.shareFromGoingOutLessOften > 0.6 && dec.shareFromGoingOutLessOften < 0.8,
  `share ${dec.shareFromGoingOutLessOften}`);

// ---------------------------------------------------------------------------
console.log('4. errors, standardisation, and the claims that depend on them');

eq('160 replicate weights', E.method.replicates, 160);
near('the Fay multiplier is 4/160', E.method.multiplier, 4 / 160, 1e-15);
eq('the replicate join covered every record', E.method.recordsJoined, 252808);
for (const r of E.meanTravelMinutes) {
  near(`replicate series ${r.year} matches the diaries`, r.value, mean(byYear.get(r.year)), 5e-3);
  ok(`replicate se ${r.year} is positive and sane`, r.se > 0 && r.se < 5, `se=${r.se}`);
}
const T = E.trends;
ok('the 2003-2019 decline is many standard errors from zero', T.meanThrough2019.z < -4, `z=${T.meanThrough2019.z}`);
ok('the rise in days with no travel is larger still', T.shareZeroThrough2019.z > 10, `z=${T.shareZeroThrough2019.z}`);
ok('the travelling day shortened too, but detectably less',
  T.meanAmongTravellersThrough2019.z < 0 && Math.abs(T.meanAmongTravellersThrough2019.z) < Math.abs(T.meanThrough2019.z),
  `z=${T.meanAmongTravellersThrough2019.z} vs ${T.meanThrough2019.z}`);
ok('the page does not claim the travelling day was flat', !/flat among (those|travellers)/i.test(flat));

eq('standardisation uses 28 cells', S.method.cells, 28);
eq('standardised to 2003', S.method.referenceYear, 2003);
const st = S.trends;
ok('the decline survives standardisation', st.standardisedThrough2019.slopePerYear < 0);
ok('composition explains less than half of it',
  Math.abs(st.standardisedThrough2019.slopePerYear) > 0.5 * Math.abs(st.crudeThrough2019.slopePerYear),
  `${st.standardisedThrough2019.slopePerYear} vs ${st.crudeThrough2019.slopePerYear}`);
near('year explains under one per cent of the variance', S.explained.year.share, 0.00412, 1e-4);
ok('demographics explain little more', S.explained.yearAgeSexEmployment.share < 0.05,
  `${S.explained.yearAgeSexEmployment.share}`);

// the group claims the page makes in prose
const ageRow = (g) => S.byAge.rows.find((r) => r.group === g);
const sexRow = (g) => S.bySex.rows.find((r) => r.group === g);
const young = ageRow('15-24');
ok('the 15-24 band lost the most before the pandemic',
  S.byAge.rows.every((r) => r.group === '15-24' || (r.mean2003 - r.mean2019) < (young.mean2003 - young.mean2019)),
  `15-24 lost ${(young.mean2003 - young.mean2019).toFixed(1)} min`);
ok('the 15-24 share with no travel nearly doubled by 2019',
  young.shareZero2019 / young.shareZero2003 > 1.6, `${young.shareZero2003} to ${young.shareZero2019}`);
const men = sexRow('men'), women = sexRow('women');
ok('men and women converged: the gap shrank', Math.abs(men.mean2019 - women.mean2019) < Math.abs(men.mean2003 - women.mean2003),
  `${(men.mean2003 - women.mean2003).toFixed(1)} to ${(men.mean2019 - women.mean2019).toFixed(1)}`);
ok('and it converged because men fell, not because women rose', men.mean2019 < men.mean2003 && women.mean2019 <= women.mean2003,
  `men ${men.mean2003}->${men.mean2019}, women ${women.mean2003}->${women.mean2019}`);

// the purpose claims
const pm03 = F.series.find((s) => s.year === 2003).purposeMeanMin;
const pm19 = F.series.find((s) => s.year === 2019).purposeMeanMin;
const losses = Object.keys(pm03).map((k) => ({ k, d: pm19[k] - pm03[k] })).sort((a, b) => a.d - b.d);
eq('the largest single loss is travel to help nonhousehold members', losses[0].k, '1804');
eq('the second is travel for socialising and leisure', losses[1].k, '1812');
ok('travel to work fell far less than either', Math.abs(pm19['1805'] - pm03['1805']) < Math.abs(losses[1].d),
  `work ${(pm19['1805'] - pm03['1805']).toFixed(2)}`);
ok('shopping travel did not fall', pm19['1807'] >= pm03['1807'] - 0.05,
  `consumer purchases ${(pm19['1807'] - pm03['1807']).toFixed(2)}`);
const totalD = Object.keys(pm03).reduce((a, k) => a + (pm19[k] - pm03[k]), 0);
ok('those two purposes are most of the whole decline',
  (losses[0].d + losses[1].d) / totalD > 0.6, `${((losses[0].d + losses[1].d) / totalD * 100).toFixed(0)}%`);
near('the purpose totals reconcile with the yearly means', totalD,
  F.series.find((s) => s.year === 2019).meanMin - F.series.find((s) => s.year === 2003).meanMin, 0.02);

// ---------------------------------------------------------------------------
console.log('5. England, re-parsed from the committed spreadsheet');

// an independent zip + ODS reader, so a bug in nts.mjs cannot hide here
const zlib = await import('node:zlib');
const ods = fs.readFileSync(path.join(DATA, 'nts0101.ods'));
let off = 0, content = null;
while (off + 30 <= ods.length && ods.readUInt32LE(off) === 0x04034b50) {
  const method = ods.readUInt16LE(off + 8), cs = ods.readUInt32LE(off + 18);
  const nl = ods.readUInt16LE(off + 26), el = ods.readUInt16LE(off + 28);
  const nm = ods.slice(off + 30, off + 30 + nl).toString('latin1');
  const st = off + 30 + nl + el;
  if (nm === 'content.xml') content = (method === 0 ? ods.slice(st, st + cs) : zlib.inflateRawSync(ods.slice(st, st + cs))).toString('utf8');
  off = st + cs;
}
ok('content.xml recovered from the .ods', !!content && content.length > 50000, `${content ? content.length : 0} bytes`);

const tbl = /<table:table [^>]*table:name="NTS0101"[^>]*>([\s\S]*?)<\/table:table>/.exec(content)[1];
// ODS collapses runs of identical cells into one element with a repeat count, so a
// parser that ignores it silently shifts every column after the first empty run.
const rowsX = [...tbl.matchAll(/<table:table-row(?: [^>]*)?>([\s\S]*?)<\/table:table-row>/g)].map((m) => {
  const cells = [];
  for (const c of m[1].matchAll(/<table:table-cell([^>]*)(?:\/>|>([\s\S]*?)<\/table:table-cell>)/g)) {
    const num = /office:value="([^"]*)"/.exec(c[1])?.[1];
    const txt = (c[2] ?? '').replace(/<[^>]+>/g, '').trim();
    const v = num !== undefined ? +num : (txt || null);
    const rep = Math.min(Number(/table:number-columns-repeated="(\d+)"/.exec(c[1])?.[1] ?? 1), 200);
    for (let k = 0; k < rep; k++) cells.push(v);
  }
  return cells;
});
const hIdx = rowsX.findIndex((r) => r.some((c) => typeof c === 'string' && /Time taken per person per year/.test(c)));
const hdr = rowsX[hIdx];
const cH = hdr.findIndex((c) => typeof c === 'string' && /Time taken per person per year/.test(c));
const cM = hdr.findIndex((c) => typeof c === 'string' && /^Distance travelled per person per year/.test(c));
const ukSeries = [];
for (let i = hIdx + 1; i < rowsX.length; i++) {
  const r = rowsX[i];
  // single years are stored as numbers, two-year survey labels as strings
  if (r[0] == null) continue;
  const m = /^(\d{4})(?:\s*(?:to|-|\/)\s*(\d{4}))?/.exec(String(r[0]).trim());
  if (!m || typeof r[cH] !== 'number' || typeof r[cM] !== 'number') continue;
  ukSeries.push({ year: +m[1], endYear: m[2] ? +m[2] : +m[1], hours: r[cH], miles: r[cM] });
}
eq('published rows parsed', ukSeries.length, NT.source.surveyYears);
ok('every footnoted row survived the parse', ukSeries.length >= 35, `${ukSeries.length} rows`);

// The table stacks overlapping rolling averages on single years, so a mean over all
// rows counts the late 1990s several times. Rebuild the same greedy non-overlapping
// cover the analysis uses, independently, and check it lands in the same place.
const cover = [];
let lastEnd = -Infinity;
for (const s of ukSeries) { if (s.year > lastEnd) { cover.push(s); lastEnd = s.endYear; } }
eq('non-overlapping cover size', cover.length, NT.summary.nonOverlappingRows);
const ukMin = cover.map((s) => s.hours * 60 / 365);
const ukMean = ukMin.reduce((a, b) => a + b, 0) / ukMin.length;
near('English mean minutes per day', ukMean, NT.summary.meanMinutesPerDay, 5e-3);
near('English mean hours per day', ukMean / 60, NT.summary.meanHoursPerDay, 5e-4);
ok('and it lands within a minute of an hour', Math.abs(ukMean - 60) < 1.5, `${ukMean.toFixed(2)} min`);
const allMean = ukSeries.reduce((a, s) => a + s.hours * 60 / 365, 0) / ukSeries.length;
near('the all-rows mean is reported beside it', allMean, NT.summary.allRowsMeanMinutesPerDay, 5e-3);
ok('the two differ, which is why both are printed', Math.abs(allMean - ukMean) > 0.1);

const win = ukSeries.filter((s) => s.year >= 2002 && s.year <= 2019 && s.endYear === s.year);
eq('the clean window is single years only', win.length, NT.cleanWindow.n);
const olsFit = (xs, ys) => {
  const n = xs.length, mx = xs.reduce((a, b) => a + b, 0) / n, my = ys.reduce((a, b) => a + b, 0) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx) ** 2; }
  const slope = sxy / sxx, b0 = my - slope * mx;
  let ssr = 0; for (let i = 0; i < n; i++) ssr += (ys[i] - (b0 + slope * xs[i])) ** 2;
  const se = Math.sqrt((ssr / (n - 2)) / sxx);
  return { slope, se, t: slope / se, n };
};
const ukFit = olsFit(win.map((s) => s.year), win.map((s) => s.hours * 60 / 365));
near('English clean-window slope', ukFit.slope, NT.cleanWindow.trendMinutesPerDayPerYear.slope, 5e-4);
near('English clean-window standard error', ukFit.se, NT.cleanWindow.trendMinutesPerDayPerYear.se, 5e-4);
ok('the English decline is significant and negative', ukFit.t < -3, `t=${ukFit.t.toFixed(2)}`);
ok('the American and English declines have the same sign',
  Math.sign(T.meanThrough2019.slopePerYear) === Math.sign(ukFit.slope));

const a72 = ukSeries[0], b19 = ukSeries.find((s) => s.year === 2019);
const dLogD = Math.log(b19.miles / a72.miles);
const dLogV = Math.log((b19.miles / b19.hours) / (a72.miles / a72.hours));
const dLogT = Math.log(b19.hours / a72.hours);
near('distance growth splits into speed and time with no remainder', dLogD - dLogV - dLogT, 0, 1e-12);
near('the speed share', dLogV / dLogD, NT.speedNotTime.shareOfDistanceGrowthFromSpeed, 5e-4);
ok('most of the extra distance came from speed, not from the day', dLogV / dLogD > 0.8, `${(dLogV / dLogD * 100).toFixed(1)}%`);
eq('four series breaks are carried onto the record', NT.notes.length >= 4, true);
ok('the England/Great Britain break is named', NT.notes.some((n) => /Great Britain/.test(n) && /England/.test(n)));
ok('the 1995 weighting uplift is named', NT.notes.some((n) => /1995/.test(n) && /uplift/i.test(n)));

// ---------------------------------------------------------------------------
console.log('6. Europe, re-read from the API dump');

const raw = JSON.parse(fs.readFileSync(path.join(DATA, 'hetus_tus00age.json'), 'utf8'));
const pick = (sel) => {
  let n = 0;
  for (let i = 0; i < raw.id.length; i++) {
    const k = raw.dimension[raw.id[i]].category.index[sel[raw.id[i]]];
    if (k === undefined) return undefined;
    n = n * raw.size[i] + k;
  }
  return raw.value[n];
};
const toMin = (s) => { const m = typeof s === 'string' && /^(\d+):(\d{2})$/.exec(s.trim()); return m ? +m[1] * 60 + +m[2] : null; };
const geos = Object.keys(raw.dimension.geo.category.index);
eq('22 countries in the dump', geos.length, HE.source.countries);
const v2010 = geos.filter((g) => g !== 'UK').map((g) => toMin(pick({ freq: 'A', unit: 'TIME_SP', sex: 'T', age: 'TOTAL', acl00: 'AC9A', geo: g, time: '2010' }))).filter((x) => x != null);
const m2010 = v2010.reduce((a, b) => a + b, 0) / v2010.length;
eq('17 countries reported travel in the 2010 wave, excluding the UK', v2010.length, HE.spread['2010ExcludingUK'].n);
near('European 2010 mean, excluding the UK', m2010, HE.spread['2010ExcludingUK'].mean, 5e-3);
ok('and it too is near an hour', Math.abs(m2010 - 60) < 20, `${m2010.toFixed(1)} min`);
ok('but it is not the same number everywhere', Math.max(...v2010) / Math.min(...v2010) > 1.4,
  `${Math.min(...v2010)} to ${Math.max(...v2010)} min`);
const ptp = geos.map((g) => pick({ freq: 'A', unit: 'PTP_RT', sex: 'T', age: 'TOTAL', acl00: 'AC9A', geo: g, time: '2010' })).filter((x) => typeof x === 'number');
ok('the zero-travel day is a European fact too', Math.min(...ptp) < 90,
  `participation ${Math.min(...ptp)}% to ${Math.max(...ptp)}%, so ${(100 - Math.max(...ptp)).toFixed(1)}%-${(100 - Math.min(...ptp)).toFixed(1)}% travelled not at all`);
ok('the UK 2000-to-2010 jump is flagged rather than used', /instrument change/i.test(HE.spread.ukJump.note));

// ---------------------------------------------------------------------------
console.log('7. quotations, byte for byte');

ok('the quotations are pinned', QU.quotes.length >= 7, `${QU.quotes.length} spans`);
const norm = (s) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ').trim();
for (const q of QU.quotes) {
  ok(`quote present in data.json: ${q.id}`, PD.quotes.quotes.some((x) => x.id === q.id && x.text === q.text));
  ok(`quote carries its source: ${q.id}`, !!QU.sources[q.source] && /^[0-9a-f]{64}$/.test(QU.sources[q.source].sha256));
}
// The quotations are painted by the page at run time, so the served HTML holds ids,
// not text. Assert the page asks for ids that exist: a typo here would silently drop
// a quotation from a page whose whole argument is built on them.
const askedFor = [...scriptSrc.matchAll(/'(?:q-[a-z]+)':\s*'([A-Za-z0-9-]+)'/g)].map((m) => m[1]);
ok('the page requests at least seven quotations', askedFor.length >= 7, `${askedFor.length} requested`);
const known = new Set([...QU.quotes.map((q) => q.id), ...J('guide.json').quotes.map((q) => q.id)]);
for (const id of askedFor) ok(`the page requests a quotation that exists: ${id}`, known.has(id));

ok('the claim under test is quoted, not paraphrased',
  /tails of the distribution are not spread much around the central value/.test(QU.quotes.find((q) => q.id === 'marchetti-one-hour').text));
ok('the standing verdict of the review literature is quoted',
  /not constant except, perhaps, at the most aggregate level/.test(QU.quotes.find((q) => q.id === 'mokhtarian-verdict').text));

// If the copyrighted PDFs happen to be present, re-check the spans against them.
// They are deliberately not committed, so this is a bonus check, not a gate.
let pdfChecked = 0;
for (const [k, s] of Object.entries(QU.sources)) {
  const p = path.join(DATA, s.pdf);
  if (!fs.existsSync(p)) continue;
  eq(`${s.pdf} is the file that was quoted`, crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex'), s.sha256);
  const txt = path.join(DATA, `${k}.txt`);
  if (!fs.existsSync(txt)) continue;
  const hay = norm(fs.readFileSync(txt, 'utf8'));
  for (const q of QU.quotes.filter((x) => x.source === k)) {
    ok(`re-found in the paper: ${q.id}`, hay.indexOf(norm(q.text)) === q.offset);
    pdfChecked++;
  }
}
console.log(`  (${pdfChecked} spans re-checked against local PDFs; they are not committed, so 0 here is expected in a clean checkout)`);

// ---------------------------------------------------------------------------
console.log('8. what the page ships');

const shipped = fs.readFileSync(path.join(PUB, 'diaries.bin'));
eq('the shipped binary is byte-identical to the research artifact',
  crypto.createHash('sha256').update(shipped).digest('hex'),
  crypto.createHash('sha256').update(bin).digest('hex'));
eq('data.json carries the same record count', PD.atus.source.records, 252808);
eq('data.json carries the same replicate method', PD.atus.errors.method.formula, E.method.formula);
near('data.json carries the same English mean', PD.nts.summary.meanMinutesPerDay, NT.summary.meanMinutesPerDay, 1e-9);
near('data.json carries the same European mean', PD.hetus.spread['2010ExcludingUK'].mean, HE.spread['2010ExcludingUK'].mean, 1e-9);
eq('data.json carries the same decomposition', JSON.stringify(PD.atus.standardised.decomposition), JSON.stringify(S.decomposition));
ok('data.json does not pre-bake the yearly means the browser recomputes',
  !JSON.stringify(PD.atus).includes('"meanMin":77.26'), 'the page derives them from the diaries');

// ---------------------------------------------------------------------------
console.log("9. the page's prose and head");

eq('canonical', /<link rel="canonical" href="([^"]+)"/.exec(html)[1], 'https://artwaste.land/strata/the-hour-nobody-spends/');
ok('the search-facing title asks the question people ask', /<title>[^<]*How Much Time Do People Spend Travelling/.test(html));
ok('the poetic title is the H1', /<h1>The Hour Nobody Spends<\/h1>/.test(flat.replace(/> </g, '><')) || /The Hour Nobody Spends/.test(flat));
ok('the frontmatter dek and the meta description agree on the headline number',
  /70\.3 minutes a day/.test(md) && /252,808/.test(md));
// the static figures in the head, the dek and the opening paragraph are typed, not
// computed, so they are held to the data here (added by the assay line, 2026-10-18,
// after "32 English survey years" and "0.997 hours" survived a passing run).
// the dated Corrected notes quote the old figures on purpose, so they are left out
const uncorrected = (md.replace(/^\*Corrected [^\n]*$/gm, '') + html.replace(/<p class="corrections"[\s\S]*?<\/p>/g, ''));
const yearsTyped = [...uncorrected.matchAll(/(\d+) English survey years/g)].map((m) => Number(m[1]));
ok('every typed English survey-year count equals the parsed table',
  yearsTyped.length >= 4 && yearsTyped.every((v) => v === NT.summary.surveyYears),
  `typed ${JSON.stringify(yearsTyped)}, table ${NT.summary.surveyYears}`);
const hoursTyped = [...md.replace(/^\*Corrected [^\n]*$/gm, '').matchAll(/([\d.]+) hours in England/g)].map((m) => m[1]);
ok('the dek\'s England level equals the computed mean to three places',
  hoursTyped.length >= 1 && hoursTyped.every((v) => v === NT.summary.meanHoursPerDay.toFixed(3)),
  `typed ${JSON.stringify(hoursTyped)}, data ${NT.summary.meanHoursPerDay.toFixed(3)}`);
ok('the page says the level is right before it says anything is wrong',
  flat.indexOf('the level, which is right') < flat.indexOf('The hour moved'));
ok('the page states the two-report provenance problem',
  /DOT-RSPA-DPB/.test(flat) && /neither appears to be on the open web/.test(flat));
ok('the page states that Marchetti collected no data of his own', /collected no data of his own/.test(flat));
ok('the page states the 2020 weighting rule', /suspended from 18 March to 9 May 2020/.test(flat) && /no annual estimate for that year exists/.test(flat));
ok('the page carries the diary-day caveat', /A diary day is not a person/.test(flat));
ok('the page carries the response-rate caveat', /The response rate fell by a quarter/.test(flat));
ok('the page carries the survey-mode objection', /survey artifact before/.test(flat) && /McGuckin/.test(flat));
ok('the page carries the destination-purpose caveat', /A travel purpose is a destination/.test(flat));
ok('the page carries the lexicon break', /moved from 17 to 18 in\s*2005|first digit of the travel codes moved from 17 to 18/.test(flat));
ok('the page prints the number it could not reconcile', /One number we could not reconcile/.test(flat));
ok('the page does not call the finding new without qualification',
  !/we are the first/i.test(flat) && !/never been (shown|measured)/i.test(flat) && !/for the first time/i.test(flat));

// --- the credit obligation, which is the one that would be easiest to fudge -----
console.log('9b. the prior work this page must credit');
const PW = J('prior-work.json');
ok('a prior-work record exists', Array.isArray(PW.works) && PW.works.length >= 8, `${PW.works.length} works`);
const doiRe = /^10\.\d{4,9}\/\S+$/;
for (const w of PW.works) {
  ok(`prior work has a resolvable identifier: ${w.id}`, (w.doi && doiRe.test(w.doi)) || /^https?:\/\//.test(w.url || ''));
  ok(`prior work says what it established: ${w.id}`, typeof w.established === 'string' && w.established.length > 60);
}
const morris = PW.works.find((w) => w.id === 'morris-2023');
ok('the published source of the headline decline is on the record', !!morris && /2003-2019/.test(morris.established));
ok('the page names it before it states the trend',
  flat.indexOf('Morris, Speroni and Taylor') > 0 &&
  flat.indexOf('Morris, Speroni and Taylor') < flat.indexOf('The hour moved'));
ok('the page says the trend is not its own finding',
  /is <strong>not<\/strong> a\s*finding of this page|not a finding of this page/.test(html.replace(/\s+/g, ' ')));
ok('data.json ships the prior work so the page cannot quietly drop it',
  PD.priorWork && PD.priorWork.works.length === PW.works.length);
ok('the page claims about seventy per cent, and the data says between 65 and 75',
  dec.shareFromGoingOutLessOften > 0.65 && dec.shareFromGoingOutLessOften < 0.75,
  `${(dec.shareFromGoingOutLessOften * 100).toFixed(1)}%`);

// --- the survey's own account of its weaknesses --------------------------------
console.log("9c. the survey's own account of itself");
const G = J('guide.json');
ok('response rates parsed from the guide, not transcribed', Object.keys(G.responseRates).length >= 20);
eq('2003 response rate', G.responseRates['2003'], 57.8);
eq('2019 response rate', G.responseRates['2019'], 42.0);
ok('the rate fell over the trend window', G.responseRates['2019'] < G.responseRates['2003'] - 10);
ok('the guide quotes are pinned', G.quotes.length === 5 && /^[0-9a-f]{64}$/.test(G.source.sha256));
ok('the variance formula on the record is the one the errors were computed with',
  G.quotes.some((q) => q.id === 'guide-variance' && q.text.includes('(4/160)')) && E.method.multiplier === 4 / 160);
ok('the guide sentence about unmeasured nonresponse error is carried',
  G.quotes.some((q) => /Nonsampling errors were not measured/.test(q.text)));
ok('data.json ships the guide record', PD.guide && PD.guide.responseRates['2003'] === 57.8);
// the house OG-title convention ("<Title> — Artificial Wasteland") lives in <meta>
// and is not prose; the gate is on what a reader actually reads.
ok('no em dash in the page prose',
  !/—/.test(html.replace(/<script>[\s\S]*?<\/script>/g, '').replace(/<meta[^>]*>/g, '')));
ok('the page names this verifier', /verify-the-hour-nobody-spends\.mjs/.test(flat));
ok('the markdown declares the immersive href', /href: "\/strata\/the-hour-nobody-spends\/"/.test(md));
ok('the markdown declares the ground-truth seam', /seam: "groundtruth"/.test(md));

// ---------------------------------------------------------------------------
console.log(`\n${pass}/${pass + fail} checks pass${fail ? `, ${fail} FAILED` : ''}.`);
process.exit(fail ? 1 : 0);
