#!/usr/bin/env node
// verify-nobody-here-sleeps.mjs — recompute every figure the page prints, from
// the committed sample, and fail if the page and the data disagree.
//
//   node research/moltbook-clock/verify-nobody-here-sleeps.mjs
//
// The page computes its own figures in the browser from an embedded block, so
// this file's job is to prove that block is what posts.jsonl actually says, and
// that the handful of numbers typed into the prose and the dek match it too.
// Written from the raw harvest, not from build-data.mjs's output, so a bug in
// the builder shows up as a disagreement rather than being inherited.

import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert';

const HERE = path.dirname(new URL(import.meta.url).pathname);
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'nobody-here-sleeps', 'index.html');
const MD = path.join(ROOT, 'src', 'content', 'strata', 'nobody-here-sleeps.md');

let checks = 0, failures = 0;
const ok = (cond, label, detail = '') => {
  checks++; if (!cond) failures++;
  console.log(`  ${cond ? 'ok  ' : 'FAIL'} ${label}${detail ? '  ->  ' + detail : ''}`);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── the sample, read fresh ───────────────────────────────────────────────────
const rows = fs.readFileSync(path.join(HERE, 'posts.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
const ms = rows.map((r) => Date.parse(r.t)).filter(Number.isFinite).sort((a, b) => a - b);
const html = fs.readFileSync(PAGE, 'utf8');
const md = fs.readFileSync(MD, 'utf8');
const embedded = JSON.parse(/<script type="application\/json" id="clock-data">([\s\S]*?)<\/script>/.exec(html)[1]);

console.log('\n== the sample ==');
ok(rows.length === 45000, 'the committed sample is 45,000 posts', String(rows.length));
ok(embedded.harvest.posts === rows.length, 'the page embeds that post count', String(embedded.harvest.posts));
ok(embedded.harvest.authors === new Set(rows.map((r) => r.n)).size, 'and that author count', String(embedded.harvest.authors));
ok(!/"content"|"body"|"title"/.test(fs.readFileSync(path.join(HERE, 'posts.jsonl'), 'utf8').slice(0, 4000)),
  'no post text was collected (the sample carries no content field)');

// ── minute of hour ───────────────────────────────────────────────────────────
console.log('\n== minute of hour ==');
const startH = Math.ceil(ms[0] / 36e5) * 36e5, endH = Math.floor(ms[ms.length - 1] / 36e5) * 36e5;
const trimmed = ms.filter((t) => t >= startH && t < endH);
const minute = new Array(60).fill(0);
for (const t of trimmed) minute[new Date(t).getUTCMinutes()]++;
ok(trimmed.length === embedded.minute.n, 'the whole-hour trim matches the page', String(trimmed.length));
ok(minute.every((c, i) => c === embedded.minute.counts[i]), 'every one of the 60 minute bins matches');
const mExp = trimmed.length / 60;
const zeroLift = minute[0] / mExp;
ok(near(zeroLift, 2.64, 0.005), 'minute :00 lift is 2.64x', zeroLift.toFixed(3));
ok(/2\.64/.test(html), 'the page states 2.64x for :00');
ok(/2\.64 times its share/.test(md), 'the dek states it too');
const chi2 = minute.reduce((s, c) => s + (c - mExp) ** 2 / mExp, 0);
ok(near(chi2, 3819.8, 0.5), 'chi-squared is 3819.8 on 59 df', chi2.toFixed(1));
ok(/3819\.8/.test(md), 'the entry states that chi-squared');
const roundSet = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
const roundFrac = roundSet.reduce((s, m) => s + minute[m], 0) / trimmed.length;
ok(near(roundFrac, 0.2439, 0.0002), 'five-minute boundaries hold 24.39%', (100 * roundFrac).toFixed(2) + '%');
ok(/24\.4 per cent/.test(md), 'the dek states 24.4 per cent');

// ── second of minute ─────────────────────────────────────────────────────────
console.log('\n== second of minute ==');
const second = new Array(60).fill(0);
for (const t of ms) second[new Date(t).getUTCSeconds()]++;
const secLift = second[4] / (ms.length / 60);
ok(near(secLift, 3.55, 0.01), 'second :04 lift is 3.55x', secLift.toFixed(3));
ok(second.indexOf(Math.max(...second)) === 4, 'second :04 is the busiest second of all 60');
ok(/four seconds after/.test(md), 'the entry describes the lag as about four seconds');

// ── the gap test, and its chance rate ────────────────────────────────────────
console.log('\n== per-agent gaps ==');
const byAgent = new Map();
for (const r of rows) {
  const t = Date.parse(r.t); if (!Number.isFinite(t)) continue;
  if (!byAgent.has(r.n)) byAgent.set(r.n, []);
  byAgent.get(r.n).push(t);
}
const gaps = [];
for (const [, times] of byAgent) {
  times.sort((a, b) => a - b);
  for (let i = 1; i < times.length; i++) { const s = (times[i] - times[i - 1]) / 1000; if (s > 0 && s <= 6 * 3600) gaps.push(s); }
}
ok(gaps.length === embedded.gaps.n, 'the gap count matches the page', String(gaps.length));
const TOL = 2;
const liftFor = (p) => {
  let hit = 0;
  for (const g of gaps) if (Math.abs(g - Math.round(g / p) * p) <= TOL) hit++;
  return (hit / gaps.length) / ((2 * TOL) / p);
};
// THE load-bearing number on this page. If the chance rate is ever written back
// as (2*TOL+1)/p, this assertion is what goes red.
ok(near((2 * TOL) / 60, 0.06667, 1e-5), 'the chance rate for a +-2 s window on 60 s is 6.667%, not 8.333%');
const l60 = liftFor(60), l3600 = liftFor(3600), l1800 = liftFor(1800);
ok(near(l60, 4.38, 0.01), 'gaps align to the minute at 4.38x', l60.toFixed(3));
ok(near(l1800, 11.95, 0.02), 'to the half hour at 11.95x', l1800.toFixed(3));
ok(near(l3600, 20.89, 0.02), 'to the hour at 20.89x', l3600.toFixed(3));
ok(/20\.9/.test(html) && /20\.9/.test(md), 'page and entry both state 20.9x for the hour');
ok(/4\.4 times more often/.test(md), 'the dek states 4.4x for the minute');
const embLift = Object.fromEntries(embedded.gaps.periods.map((p) => [p.period, p.lift]));
ok(near(embLift[3600], l3600, 1e-9), 'the embedded lift table agrees with a fresh computation');
ok(embedded.gaps.periods.every((p) => near(p.chance, (2 * TOL) / p.period, 1e-12)),
  'every embedded chance rate uses the continuous formula');

// ── the diurnal control ──────────────────────────────────────────────────────
console.log('\n== the diurnal control ==');
const startD = Math.ceil(ms[0] / 864e5) * 864e5, endD = Math.floor(ms[ms.length - 1] / 864e5) * 864e5;
const dayMs = ms.filter((t) => t >= startD && t < endD);
const hour = new Array(24).fill(0);
for (const t of dayMs) hour[new Date(t).getUTCHours()]++;
const ratio = Math.max(...hour) / Math.min(...hour);
ok((endD - startD) / 864e5 === 8, 'the diurnal control covers 8 whole UTC days', String((endD - startD) / 864e5));
ok(near(ratio, 1.30, 0.005), 'peak hour to trough hour is 1.30x', ratio.toFixed(3));
ok(/1\.30/.test(html) && /1\.30 times/.test(md), 'page and entry both state 1.30x');
// The claim the page rests on: the minute effect beats the day effect.
ok(zeroLift > ratio * 2, 'the minute-of-hour effect is more than twice the day-night effect',
  `${zeroLift.toFixed(2)}x vs ${ratio.toFixed(2)}x`);

// ── the metronomes ───────────────────────────────────────────────────────────
console.log('\n== the metronomes ==');
let tight = 0, pool = 0;
const metro = [];
for (const [name, times] of byAgent) {
  if (times.length < 8) continue;
  const g = []; for (let i = 1; i < times.length; i++) g.push((times[i] - times[i - 1]) / 1000);
  const sorted = g.slice().sort((a, b) => a - b);
  const med = sorted[Math.floor(sorted.length / 2)];
  const dev = g.map((x) => Math.abs(x - med)).sort((a, b) => a - b);
  const mad = dev[Math.floor(dev.length / 2)];
  pool++; if (mad <= 2) tight++;
  metro.push({ name, med, mad, posts: times.length });
}
ok(tight === embedded.metronomeCount, 'the count of agents with MAD <= 2 s matches the page', String(tight));
ok(tight === 11, 'and it is 11', String(tight));
ok(/11 agents/.test(md), 'the dek states 11');
ok(pool === embedded.metronomePool, 'the pool it is drawn from matches', String(pool));
const hourly = metro.filter((m) => Math.abs(m.med - 3600) < 5 && m.mad <= 2 && m.posts >= 100);
ok(hourly.length >= 1, 'at least one agent holds a one-hour interval to within 2 s across 100+ posts',
  hourly.map((m) => `${m.name} ${m.med.toFixed(1)}s ±${m.mad.toFixed(1)}s`).join(', '));

// ── the population test, added after @phenology's objection ──────────────────
// The published claim depends on the :00 peak not being an artefact of a few
// high-volume accounts. That is checkable, so check it rather than assert it.
console.log('\n== the population test ==');
const inWin = rows.map((r) => ({ t: Date.parse(r.t), n: r.n })).filter((r) => Number.isFinite(r.t) && r.t >= startH && r.t < endH);
const agentMins = new Map();
for (const r of inWin) {
  if (!agentMins.has(r.n)) agentMins.set(r.n, []);
  agentMins.get(r.n).push(new Date(r.t).getUTCMinutes());
}
const liftAt0 = (mins) => { let z = 0; for (const m of mins) if (m === 0) z++; return z / (mins.length / 60); };
const elig = [...agentMins.values()].filter((m) => m.length >= 20);
const meanLift = elig.reduce((s, m) => s + liftAt0(m), 0) / elig.length;
ok(near(meanLift, 4.429, 0.005), 'weighting every agent equally gives a HIGHER lift, 4.43x', meanLift.toFixed(3));
ok(meanLift > zeroLift, 'per-agent weighting beats the pooled figure, so the loud accounts dilute rather than drive it',
  `${meanLift.toFixed(2)}x vs ${zeroLift.toFixed(2)}x`);
const ranked = [...agentMins.entries()].sort((a, b) => b[1].length - a[1].length);
const dropLift = (k) => {
  const drop = new Set(ranked.slice(0, k).map(([n]) => n));
  const kept = [];
  for (const [n, mins] of agentMins) if (!drop.has(n)) kept.push(...mins);
  return liftAt0(kept);
};
ok(dropLift(2) > dropLift(0) && dropLift(10) > dropLift(2),
  'removing the loudest agents raises the lift monotonically over the first ten',
  `${dropLift(0).toFixed(2)} -> ${dropLift(2).toFixed(2)} -> ${dropLift(10).toFixed(2)}`);
const overN = elig.filter((m) => liftAt0(m) > 1).length;
ok(near(overN / elig.length, 0.351, 0.005), 'but only 35.1% of agents are over-represented at :00', String(overN));
ok(/large minority/.test(html), 'the page states the refinement rather than the simpler claim');
ok(/phenology/.test(html), 'and credits the reader who forced it');
ok(near(embedded.population.meanPerAgentLift, meanLift, 1e-9), 'the embedded population block agrees with a fresh computation');

// ── the page cannot print a figure the data did not produce ──────────────────
console.log('\n== the page is generated, not typed ==');
ok(/id="f-zero"/.test(html) && !/>2\.640×</.test(html), 'the in-prose lifts are filled at runtime, not hardcoded');
ok(/build-data\.mjs/.test(html), 'the page names the generator that fills it');
ok(/check-null\.mjs/.test(html), 'and the file that tests its control');

console.log(`\n${failures ? 'FAIL' : 'PASS'} ${checks - failures}/${checks}\n`);
process.exit(failures ? 1 : 0);
