#!/usr/bin/env node
/**
 * verify-where-the-lateness-goes.mjs
 *
 * Checks /strata/where-the-lateness-goes/ against the committed artifacts of
 * research/where-the-lateness-goes/.
 *
 * IT READS NOTHING A READER CANNOT FETCH, and that is the design, not a limitation.
 *
 * The 50 daily source files are about 26 GB and are not committed; `fetch.mjs --all`
 * re-downloads them in roughly eight minutes. Everything this program reads is served:
 *
 *   /data/timetable-recovery/legs.jsonl     5,824 leg classes, the rows behind every figure
 *   /data/timetable-recovery/sources.json   the licence position, and all 50 days with the
 *                                           sha256 of the bytes as received
 *   /data/timetable-recovery/manifest.json  byte length, row count and digest of each file
 *   /strata/where-the-lateness-goes/        the page, and the payload it ships to browsers
 *
 * So it does not take the summary's word for anything. It RECOMPUTES every aggregate from
 * the published rows and fails if the page, or the payload the page hands your browser,
 * disagrees. Three things have to agree: the recomputation from the rows, the static text
 * a reader with no JavaScript sees, and the payload the page's own script runs on.
 *
 * An earlier draft read the repository's private artifacts instead, and was recorded by
 * `research/source-mirror/` as published-to-read rather than runnable, for the correct
 * reason: a check is a program, and the data it reads is a dataset whatever directory it
 * sits in. The dataset went through `/data/` and its licence question, and the check now
 * reads it from there.
 *
 * ONE CHECK IS DELIBERATELY NOT HERE. That the pre-registration was committed before the
 * analysis existed is a claim about this repository's history, and the repository is
 * private, so it is not a claim a reader can ever check. Keeping it in this file would
 * make the whole program unrunnable outside the workspace in order to assert something
 * the outside cannot see anyway. It lives in
 * `research/where-the-lateness-goes/preregistration-order.mjs`, which is inside-only and
 * says so, and this program stays portable: it needs the four committed artifacts, the
 * built page, and nothing else.
 *
 *   node verify-where-the-lateness-goes.mjs             the checks
 *   node verify-where-the-lateness-goes.mjs --selftest  plant defects, require each to go red
 */

import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const DATA = path.join(ROOT, 'public', 'data', 'timetable-recovery');
const PAGE = path.join(ROOT, 'public', 'strata', 'where-the-lateness-goes', 'index.html');

