// research/five-hundred-nights/verify.mjs
//
// The offline honesty gate for the 500th stratum, "Five Hundred Nights".
//
// This does NOT trust data.json. It re-reads the RAW repository from scratch
// (the same primary files analyze.mjs reads, derived the same way) and asserts
// that every figure it computes equals the figure shipped in
// public/strata/five-hundred-nights/data.json, the file the page fetches and
// displays.
//
// PINNED TO THE SNAPSHOT COMMIT. The page is a portrait of the corpus at its
// five hundredth night, and the corpus kept growing the same night it landed
// (504 by the time the ink dried; the page owns this). So the derivation reads
// the repository AT THE COMMIT THAT WROTE data.json (materialized in a temp
// git worktree), not the moving tip. That makes every shipped figure
// reproducible forever, however far past 500 the makers run.
//
//   node research/five-hundred-nights/verify.mjs
//
// Sources re-read here:
//   src/content/strata/*.md .............. n, span, cadence, seams, edges, hubs, drift
//   coordination/moves.tsv ............... makers, moves, kinds
//   research/lineage-self-corrections/events.json ... selfCorrections (a CITED count)
//   git log (best-effort) ................ msgInstances (falls back to 0, as analyze does)
//
// Exit 0 iff ALL checks PASS; non-zero otherwise. One line per check.

import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');

// ── materialize the snapshot commit (the commit that wrote data.json) ──
const DATA_REL = 'public/strata/five-hundred-nights/data.json';
const PIN = execSync(`git log -1 --format=%H -- ${DATA_REL}`, { cwd: ROOT }).toString().trim();
if (!PIN) { console.error('FATAL: cannot resolve the snapshot commit for ' + DATA_REL); process.exit(2); }
const SNAP = fs.mkdtempSync(path.join(os.tmpdir(), 'fhn-snapshot-'));
execSync(`git worktree add --detach "${SNAP}" ${PIN}`, { cwd: ROOT, stdio: 'ignore' });
process.on('exit', () => {
  try { execSync(`git worktree remove --force "${SNAP}"`, { cwd: ROOT, stdio: 'ignore' }); } catch { }
});

const STR = path.join(SNAP, 'src/content/strata');
const R = p => fs.readFileSync(path.join(SNAP, p), 'utf8');
const fm = (t, k) => { const m = t.match(new RegExp('^' + k + ':\\s*"?([^"\\n]+)"?', 'm')); return m ? m[1].trim() : null; };

// ── independently re-derive the picture from the raw repository ──
// (logic mirrors research/five-hundred-nights/analyze.mjs so it re-derives the SAME way)

// strata
const files = fs.readdirSync(STR).filter(f => f.endsWith('.md'));
const strata = [];
for (const f of files) {
  const t = fs.readFileSync(path.join(STR, f), 'utf8');
  if (/^draft:\s*true/m.test(t)) continue;
  const relates = (t.match(/^\s*-\s*to:\s*\S+/gm) || []).length;
  const relTargets = (t.match(/^\s*-\s*to:\s*(\S+)/gm) || []).map(x => x.replace(/^\s*-\s*to:\s*/, '').trim());
  strata.push({
    slug: f.replace(/\.md$/, ''),
    title: fm(t, 'title') || f,
    seam: fm(t, 'seam') || 'unsorted',
    date: fm(t, 'date') || '',
    dek: (fm(t, 'dek') || ''),
    relates, relTargets,
  });
}
const N = strata.length;

// cadence
const dayOf = (d) => String(d).slice(0, 10);
const byDay = {};
for (const s of strata) if (s.date) { const d = dayOf(s.date); byDay[d] = (byDay[d] || 0) + 1; }
const daysArr = Object.keys(byDay).sort();
const span = daysArr.length ? { first: daysArr[0], last: daysArr[daysArr.length - 1] } : { first: '', last: '' };
const calDays = span.first ? Math.round((Date.parse(span.last) - Date.parse(span.first)) / 86400000) + 1 : 0;
const busiestEntry = Object.entries(byDay).sort((a, b) => b[1] - a[1])[0] || ['', 0];
const busiest = { date: busiestEntry[0], count: busiestEntry[1] };
const daysWithZero = calDays - daysArr.length;

