#!/usr/bin/env node
// Verifier for /strata/the-thumb-came-off-the-scale/
//
//   node verify-the-thumb-came-off-the-scale.mjs
//
// Four independent things, any one of which can fail the page.
//
//  A. The distilled archive is what it claims to be, and the chain that made it
//     runs: research/ghost-games/{fetch,distil,analyse,build-page-data}.mjs.
//  B. The data bundle the page ships is rebuilt from scratch out of the
//     distilled archive and compared cell by cell. One altered sum fails.
//  C. The page's own arithmetic is LIFTED out of the shipped bytes with
//     node:vm and run against an independent implementation in research/.
//  D. Every number quoted in the prose is extracted from the served bytes by
//     pattern and checked against the freshly computed value.
//
// Nothing here reads research/ghost-games/page-data.json. The bundle under
// test is the one embedded in the HTML.

import { readFileSync, existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import vm from 'node:vm'

import { loadMatches, homePointShare, mean, meanSd, welch, DIV_NAMES } from './research/ghost-games/lib.mjs'
import {
  CROWD_SEASONS, GHOST_SEASON, SPLIT_SEASON, RETURN_SEASON, PRE_CUT, GHOST_CORE,
  FREE_KICK_DIVS, MEASURES, SHARED_GROUND, inSharedWindow, findSuspension,
} from './research/ghost-games/analyse.mjs'
import { buildBundle, FIELDS } from './research/ghost-games/build-page-data.mjs'

const ROOT = path.dirname(fileURLToPath(import.meta.url))
const PAGE = path.join(ROOT, 'public/strata/the-thumb-came-off-the-scale/index.html')

let passed = 0, failed = 0
const ok = (name, cond, extra = '') => {
  if (cond) passed++; else failed++
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`)
}
const section = s => console.log(`\n── ${s} ${'─'.repeat(Math.max(0, 64 - s.length))}`)

const html = readFileSync(PAGE, 'utf8')
const text = html.replace(/<[^>]+>/g, ' ').replace(/&minus;/g, '−').replace(/&ndash;/g, '–')
  .replace(/&middot;/g, '·').replace(/&amp;/g, '&').replace(/&nbsp;/g, ' ')
  .replace(/&times;/g, '×')
  .replace(/\s+/g, ' ')

// A prose check: the exact rendered string must appear in the page text.
const says = (label, s) => ok(label, text.includes(s), `"${s}"` + (text.includes(s) ? '' : '  NOT FOUND'))

const vals = (rows, f) => rows.map(f).filter(x => x !== null && x !== undefined && Number.isFinite(x))
const pctS = (x, d = 2) => (x * 100).toFixed(d) + '%'

// ────────────────────────────────────────────────────────────────────────────
section('A. the distilled archive and the chain that built it')

for (const f of ['fetch.mjs', 'distil.mjs', 'lib.mjs', 'analyse.mjs', 'build-page-data.mjs',
  'data/matches-min.tsv.gz']) {
  ok(`research/ghost-games/${f} exists`, existsSync(path.join(ROOT, 'research/ghost-games', f)))
}

const M = loadMatches()
ok('the archive loads', M.length > 200000, `${M.length} matches`)
const divs = [...new Set(M.map(m => m.div))]
const seasons = [...new Set(M.map(m => m.season))].sort((a, b) => a - b)
ok('22 divisions', divs.length === 22, String(divs.length))
ok('33 seasons, 1993 to 2025', seasons.length === 33 && seasons[0] === 1993 &&
  seasons[seasons.length - 1] === 2025, `${seasons[0]}..${seasons[seasons.length - 1]}`)
ok('every division has a name', divs.every(d => DIV_NAMES[d]))
ok('every match has a parsable ISO date', M.every(m => /^\d{4}-\d{2}-\d{2}$/.test(m.date)))
ok('every match has both scores', M.every(m => Number.isFinite(m.fthg) && Number.isFinite(m.ftag)))
ok('no match is a team against itself', M.every(m => m.home !== m.away))
ok('dates lie inside their season', M.every(m => {
  const y = +m.date.slice(0, 4)
  return y === m.season || y === m.season + 1
}))

// ────────────────────────────────────────────────────────────────────────────
section('B. the bundle in the page, rebuilt from the archive')

const m = /<script id="ghost-data" type="application\/json">([\s\S]*?)<\/script>/.exec(html)
ok('the page carries a ghost-data block', !!m)
const shipped = JSON.parse(m[1])
const fresh = buildBundle(M)

ok('the field list matches', JSON.stringify(shipped.fields) === JSON.stringify(FIELDS))
ok('the match count matches', shipped.meta.matches === M.length, String(shipped.meta.matches))
ok('the same number of cells', shipped.cells.length === fresh.cells.length,
  `${shipped.cells.length} vs ${fresh.cells.length}`)

let cellMismatch = null
for (let i = 0; i < fresh.cells.length; i++) {
  const a = shipped.cells[i], b = fresh.cells[i]
  if (!a || a.length !== b.length) { cellMismatch = `row ${i} shape`; break }
  for (let j = 0; j < b.length; j++) {
    const eq = typeof b[j] === 'number' ? Math.abs(a[j] - b[j]) < 1e-9 : a[j] === b[j]
    if (!eq) { cellMismatch = `row ${i} (${b[0]} ${b[1]}) field ${j}: ${a[j]} vs ${b[j]}`; break }
  }
  if (cellMismatch) break
}
ok('all 694 division-season cells agree, sum for sum', cellMismatch === null, cellMismatch || '')

for (const key of ['suspension', 'split', 'placebo', 'referees', 'shared', 'sharedAll', 'ghostCoreCell']) {
  ok(`the ${key} block agrees`, JSON.stringify(shipped[key]) === JSON.stringify(fresh[key]))
}

// The cells are the archive: check a few against a direct recount, so the
// bundle is not merely self-consistent.
{
  const probe = ['E0:2020', 'I1:2019', 'D1:1993', 'SP1:2025', 'B1:2013']
  let bad = 0
  for (const key of probe) {
    const [d, s] = key.split(':')
    const rows = M.filter(x => x.div === d && x.season === +s)
    const cell = shipped.cells.find(c => c[0] === d && c[1] === +s)
    if (!cell) { bad++; continue }
    if (cell[2] !== rows.length) bad++
    const gi = 1 + 2 * FIELDS.indexOf('homeGoals')
    if (Math.abs(cell[2 + gi + 1] - rows.reduce((a, r) => a + r.fthg, 0)) > 1e-9) bad++
  }
  ok('five sampled cells recount correctly against the raw rows', bad === 0, `${bad} mismatches`)
}

// ────────────────────────────────────────────────────────────────────────────
section('C. the page\'s own arithmetic, lifted out of the shipped bytes')

const modelStart = html.indexOf('<script id="ghost-model">')
ok('the page carries a ghost-model block', modelStart >= 0)
const modelSrc = html.slice(html.indexOf('>', modelStart) + 1, html.indexOf('</script>', modelStart))
ok('the model block is DOM-free', !/\bdocument\b|\bwindow\.addEventListener\b/.test(modelSrc))

const sandbox = { window: {}, console }
vm.createContext(sandbox)
vm.runInContext(modelSrc, sandbox, { filename: 'ghost-model' })
const P = sandbox.window.GHOST
ok('the lifted model exposes its functions', P && typeof P.avg === 'function' &&
  typeof P.fitLine === 'function' && typeof P.signTest === 'function')

const F = shipped.fields
const cellsBy = new Map(shipped.cells.map(c => [c[0] + ':' + c[1], c.slice(2)]))
const pool = (ds, ss) => P.add(ds.flatMap(d => ss.map(s => cellsBy.get(d + ':' + s)).filter(Boolean)))

// The page derives its own card panel; rebuild the same rule here.
const CARD_DIVS = divs.filter(d => {
  const c = pool([d], CROWD_SEASONS), g = pool([d], [GHOST_SEASON])
  if (!c || !g) return false
  return P.count(F, c, 'homeYellows') / c[0] > 0.95 && P.count(F, g, 'homeYellows') / g[0] > 0.95
})
ok('the card panel is all 22 divisions', CARD_DIVS.length === 22, String(CARD_DIVS.length))

// Now: the page's measures, computed by the LIFTED code from the SHIPPED
// bundle, against the same measures computed row by row from the archive.
{
  const windows = {
    crowd: { rows: M.filter(x => CARD_DIVS.includes(x.div) && CROWD_SEASONS.includes(x.season)),
      cell: pool(CARD_DIVS, CROWD_SEASONS) },
    ghost: { rows: M.filter(x => CARD_DIVS.includes(x.div) && x.season === GHOST_SEASON),
      cell: pool(CARD_DIVS, [GHOST_SEASON]) },
    ret: { rows: M.filter(x => CARD_DIVS.includes(x.div) && x.season === RETURN_SEASON),
      cell: pool(CARD_DIVS, [RETURN_SEASON]) },
  }
  let worst = 0, where = ''
  for (const [wk, w] of Object.entries(windows)) {
    for (const key of Object.keys(MEASURES)) {
      const lab = P.MEASURES[key]
      if (!lab) { worst = Infinity; where = 'missing measure ' + key; continue }
      const fromPage = lab.of(F, w.cell)
      const fromRows = mean(vals(w.rows, MEASURES[key].get))
      const d = Math.abs(fromPage - fromRows)
      if (d > worst) { worst = d; where = `${wk}.${key}: page ${fromPage} vs rows ${fromRows}` }
    }
  }
  ok('all 8 measures x 3 windows agree between the lifted page code and a row-by-row recount',
    worst < 1e-9, where)
}

// The trend fit, and the placebo, both through the lifted code.
{
  const pts = seasons.map(s => [s, mean(vals(M.filter(x => x.season === s), homePointShare))])
  const fitLab = P.fitLine(pts.filter(p => p[0] <= 2018))
  // independent least squares here in the verifier
  const pre = pts.filter(p => p[0] <= 2018)
  const mx = mean(pre.map(p => p[0])), my = mean(pre.map(p => p[1]))
  const b = pre.reduce((a, p) => a + (p[0] - mx) * (p[1] - my), 0) /
    pre.reduce((a, p) => a + (p[0] - mx) ** 2, 0)
  const a0 = my - b * mx
  ok('the lifted trend fit matches an independent least squares',
    Math.abs(fitLab.b - b) < 1e-12 && Math.abs(fitLab.a - a0) < 1e-9,
    `slope ${fitLab.b.toExponential(6)}`)
  const rmse = Math.sqrt(pre.reduce((acc, p) => acc + (p[1] - (a0 + b * p[0])) ** 2, 0) / (pre.length - 2))
  ok('so does its residual rmse', Math.abs(fitLab.rmse - rmse) < 1e-12)
}
{
  // Two-sided sign test against a fair coin, in EXACT INTEGER ARITHMETIC.
  //
  // 2026-08-16. What stood here was a line-for-line copy of the page's own
  // `signTest` — same forward binomial recurrence, same accumulation order, same
  // `Math.max(k, n-k)` tail, same closing `2 * s * Math.pow(0.5, n)` — with only
  // the declaration order changed. Held against the function it copied, the
  // difference is exactly 0 by construction, so the assertion `|P.signTest(21,22)
  // - exact(21,22)| < 1e-15` COULD NOT FAIL FOR ANY INPUT. It was a tautology
  // wearing the words "an exact binomial computed here".
  //
  // The shared algorithm does have a failure mode, and both copies carried it:
  // `c` accumulates C(n,i) in linear doubles and overflows to Infinity around
  // n = 1029, so the result becomes 1 and then NaN. The page's own inputs are
  // n = 22 and n = 84 — nowhere near it — so nothing published was ever wrong.
  // What was wrong was that nothing could have told us.
  //
  // BigInt shares no failure mode with a float recurrence: no overflow, no
  // underflow, no rounding. Verified against the copied version at the page's
  // inputs, where they agree to 3.3e-16.
  const exact = (k, n) => {
    const kk = BigInt(Math.max(k, n - k)), N = BigInt(n)
    let c = 1n, s = 0n
    for (let i = 0n; i <= N; i++) { if (i >= kk) s += c; c = c * (N - i) / (i + 1n) }
    const num = 2n * s, den = 1n << N
    if (num >= den) return 1
    const SCALE = 10n ** 25n
    return Number(num * SCALE / den) / 1e25
  }
  ok('the lifted sign test matches exact integer arithmetic', Math.abs(P.signTest(21, 22) - exact(21, 22)) < 1e-15 &&
    Math.abs(P.signTest(65, 84) - exact(65, 84)) < 1e-15)
  // A named regression test for the copy that used to be here: the reference must
  // survive where the page's float recurrence does not, or it is not a reference.
  ok('the reference still returns a probability where the float recurrence overflows',
    exact(700, 1100) > 0 && exact(700, 1100) < 1 && Number.isNaN(P.signTest(700, 1100)),
    `exact ${exact(700, 1100).toExponential(3)}, lifted float ${P.signTest(700, 1100)}`)
  ok('the lifted normal cdf is close to the true one',
    Math.abs(P.normalCdf(0) - 0.5) < 1e-9 && Math.abs(P.normalCdf(1.959964) - 0.975) < 2e-6)
  const d = P.disciplineShare(0.1692, 0.2524, 0.0117, 0.05, 0.9)
  ok('the lifted arithmetic bound is the stated ratio',
    Math.abs(d.bought - (0.2524 * 0.05 + 0.0117 * 0.9)) < 1e-12 &&
    Math.abs(d.share - d.bought / 0.1692) < 1e-12)
}

// ────────────────────────────────────────────────────────────────────────────
section('D. every number in the prose, recomputed')

const CARD = CARD_DIVS
const panel = M.filter(x => CARD.includes(x.div))
const crowdRows = panel.filter(x => CROWD_SEASONS.includes(x.season))
const ghostRows = panel.filter(x => x.season === GHOST_SEASON)
const retRows = panel.filter(x => x.season === RETURN_SEASON)
const coreRows = ghostRows.filter(x => x.date >= GHOST_CORE[0] && x.date <= GHOST_CORE[1])

says('the match count', M.length.toLocaleString('en-GB'))
says('the division count', '22 divisions')
says('the season count', '33 seasons')

// § 1 the long slide
{
  const share = s => mean(vals(M.filter(x => x.season === s), homePointShare))
  const pre = seasons.filter(s => s <= 2018).map(s => [s, share(s)])
  const mx = mean(pre.map(p => p[0])), my = mean(pre.map(p => p[1]))
  const b = pre.reduce((a, p) => a + (p[0] - mx) * (p[1] - my), 0) /
    pre.reduce((a, p) => a + (p[0] - mx) ** 2, 0)
  const a0 = my - b * mx
  const rmse = Math.sqrt(pre.reduce((acc, p) => acc + (p[1] - (a0 + b * p[0])) ** 2, 0) / (pre.length - 2))
  const actual = share(GHOST_SEASON), pred = a0 + b * GHOST_SEASON
  says('the ghost season point share', pctS(actual))
  says('the trend prediction for it', pctS(pred))
  says('the gap in percentage points', ((actual - pred) * -100).toFixed(2))
  says('that gap in units of rmse', Math.abs((actual - pred) / rmse).toFixed(1))
  const others = seasons.filter(s => s !== GHOST_SEASON)
    .map(s => Math.abs((share(s) - (a0 + b * s)) / rmse))
  says('the largest residual of any other season', Math.max(...others).toFixed(1))
  says('the first season point share', pctS(share(1993)))
  says('the last pre-pandemic point share', pctS(share(2018)))
}

// § 2 the hole
{
  const susp = divs.map(d => findSuspension(M, d)).filter(Boolean)
  const restarted = susp.filter(s => s.restarted)
  ok('eleven divisions restarted', restarted.length === 11, String(restarted.length))
  ok('eleven did not', susp.length - restarted.length === 11)
  const gaps = restarted.map(s => s.gapDays)
  says('the shortest suspension', String(Math.min(...gaps)))
  says('the longest suspension', String(Math.max(...gaps)))
  const before = [], after = []
  for (const s of restarted) {
    for (const x of M.filter(y => y.div === s.div && y.season === SPLIT_SEASON)) {
      if (x.date < PRE_CUT) before.push(x); else if (x.date >= s.restart) after.push(x)
    }
  }
  says('matches with a crowd in the split season', before.length.toLocaleString('en-GB'))
  says('matches without one', after.length.toLocaleString('en-GB'))
  const w = k => welch(vals(before, MEASURES[k].get), vals(after, MEASURES[k].get))
  const wy = w('yellowDiff')
  says('the split-season card gap with a crowd', '+' + wy.a.mean.toFixed(3))
  says('and without', '−' + Math.abs(wy.b.mean).toFixed(3))
  says('its t statistic', '−' + Math.abs(wy.t).toFixed(1))
  says('the foul flip t', '−' + Math.abs(w('foulDiff').t).toFixed(1))
  const wp = w('pointShare')
  says('split-season point share with a crowd', pctS(wp.a.mean, 1))
  says('and without', pctS(wp.b.mean, 1))
  says('its p value', wp.p.toFixed(2))
  const wg = w('goalDiff')
  says('split-season goal difference with a crowd', wg.a.mean.toFixed(3))
  says('and without', wg.b.mean.toFixed(3))
  says('its p value', wg.p.toFixed(2))
  // the restart dates the fixture list hands back
  const byDiv = Object.fromEntries(restarted.map(s => [s.div, s.restart]))
  ok('the Bundesliga restart is read off the fixture list as 16 May 2020',
    byDiv.D1 === '2020-05-16', byDiv.D1)
  ok('and the Premier League as 17 June 2020', byDiv.E0 === '2020-06-17', byDiv.E0)
  ok('and Serie A as 20 June 2020', byDiv.I1 === '2020-06-20', byDiv.I1)
  ok('and Portugal as 3 June 2020', byDiv.P1 === '2020-06-03', byDiv.P1)
  ok('and Greece as 6 June 2020', byDiv.G1 === '2020-06-06', byDiv.G1)
  ok('and Turkey as 12 June 2020', byDiv.T1 === '2020-06-12', byDiv.T1)
  ok('and Spain as 10 and 11 June 2020',
    byDiv.SP2 === '2020-06-10' && byDiv.SP1 === '2020-06-11', byDiv.SP1 + '/' + byDiv.SP2)
}

// § 3 which side moved
{
  says('crowd-season matches', crowdRows.length.toLocaleString('en-GB'))
  says('ghost-season matches', ghostRows.length.toLocaleString('en-GB'))
  // welch(a, b) reports diff = a - b, so the change from crowd to empty is -diff.
  const side = f => {
    const w = welch(vals(crowdRows, f), vals(ghostRows, f))
    return { change: -w.diff, t: -w.t, p: w.p }
  }
  const s = {
    homeShots: side(x => x.hs), awayShots: side(x => x.as),
    homeGoals: side(x => x.fthg), awayGoals: side(x => x.ftag),
    homeYellows: side(x => x.hy), awayYellows: side(x => x.ay),
    homeFouls: side(x => x.hf), awayFouls: side(x => x.af),
  }
  says('home shots fell by', Math.abs(s.homeShots.change).toFixed(2))
  says('at t', '−' + Math.abs(s.homeShots.t).toFixed(1))
  says('away shots moved by', Math.abs(s.awayShots.change).toFixed(2))
  says('home goals fell by', Math.abs(s.homeGoals.change).toFixed(2))
  says('away goals rose by', s.awayGoals.change.toFixed(3))
  says('home yellows moved by', '−' + Math.abs(s.homeYellows.change).toFixed(2))
  says('its p value', s.homeYellows.p.toFixed(2))
  says('away yellows fell by', Math.abs(s.awayYellows.change).toFixed(2))
  says('at away-yellow t', '−' + Math.abs(s.awayYellows.t).toFixed(2))
  says('home fouls rose by', s.homeFouls.change.toFixed(2))
  says('away fouls rose by', s.awayFouls.change.toFixed(2))
}

// § 4 cards per foul
{
  const paired = x => x.hf !== null && x.af !== null && x.hy !== null && x.ay !== null &&
    !FREE_KICK_DIVS.includes(x.div)
  const rate = rows => {
    const r = rows.filter(paired)
    const h = r.reduce((a, x) => a + x.hy, 0) / r.reduce((a, x) => a + x.hf, 0)
    const aw = r.reduce((a, x) => a + x.ay, 0) / r.reduce((a, x) => a + x.af, 0)
    return { n: r.length, ratio: aw / h }
  }
  const c = rate(crowdRows), g = rate(ghostRows)
  says('the crowd-season conversion premium', ((c.ratio - 1) * 100).toFixed(1) + '%')
  says('the ghost-season conversion premium', ((g.ratio - 1) * 100).toFixed(1) + '%')
  says('the number of paired matches behind it', (c.n + g.n).toLocaleString('en-GB'))
  ok('three divisions are excluded for recording free kicks, not fouls',
    FREE_KICK_DIVS.length === 3 && CARD.filter(d => !FREE_KICK_DIVS.includes(d)).length === 19)
  says('the count of divisions used', 'other 19')
}

// § 5 referees
{
  const named = M.filter(x => x.referee && x.hy !== null)
  const rows = []
  for (const r of [...new Set(named.map(x => x.referee))]) {
    const c = named.filter(x => x.referee === r && CROWD_SEASONS.includes(x.season))
    const g = named.filter(x => x.referee === r && x.season === GHOST_SEASON)
    if (c.length >= 20 && g.length >= 20) {
      rows.push({ c: mean(vals(c, MEASURES.yellowDiff.get)), g: mean(vals(g, MEASURES.yellowDiff.get)) })
    }
  }
  says('the number of referees', String(rows.length))
  const refDivs = [...new Set(named.map(x => x.div))]
  says('the number of divisions naming their referees', String(refDivs.length) + ' divisions')
  says('their mean gap with a crowd', '+' + mean(rows.map(r => r.c)).toFixed(3))
  says('and without', '−' + Math.abs(mean(rows.map(r => r.g))).toFixed(3))
  says('how many fell', String(rows.filter(r => r.g < r.c).length))
  const d = rows.map(r => r.g - r.c)
  const ds = meanSd(d)
  says('the paired t', '−' + Math.abs(ds.mean / ds.se).toFixed(2))
}

// § 6 placebo
{
  const susp = divs.map(d => findSuspension(M, d)).filter(Boolean).filter(s => s.restarted)
  const K = Object.fromEntries(susp.map(s => [s.div, s.nAfter]))
  const swings = []
  for (const s of seasons) {
    const early = [], late = []
    for (const d of Object.keys(K)) {
      const g = M.filter(x => x.div === d && x.season === s && x.hy !== null)
        .sort((a, b) => (a.date < b.date ? -1 : 1))
      if (g.length < K[d] + 50) continue
      if (s === SPLIT_SEASON) {
        const r = susp.find(x => x.div === d).restart
        early.push(...g.filter(x => x.date < PRE_CUT))
        late.push(...g.filter(x => x.date >= r))
      } else {
        early.push(...g.slice(0, g.length - K[d]))
        late.push(...g.slice(g.length - K[d]))
      }
    }
    if (early.length && late.length) {
      swings.push({ season: s,
        swing: mean(vals(late, MEASURES.yellowDiff.get)) - mean(vals(early, MEASURES.yellowDiff.get)) })
    }
  }
  const ghost = swings.find(s => s.season === SPLIT_SEASON).swing
  const others = swings.filter(s => s.season !== SPLIT_SEASON).map(s => s.swing)
  const os = meanSd(others)
  says('the placebo mean', '−' + Math.abs(os.mean).toFixed(3))
  says('the placebo sd', os.sd.toFixed(3))
  says('the worst placebo season', '−' + Math.abs(Math.min(...others)).toFixed(3))
  says('the ghost swing', '−' + Math.abs(ghost).toFixed(3))
  says('its z', Math.abs((ghost - os.mean) / os.sd).toFixed(1))
  says('the number of placebo seasons', String(others.length) + ' other seasons')
  ok('the ghost restart is the extreme of all 26', others.every(x => x > ghost))
}

// § 7 unanimity
{
  const per = key => CARD.map(d => ({
    d,
    c: mean(vals(M.filter(x => x.div === d && CROWD_SEASONS.includes(x.season)), MEASURES[key].get)),
    g: mean(vals(M.filter(x => x.div === d && x.season === GHOST_SEASON), MEASURES[key].get)),
  }))
  const y = per('yellowDiff'), p = per('pointShare'), r = per('redDiff')
  const fell = a => a.filter(x => x.g < x.c).length
  says('yellow gap unanimity', `${fell(y)} of ${y.length}`)
  says('point share unanimity', `${fell(p)} of ${p.length}`)
  says('red card unanimity', `${fell(r)} of ${r.length}`)
  const ex = y.filter(x => x.g >= x.c)
  ok('exactly one division is the exception', ex.length === 1, ex.map(x => x.d).join())
  ok('and it is Scottish League One', ex[0].d === 'SC2', ex[0].d)
  says('its crowd gap', ex[0].c.toFixed(3))
  says('its ghost gap', ex[0].g.toFixed(3))
  says('its ghost sample', String(M.filter(x => x.div === 'SC2' && x.season === GHOST_SEASON).length))
  // the page prints this as "1.1 × 10−5"
  says('the sign-test p for the card gap',
    P.signTest(fell(y), y.length).toExponential(1).replace(/e-(\d+)$/, ' × 10 −$1'))
  says('the sign-test p for point share', P.signTest(fell(p), p.length).toFixed(3))
}

// § 8 the arithmetic
{
  const hp = x => (x.fthg > x.ftag ? 3 : x.fthg === x.ftag ? 1 : 0)
  const ap = x => (x.ftag > x.fthg ? 3 : x.fthg === x.ftag ? 1 : 0)
  const adv = rows => mean(vals(rows, hp)) - mean(vals(rows, ap))
  const c = adv(crowdRows), g = adv(ghostRows)
  says('the points advantage with a crowd', c.toFixed(4))
  says('and without', g.toFixed(4))
  says('the points lost', (c - g).toFixed(4))
  const dY = mean(vals(crowdRows, MEASURES.yellowDiff.get)) - mean(vals(ghostRows, MEASURES.yellowDiff.get))
  const dR = mean(vals(crowdRows, MEASURES.redDiff.get)) - mean(vals(ghostRows, MEASURES.redDiff.get))
  says('the net yellow advantage lost', dY.toFixed(4))
  says('the net red advantage lost', dR.toFixed(4))
  says('the share bought at 0.05 and 0.9', Math.round((dY * 0.05 + dR * 0.9) / (c - g) * 100) + '%')
  says('the share bought with a worthless yellow', Math.round(dR * 0.9 / (c - g) * 100) + '%')
  says('the price a yellow would need', ((c - g) / dY).toFixed(2))
  says('the price a red would need', ((c - g) / dR).toFixed(1))
}

// § 9 shared ground
{
  const derbies = SHARED_GROUND.flatMap(p => M.filter(x => inSharedWindow(p, x)))
  const keys = new Set(derbies.map(x => x.div + ':' + x.season))
  const base = M.filter(x => keys.has(x.div + ':' + x.season))
  says('the number of shared-ground matches', String(derbies.length))
  says('their home point share', pctS(mean(vals(derbies, homePointShare)), 1))
  says('the baseline point share', pctS(mean(vals(base, homePointShare)), 1))
  says('the standard error on it', (meanSd(vals(derbies, homePointShare)).se * 100).toFixed(1))
  ok('every pair is balanced leg for leg', SHARED_GROUND.every(p => {
    const g = M.filter(x => inSharedWindow(p, x))
    return Math.abs(g.filter(x => x.home === p.clubs[0]).length -
      g.filter(x => x.home === p.clubs[1]).length) <= 1
  }))
  ok('the ghost season is excluded from this arm', derbies.every(x => x.season !== GHOST_SEASON))
  ok('the Munich pair starts at 1995-96', M.filter(x => inSharedWindow(SHARED_GROUND
    .find(p => p.ground === 'Olympiastadion'), x)).every(x => x.season >= 1995))
  ok('the Selhurst Park pair ends at 2002-03', M.filter(x => inSharedWindow(SHARED_GROUND
    .find(p => p.ground === 'Selhurst Park'), x)).every(x => x.season <= 2002))
  says('the number of shared grounds', 'seven shared grounds')
  // Ponzo and Scoppa's published Serie A figures, reproduced on this archive
  const hp = x => (x.fthg > x.ftag ? 3 : x.fthg === x.ftag ? 1 : 0)
  const ap = x => (x.ftag > x.fthg ? 3 : x.fthg === x.ftag ? 1 : 0)
  const sa = M.filter(x => x.div === 'I1' && x.season <= 2012)
  says('Serie A home points to 2012-13', mean(vals(sa, hp)).toFixed(3))
  says('and away points', mean(vals(sa, ap)).toFixed(3))
}

// § 10 the return, the substitution test, Germany
{
  const yd = rows => mean(vals(rows, MEASURES.yellowDiff.get))
  says('the crowd-season card gap', yd(crowdRows).toFixed(3))
  says('the ghost-season card gap', yd(ghostRows).toFixed(3))
  says('the return-season card gap', yd(retRows).toFixed(3))
  const e0c = M.filter(x => x.div === 'E0' && CROWD_SEASONS.includes(x.season))
  const e0g = M.filter(x => x.div === 'E0' && x.season === GHOST_SEASON)
  const w = welch(vals(e0c, MEASURES.yellowDiff.get), vals(e0g, MEASURES.yellowDiff.get))
  says('the Premier League crowd gap', w.a.mean.toFixed(3))
  says('its ghost gap', w.b.mean.toFixed(3))
  says('its t', '−' + Math.abs(w.t).toFixed(2))
  says('its ghost sample', String(e0g.length) + ' empty matches')
  // Germany
  const d1 = M.filter(x => x.div === 'D1')
  const pre = d1.filter(x => x.season === SPLIT_SEASON && x.date < PRE_CUT)
  const post = d1.filter(x => x.season === SPLIT_SEASON && x.date >= '2020-05-16')
  const next = d1.filter(x => x.season === GHOST_SEASON)
  says('Bundesliga before the suspension', pctS(mean(vals(pre, homePointShare)), 1))
  says('after the restart', pctS(mean(vals(post, homePointShare)), 1))
  says('and the season after', pctS(mean(vals(next, homePointShare)), 1))
  // the eleven that restarted, pooled
  const susp = divs.map(d => findSuspension(M, d)).filter(Boolean).filter(s => s.restarted)
  const rd = susp.map(s => s.div)
  const pooledCrowd = M.filter(x => rd.includes(x.div) && CROWD_SEASONS.includes(x.season))
  const pooledFirst = susp.flatMap(s => M.filter(x => x.div === s.div && x.season === SPLIT_SEASON &&
    x.date >= s.restart))
  const pooledGhost = M.filter(x => rd.includes(x.div) && x.season === GHOST_SEASON)
  says('the eleven with crowds', pctS(mean(vals(pooledCrowd, homePointShare)), 1))
  says('in the first empty weeks', pctS(mean(vals(pooledFirst, homePointShare)), 1))
  says('across the empty season', pctS(mean(vals(pooledGhost, homePointShare)), 1))
}

// the sensitivity quoted in the check section
{
  says('the core-window card gap', mean(vals(coreRows, MEASURES.yellowDiff.get)).toFixed(3))
  says('the core-window point share', pctS(mean(vals(coreRows, homePointShare))))
  says('against the whole ghost season', mean(vals(ghostRows, MEASURES.yellowDiff.get)).toFixed(3))
}

// ────────────────────────────────────────────────────────────────────────────
section('E. the page as a document')

ok('it prints the command that verifies it',
  html.includes('node verify-the-thumb-came-off-the-scale.mjs'))
ok('the way-out footer is present', html.includes('<!--aw-wayout-->'))
ok('the site bar is present', html.includes('/media/home-banner.js'))
ok('it declares its canonical url',
  html.includes('rel="canonical" href="https://artwaste.land/strata/the-thumb-came-off-the-scale/"'))
ok('it names its source', html.includes('football-data.co.uk'))
ok('it carries a "what is not verified" section', html.includes('What is not verified here'))
ok('no em dash in the page prose', !/—/.test(html))
{
  const cited = ['Nevill', 'Garicano', 'Ponzo', 'van de Ven', 'Bryson', 'Endrich', 'Scoppa',
    'Wunderlich', 'Fischer', 'Reade', 'Schank', 'Ridder', 'Badiella', 'Titman',
    'Pettersson-Lidbom', 'Pollard']
  const missing = cited.filter(c => !html.includes(c))
  ok('every author named in the prose is in the reference list', missing.length === 0, missing.join())
}

// ────────────────────────────────────────────────────────────────────────────
console.log(`\n${passed}/${passed + failed} checks passed`)
process.exit(failed === 0 ? 0 : 1)