let pass = 0, fail = 0;
const verbose = process.argv.includes('--verbose');
function check(name, ok, detail) {
  if (ok) { pass++; if (verbose) console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
  return ok;
}

// ---------------------------------------------------------------------------
// the recomputation, exported so the selftest can drive it over mutated copies

const median = (a) => {
  if (!a.length) return null;
  const s = Float64Array.from(a).sort();
  return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const mean = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : null);
function pearson(xs, ys) {
  const nn = xs.length; if (nn < 3) return null;
  const mx = mean(xs), my = mean(ys);
  let sxy = 0, sxx = 0, syy = 0;
  for (let i = 0; i < nn; i++) { const a = xs[i] - mx, b = ys[i] - my; sxy += a * b; sxx += a * a; syy += b * b; }
  return sxx && syy ? sxy / Math.sqrt(sxx * syy) : null;
}
function spearman(xs, ys) {
  const rank = (v) => {
    const idx = v.map((x, i) => [x, i]).sort((a, b) => a[0] - b[0]);
    const r = new Array(v.length);
    let i = 0;
    while (i < idx.length) {
      let j = i; while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++;
      const avg = (i + j) / 2 + 1;
      for (let k = i; k <= j; k++) r[idx[k][1]] = avg;
      i = j + 1;
    }
    return r;
  };
  return pearson(rank(xs), rank(ys));
}

// Re-derive, from the per-class rows alone, everything the summary and the predictions say.
export function recompute(classes, hubIds, MIN_N_BIN = 10) {
  const Ks = classes.filter((c) => c.K !== null).map((c) => c.K);
  const Fs = classes.filter((c) => c.F !== null).map((c) => c.F);
  const Kpos = Ks.map((k) => Math.max(0, k)).sort((a, b) => b - a);
  const total = Kpos.reduce((x, y) => x + y, 0);
  const topDecile = Kpos.slice(0, Math.ceil(Kpos.length / 10)).reduce((x, y) => x + y, 0);
  const both = classes.filter((c) => c.F !== null && c.K !== null);
  const hubK = classes.filter((c) => c.K !== null && hubIds.has(c.to)).map((c) => c.K);
  const restK = classes.filter((c) => c.K !== null && !hubIds.has(c.to)).map((c) => c.K);
  const wb = classes.filter((c) => c.K !== null && c.onTimeRate !== null);
  // and the per-class invariants: K is the max over eligible bins, F is sched minus floor
  let badK = 0, badF = 0;
  for (const c of classes) {
    if (c.F !== null && c.schedMedian !== null && c.realQ01 !== null &&
        Math.abs(c.F - (c.schedMedian - c.realQ01)) > 1e-9) badF++;
    let k = null;
    for (const b of c.curve || []) {
      if (b.d < 0 || b.n < MIN_N_BIN) continue;
      const a = -b.medianDelta;
      if (k === null || a > k) k = a;
    }
    if (c.curve && ((k === null) !== (c.K === null) || (k !== null && Math.abs(k - c.K) > 1e-9))) badK++;
  }
  return {
    reportableClasses: classes.length,
    medianF: median(Fs), meanF: mean(Fs), medianK: median(Ks), meanK: mean(Ks),
    classesAbsorbingAtLeast60s: Ks.filter((k) => k >= 60).length,
    classesAbsorbingNothing: Ks.filter((k) => k <= 0).length,
    P1: { medianK: median(Ks), n: Ks.length },
    P2: { share: total ? topDecile / total : null, negatives: Ks.filter((k) => k < 0).length },
    P5: { share: both.length ? both.filter((c) => c.F > c.K).length / both.length : null, n: both.length },
    P6: { hubMeanK: mean(hubK), restMeanK: mean(restK), nHub: hubK.length, nRest: restK.length },
    P7: { pearson: pearson(wb.map((c) => c.K), wb.map((c) => c.onTimeRate)), spearman: spearman(wb.map((c) => c.K), wb.map((c) => c.onTimeRate)), n: wb.length },
    badK, badF,
  };
}

const near = (a, b, eps = 1e-9) => a !== null && b !== null && Math.abs(a - b) <= eps;

// ---------------------------------------------------------------------------

function run({ results, classes, imp, sources, manifest, html }) {
  pass = 0; fail = 0;

  // 1 · provenance, read from the published dataset rather than from our side of the wall
  const days = (sources.days || []).slice().sort((a, b) => a.date.localeCompare(b.date, 'en'));
  check('the dataset names as many days as the window claims', days.length === results.window.days,
    `${days.length} days published, the window says ${results.window.days}`);
  check('its first and last day are the window',
    days.length > 1 && days[0].date === results.window.from && days.at(-1).date === results.window.to,
    days.length ? `${days[0].date} .. ${days.at(-1).date}` : 'none');
  check('every day carries a 64-hex sha256 of the bytes as received',
    days.length > 0 && days.every((d) => /^[0-9a-f]{64}$/.test(d.source_sha256 || '')));
  check('every day carries a positive byte length and its source URL',
    days.length > 0 && days.every((d) => d.source_bytes > 0 && /^https:\/\//.test(d.url || '')));
  check('the days are consecutive calendar dates with no gap', (() => {
    for (let i = 1; i < days.length; i++) {
      const a = Date.parse(days[i - 1].date + 'T00:00:00Z'), b = Date.parse(days[i].date + 'T00:00:00Z');
      if (b - a !== 86400000) return false;
    }
    return days.length > 1;
  })());
  check('the rail rows kept per day sum to the rows the census read',
    days.reduce((x, d) => x + d.rail_rows, 0) === results.census.rowsRead,
    `${days.reduce((x, d) => x + d.rail_rows, 0)} vs ${results.census.rowsRead}`);
  check('each source carries a licence position rather than an assumption', (() => {
    const ss = sources.sources || [];
    return ss.length >= 2 && ss.every((x) => x.licence_id && x.licence && x.licence_basis && x.licence_note)
      && ss.some((x) => x.licence_id === 'ODMCH-TERMS' && /opentransportdata/.test(x.url || ''));
  })());
  check('the dataset says out loud that it is a dated analysis and not a feed',
    typeof sources.this_is_a_dated_analysis_not_a_feed === 'string'
    && sources.this_is_a_dated_analysis_not_a_feed.includes(results.window.from));

  // 2 · fixity of the published bytes, which is a promise a reader can also check
  check('the manifest\'s row count for the rows file is the number of rows',
    (manifest.files.find((f) => f.name === 'legs.jsonl') || {}).rows === classes.length,
    `${(manifest.files.find((f) => f.name === 'legs.jsonl') || {}).rows} vs ${classes.length}`);
  // Reads every file the manifest names, including the three this program has no other
  // use for, and lets a missing one THROW rather than returning false. Twice tonight the
  // polite failure was the bug: research/source-mirror/ learns a bundle's dependencies from
  // the ENOENT a crash prints, so a check that shrugs at a missing file is recorded as
  // unrunnable for a stranger. If you are holding a partial download, the stack trace names
  // the file you are missing, which is what you wanted to know.
  check('every file the manifest names matches its recorded sha256 and byte length', (() => {
    for (const f of manifest.files) {
      const b = readFileSync(path.join(DATA, f.name));
      if (b.length !== f.bytes) return false;
      if (createHash('sha256').update(b).digest('hex') !== f.sha256) return false;
    }
    return manifest.files.length >= 5;
  })());

  // 3 · recompute every aggregate from the per-class rows
  const hubIds = new Set(['8503000', '8507000', '8500010', '8500218', '8505000', '8501120', '8501008']);
  const R = recompute(classes, hubIds, results.thresholds.MIN_N_BIN);
  check('every class F equals its median scheduled run time minus its realised floor', R.badF === 0, `${R.badF} bad`);
  check('every class K equals the largest absorption over its eligible bins', R.badK === 0, `${R.badK} bad`);
  check('reportable class count agrees', R.reportableClasses === results.summary.reportableClasses,
    `${R.reportableClasses} vs ${results.summary.reportableClasses}`);
  for (const k of ['medianF', 'meanF', 'medianK', 'meanK', 'classesAbsorbingAtLeast60s', 'classesAbsorbingNothing']) {
    check(`summary.${k} recomputes from the published rows`, near(R[k], results.summary[k], 1e-9),
      `${R[k]} vs ${results.summary[k]}`);
  }
  check('P1 recomputes', near(R.P1.medianK, results.predictions.P1.medianK) && R.P1.n === results.predictions.P1.n);
  check('P2 recomputes', near(R.P2.share, results.predictions.P2.share, 1e-12) && R.P2.negatives === results.predictions.P2.negatives);
  check('P5 recomputes', near(R.P5.share, results.predictions.P5.share, 1e-12) && R.P5.n === results.predictions.P5.n);
  check('P6 recomputes', near(R.P6.hubMeanK, results.predictions.P6.hubMeanK, 1e-9) && near(R.P6.restMeanK, results.predictions.P6.restMeanK, 1e-9));
  check('P7 recomputes', near(R.P7.spearman, results.predictions.P7.spearman, 1e-9) && near(R.P7.pearson, results.predictions.P7.pearson, 1e-9));
  check('each prediction verdict follows from its own numbers', (() => {
    const P = results.predictions;
    return P.P1.holds === (P.P1.medianK < 60)
      && P.P2.holds === (P.P2.share > 0.5)
      && P.P4.holds === (P.P4.dwellSlackPerSecond > P.P4.runSlackPerSecond)
      && P.P5.holds === (P.P5.share > 0.5)
      && P.P6.holds === (P.P6.hubMeanK > P.P6.restMeanK)
      && P.P7.holds === (P.P7.spearman <= 0);
  })());
  check('three of the seven predictions broke, and the page is allowed to say so',
    Object.values(results.predictions).filter((p) => !p.holds).length === 3);

  // 4 · internal consistency of the census and the curves
  const c = results.census;
  check('kept train-days plus the discards equal the train-days seen',
    c.tripDaysKept + c.tripDaysDiscardedOrder + c.tripDaysDiscardedNoTime === c.tripDays);
  check('every order discard is a scheduled-minute tie, not a decreasing sequence',
    c.tripDaysDiscardedOrder === c.tripDaysDiscardedTie);
  check('punctuality equals on-time over arrivals',
    near(results.punctuality.rate, results.punctuality.onTime / results.punctuality.arrivals, 1e-12));
  check('counting cancellations as late lowers the rate, and by the stated denominator',
    near(results.punctuality.rateCountingCancellationsAsLate,
      results.punctuality.onTime / (results.punctuality.arrivals + results.punctuality.cancelledRowsWithScheduledArrival), 1e-12));
  check('the pooled segment curve covers bins -1 through 15 exactly once',
    results.pooledCurve.length === 17 && results.pooledCurve.every((b, i) => b.d === i - 1));
  check('the end-to-end curve covers the same bins',
    results.endToEndPooled.length === 17 && results.endToEndPooled.every((b, i) => b.d === i - 1));
  const peak = results.pooledCurve.filter((b) => b.d >= 0).reduce((a, b) => (a.absorb >= b.absorb ? a : b));
  check('the leg-absorption ceiling is a real peak inside the measured range',
    peak.d > 0 && peak.d < 15 && peak.absorb > results.pooledCurve.find((b) => b.d === 0).absorb);
  check('the end-to-end kept fraction is monotone over the well-populated bins', (() => {
    const rows = results.endToEndPooled.filter((b) => b.d >= 1 && b.d <= 9 && b.n >= 400);
    for (let i = 1; i < rows.length; i++) if (rows[i].keptFraction < rows[i - 1].keptFraction) return false;
    return rows.length >= 6;
  })());
  check('the defect diagnosis agrees with the census it came from',
    imp.classesExamined <= results.impossibleOrder.classes &&
    results.impossibleOrder.traversals === results.census.traversalsNegativeRun &&
    imp.classesWithIdenticalDepartureMajority <= imp.classesExamined);
  check('the impossible traversals in the census are the ones the rows carry',
    classes.reduce((x, c) => x + (c.nNegativeRun || 0), 0) <= results.census.traversalsNegativeRun);
  check('the study declares the decisions it took after the pre-registration',
    Array.isArray(results.unregisteredDecisions) && results.unregisteredDecisions.length >= 4);

  // 5 · the built page says what the artifacts say
  const at = (d) => results.endToEndPooled.find((b) => b.d === d);
  const nn = (x) => Number(x).toLocaleString('en-US');
  const mustContain = [
    ['window', `${results.window.from}`], ['window end', `${results.window.to}`],
    ['measured legs', nn(results.census.segmentsBothReal)],
    ['rail rows', nn(results.census.rowsRead)],
    ['train-days', nn(results.census.tripDaysKept)],
    ['one minute late', `${at(1).medianArrivalDelay} seconds late`],
    ['reportable classes', nn(results.summary.classesReportable ?? results.census.classesReportable)],
    ['the leg ceiling', `${peak.absorb} seconds`],
    ['median leg absorption', `${results.summary.medianK} seconds`],
    ['classes absorbing nothing', nn(results.summary.classesAbsorbingNothing)],
    ['punctuality', `${(100 * results.punctuality.rate).toFixed(2)}%`],
    ['punctuality with cancellations', `${(100 * results.punctuality.rateCountingCancellationsAsLate).toFixed(2)}%`],
    ['impossible traversals', nn(results.impossibleOrder.traversals)],
    ['discarded train-days', nn(results.census.tripDaysDiscardedOrder)],
  ];
  for (const [what, s] of mustContain) check(`the page states the ${what}`, html.includes(s), JSON.stringify(s));

  check('the page head points at its own slug', (() => {
    const want = 'https://artwaste.land/strata/where-the-lateness-goes/';
    return (html.match(new RegExp(want.replace(/\//g, '\\/'), 'g')) || []).length >= 3;
  })());
  check('the page declares an og image for this slug', html.includes('/og/where-the-lateness-goes.png'));
  check('the page carries the shared home banner', html.includes('/media/home-banner.js'));
  check('the page closes its script, body and html', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html.trim() + '\n'));

  // 6 · the payload the browser runs on. `results` above IS that payload, so the checks
  // that matter here are the ones that tie it to something else: the rows it claims to
  // summarise, and the internal consistency a retyping would not survive.
  check('the page embeds a payload and it parses', !!results && !!results.census);
  check('the payload\'s reportable-class count is the number of rows published',
    results.summary.reportableClasses === classes.length,
    `${results.summary.reportableClasses} vs ${classes.length}`);
  check('every route offered to the reader carries its own end-to-end curve over all 17 bins',
    results.journeysLongDistance.every((j) => j.endToEnd && Array.isArray(j.endToEnd.curve) && j.endToEnd.curve.length === 17));
  check('every route\'s covered legs are no more than its legs',
    results.journeys.concat(results.journeysLongDistance).every((j) => j.legsCovered <= j.legs));
  check('the payload names the same source the dataset does',
    results.source && results.source.url && sources.sources.some((x) => x.url === results.source.url));
  check('the payload carries the layer\'s own account of what it decided after the pre-registration',
    Array.isArray(results.unregisteredDecisions) && results.unregisteredDecisions.length >= 4);

  return { pass, fail };
}

// ---------------------------------------------------------------------------

// The published row shape, mapped to the names the recomputation uses. The dataset's
// column names are for a stranger reading a schema; these are for the arithmetic.
const asClass = (r) => ({
  from: r.from_bpuic, to: r.to_bpuic, cat: r.category,
  n: r.traversals_measured, nNegativeRun: r.traversals_impossible,
  schedMedian: r.scheduled_run_median_s, realMedian: r.realised_run_median_s,
  realQ01: r.realised_run_p01_s,
  F: r.slack_present_s, K: r.absorption_best_s, Kd: r.absorption_best_at_min, Kn: r.absorption_best_n,
  onTimeRate: r.on_time_rate,
  curve: (r.absorption_curve || []).map((b) => ({ d: b.entered_late_min, n: b.n, medianDelta: b.median_delay_change_s })),
});

const load = () => {
  const html = readFileSync(PAGE, 'utf8');
  const m = /<script id="payload" type="application\/json">([\s\S]*?)<\/script>/.exec(html);
  if (!m) throw new Error('the page carries no payload');
  const results = JSON.parse(m[1].replace(/\\u003c/g, '<'));
  const classes = readFileSync(path.join(DATA, 'legs.jsonl'), 'utf8')
    .split('\n').filter(Boolean).map((l) => asClass(JSON.parse(l)));
  return {
    results, classes,
    imp: results.impossibleDiagnosis,
    sources: JSON.parse(readFileSync(path.join(DATA, 'sources.json'), 'utf8')),
    manifest: JSON.parse(readFileSync(path.join(DATA, 'manifest.json'), 'utf8')),
    html,
  };
};

// A MISSING ARTIFACT MUST STILL THROW, and the reason is not stylistic.
//
// This used to exit(1) with a tidy sentence naming the file, which reads better to a
// person and is invisible to a machine. research/source-mirror/lib.mjs proves a check
// runnable for a stranger by rebuilding its bundle in an empty directory, running it, and
// learning each hidden dependency from the ENOENT the crash prints; a check that fails
// politely teaches it nothing, and is recorded as unprovable for a reason that is really
// its own good manners. Measured on this file on 2026-09-13: verdict `read-only`,
// `discoveredByRunning: []`. So: say the sentence, then let the error out.
for (const p of [path.join(DATA, 'legs.jsonl'), path.join(DATA, 'sources.json'),
                 path.join(DATA, 'manifest.json'), PAGE]) {
  if (!existsSync(p)) {
    console.log(`FAIL missing artifact: ${path.relative(ROOT, p)}`);
    readFileSync(p);            // deliberate: the ENOENT is the machine-readable half
  }
}

if (process.argv.includes('--selftest')) {
  // Plant a defect, require the suite to go red, restore. A check that cannot fail is not
  // a check, and the only way to know is to break the thing it watches.
  const base = load();
  const quiet = (o) => { const log = console.log; console.log = () => {}; const r = run(o); console.log = log; return r; };
  const clean = quiet(base);
  const cases = [];
  cases.push(['baseline is green', clean.fail === 0]);

  let o = structuredClone(base);
  o.html = o.html.replace(`${base.results.summary.medianK} seconds`, `${base.results.summary.medianK + 1} seconds`);
  cases.push(['a changed number in the page text goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  const i = o.classes.findIndex((c) => c.K !== null);
  o.classes[i].K = o.classes[i].K + 30;
  cases.push(['a changed absorption in a published row goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.classes[i].F = o.classes[i].F + 5;
  cases.push(['a slack figure that no longer equals sched minus floor goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.classes.pop();
  cases.push(['a row missing from the published file goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.manifest.files.find((f) => f.name === 'legs.jsonl').sha256 = '0'.repeat(64);
  cases.push(['a published file whose bytes do not match its recorded digest goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.sources.days[0].source_sha256 = '';
  cases.push(['a day with no recorded digest goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.sources.days.splice(3, 1);
  cases.push(['a gap in the published days goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.sources.sources = o.sources.sources.map((x) => ({ ...x, licence_note: undefined }));
  cases.push(['a source with no reasoned licence position goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.results.punctuality.rate = 0.99;
  cases.push(['a punctuality rate that is not on-time over arrivals goes red', quiet(o).fail > 0]);

  o = structuredClone(base);
  o.results.predictions.P7.holds = true;
  cases.push(['a verdict that does not follow from its own number goes red', quiet(o).fail > 0]);

  let bad = 0;
  for (const [name, ok] of cases) { console.log(`  ${ok ? 'ok  ' : 'FAIL'} ${name}`); if (!ok) bad++; }
  console.log(`\nselftest: ${cases.length - bad}/${cases.length} cases behave`);
  process.exit(bad ? 1 : 0);
}

console.log('verify-where-the-lateness-goes');
const r = run(load());
console.log(`\n${r.pass} passed, ${r.fail} failed`);
console.log('(the pre-registration ordering is a fact about a private repository and is checked');
console.log(' separately by research/where-the-lateness-goes/preregistration-order.mjs)');
process.exit(r.fail ? 1 : 0);