// seams
const seamCount = {};
for (const s of strata) seamCount[s.seam] = (seamCount[s.seam] || 0) + 1;
const seams = Object.entries(seamCount).sort((a, b) => b[1] - a[1]);

// makers + moves + kinds
let movesRows = [];
try { movesRows = R('coordination/moves.tsv').split('\n').filter(l => l && !l.startsWith('#')).map(l => l.split('\t')); } catch { }
const makers = new Set(movesRows.map(m => m[1]).filter(Boolean)).size;
const moves = movesRows.length;
const kindCount = {};
for (const m of movesRows) if (m[2]) kindCount[m[2]] = (kindCount[m[2]] || 0) + 1;
const kinds = Object.entries(kindCount).sort((a, b) => b[1] - a[1]);

// msgInstances (best-effort, matches analyze's try/catch → 0 fallback)
let msgInstances = 0;
try { msgInstances = new Set((execSync('git log --format=%s%n%b', { cwd: SNAP }).toString().match(/claude-[a-z]+-[a-z]+-[a-z0-9]{4,}/g) || [])).size; } catch { }

// check-density: strata that carry a standalone verifier (a FLOOR)
const strataSlugs = new Set(strata.map(s => s.slug));
const checked = new Set();
try { for (const f of fs.readdirSync(SNAP)) { const m = f.match(/^verify-(.+)\.mjs$/); if (m && strataSlugs.has(m[1])) checked.add(m[1]); } } catch { }
try {
  for (const d of fs.readdirSync(path.join(SNAP, 'research'))) {
    const rd = path.join(SNAP, 'research', d);
    try { if (strataSlugs.has(d) && fs.statSync(rd).isDirectory() && fs.readdirSync(rd).some(f => /verify.*\.mjs$/.test(f))) checked.add(d); } catch { }
  }
} catch { }
// Self-inclusive by design: this 500th portrait counts itself among the strata
// (n = 500) AND its own verifier (THIS file) among the standalone checks. The
// mirror is inside the frame, all the way: the page that verifies the corpus is
// one of the verified. So verifiers includes five-hundred-nights, and this figure
// agrees with analyze.mjs with zero special-casing. It is still a FLOOR: many
// strata verify inline in the page JS, which a file-name scan cannot see.
const verifiers = checked.size;
const checkDensityPct = +(100 * verifiers / N).toFixed(0);

// constellation
const edges = strata.reduce((a, s) => a + s.relates, 0);
const inDeg = {};
for (const s of strata) for (const t of s.relTargets) inDeg[t] = (inDeg[t] || 0) + 1;
const hubs = Object.entries(inDeg).sort((a, b) => b[1] - a[1]).slice(0, 8);
const avgDegree = +(edges / N).toFixed(1);

// theme drift (raw word-frequency proxy over titles + deks, first half vs second)
const STOP = new Set('the a an of to and in is it that this you your for on with as by are was be at from or how why what when it its not no yes into out one two more most can does do we our they their them he she his her only never every all any but so if then than into about over under across through'.split(' '));
const wordsOf = s => (s.title + ' ' + s.dek).toLowerCase().replace(/[^a-z\s]/g, ' ').split(/\s+/).filter(w => w.length > 3 && !STOP.has(w));
const sortedByDate = [...strata].filter(s => s.date).sort((a, b) => a.date.localeCompare(b.date));
const half = Math.floor(sortedByDate.length / 2);
const freq = arr => { const f = {}; for (const s of arr) for (const w of wordsOf(s)) f[w] = (f[w] || 0) + 1; return f; };
const early = freq(sortedByDate.slice(0, half)), late = freq(sortedByDate.slice(half));
const drift = Object.keys({ ...early, ...late })
  .map(w => ({ w, e: early[w] || 0, l: late[w] || 0, d: (late[w] || 0) - (early[w] || 0) }))
  .filter(x => x.e + x.l >= 6);
const themeRising = [...drift].sort((a, b) => b.d - a.d).slice(0, 10).map(x => x.w);
const themeFalling = [...drift].sort((a, b) => a.d - b.d).slice(0, 10).map(x => x.w);

// self-corrections: CITED from the companion study, not re-derived (read its curated dataset)
let selfCorrections = null;
try {
  const ev = JSON.parse(R('research/lineage-self-corrections/events.json'));
  selfCorrections = Array.isArray(ev) ? ev.length : (ev.events ? ev.events.length : (ev.count ?? null));
} catch { }

const perNight = calDays ? +(N / calDays).toFixed(1) : null;

const derived = {
  n: N, span, calDays, perNight, busiest, daysWithZero,
  seams, makers, msgInstances, moves, kinds,
  verifiers, checkDensityPct, edges, avgDegree, hubs,
  themeRising, themeFalling, selfCorrections,
};

// ── load the SHIPPED data.json and compare, field by field ──
const shippedPath = path.join(ROOT, 'public/strata/five-hundred-nights/data.json');
let shipped;
try { shipped = JSON.parse(fs.readFileSync(shippedPath, 'utf8')); }
catch (e) { console.error('FATAL: cannot read shipped data.json:', e.message); process.exit(2); }

let failures = 0;
const J = v => JSON.stringify(v);
const show = v => {
  if (Array.isArray(v)) return v.length > 6 ? J(v.slice(0, 6)).replace(/]$/, ', …]') + ' (' + v.length + ')' : J(v);
  if (v && typeof v === 'object') return J(v);
  return String(v);
};
function check(label, got, want) {
  const ok = J(got) === J(want);
  if (!ok) failures++;
  const status = ok ? 'PASS' : 'FAIL';
  const dots = '.'.repeat(Math.max(2, 22 - label.length));
  let line = `${status}  ${label} ${dots} ${show(got)}`;
  if (!ok) line += `   [data.json has ${show(want)}]`;
  console.log(line);
}

console.log(`\nFIVE HUNDRED NIGHTS: verifying data.json against the raw repository\n`);
console.log(`  reading ${N} strata, ${moves} moves at snapshot commit ${PIN.slice(0,10)}; comparing to ${path.relative(ROOT, shippedPath)}`);
console.log(`  note: check-density is self-inclusive (this page's own verifier counts) and still a FLOOR (many strata verify inline).`);
console.log('');

check('n', derived.n, shipped.n);
check('span.first', derived.span.first, shipped.span.first);
check('span.last', derived.span.last, shipped.span.last);
check('calDays', derived.calDays, shipped.calDays);
check('perNight', derived.perNight, shipped.perNight);
check('busiest.date', derived.busiest.date, shipped.busiest.date);
check('busiest.count', derived.busiest.count, shipped.busiest.count);
check('daysWithZero', derived.daysWithZero, shipped.daysWithZero);
check('seams', derived.seams, shipped.seams);
check('makers', derived.makers, shipped.makers);
check('msgInstances', derived.msgInstances, shipped.msgInstances);
check('moves', derived.moves, shipped.moves);
check('kinds', derived.kinds, shipped.kinds);
check('verifiers', derived.verifiers, shipped.verifiers);
check('checkDensityPct', derived.checkDensityPct, shipped.checkDensityPct);
check('edges', derived.edges, shipped.edges);
check('avgDegree', derived.avgDegree, shipped.avgDegree);
check('hubs', derived.hubs, shipped.hubs);
check('themeRising', derived.themeRising, shipped.themeRising);
check('themeFalling', derived.themeFalling, shipped.themeFalling);
check('selfCorrections', derived.selfCorrections, shipped.selfCorrections);

console.log('');
if (failures === 0) {
  console.log(`  OK: all checks PASS. data.json is faithful to the repository (${N} strata, ${moves} moves).`);
  console.log(`  The page displays only these figures and recomputes perNight, checkDensityPct and avgDegree in-browser.`);
  process.exit(0);
} else {
  console.error(`  FAIL: ${failures} check(s) FAILED. data.json has drifted from the repository. Re-run analyze.mjs --write.`);
  process.exit(1);
}
