// Plain-node verifier for the correction and all three specification grids.
// It reads the same public data file as the page and independently checks it
// against the committed raw snapshots.
import { readFileSync, readdirSync, statSync } from 'fs';
import { createHash } from 'crypto';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import vm from 'vm';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const SNAP = join(HERE, 'snapshots');
const PAGE = join(ROOT, 'public', 'strata', 'who-reads-the-wasteland', 'index.html');
const DATA_PATH = join(ROOT, 'public', 'strata', 'who-reads-the-wasteland', 'data', 'multiverse.json');
const FINDINGS_PATH = join(ROOT, 'public', 'strata', 'who-reads-the-wasteland', 'findings.json');
const page = readFileSync(PAGE, 'utf8');
const dataBytes = readFileSync(DATA_PATH);
const data = JSON.parse(dataBytes);
const findings = JSON.parse(readFileSync(FINDINGS_PATH, 'utf8'));

const kitSource = readFileSync(join(ROOT, 'public', '_kit', 'multiverse.js'), 'utf8');
const sandbox = { window: {} };
vm.runInContext(kitSource, vm.createContext(sandbox));
const M = sandbox.window.AW.multiverse;

let assertions = 0;
let failures = 0;
const check = (condition, message, detail = '') => {
  assertions++;
  if (!condition) failures++;
  console.log(`${condition ? 'ok  ' : 'FAIL'} ${message}${detail ? ` (${detail})` : ''}`);
};
const equal = (actual, expected, message) => check(actual === expected, message, `${actual} vs ${expected}`);
const near = (actual, expected, tolerance, message) => check(Math.abs(actual - expected) <= tolerance, message, `${actual} vs ${expected}`);
const sum = (values) => values.reduce((a, b) => a + b, 0);
const readSnapshot = (name) => JSON.parse(readFileSync(join(SNAP, name), 'utf8'));

const dayFiles = readdirSync(SNAP).filter((name) => /^day-\d{4}-\d\d-\d\d\.json$/.test(name)).sort();
const rawDays = dayFiles.map(readSnapshot).filter((day) => day.day >= '2026-07-20');
const extensionDir = join(SNAP, 'week-2026-07-27');
const extensionDays = readdirSync(extensionDir).filter((name) => /^day-\d{4}-\d\d-\d\d\.json$/.test(name)).sort()
  .map((name) => JSON.parse(readFileSync(join(extensionDir, name), 'utf8')));
const allRawDays = [...rawDays, ...extensionDays];
const rawFlow = readSnapshot('flow.json').topFlow;

// Provenance and mechanical trim.
equal(dataBytes.length, 251608, 'shipped multiverse trim has the documented byte size');
equal(createHash('sha256').update(dataBytes).digest('hex'), '37296c2157715507a631c0fcacb938df306d55d5be22cbe7bf686327aa951650', 'shipped trim has the documented SHA-256');
const rawJsonPaths = [
  ...readdirSync(SNAP).filter((name) => name.endsWith('.json')).map((name) => join(SNAP, name)),
  ...readdirSync(extensionDir).filter((name) => name.endsWith('.json')).map((name) => join(extensionDir, name)),
];
equal(rawJsonPaths.reduce((n, path) => n + statSync(path).size, 0), 2089522, 'committed snapshots have the documented total byte size');
equal(data.days.length, 14, 'trim retains all fourteen complete days');
equal(data.flow.length, rawFlow.length, 'trim retains every flow row');
check(JSON.stringify(data.flow) === JSON.stringify(rawFlow.map((row) => [row.src, row.dst, row.views])), 'trimmed flow rows equal the raw snapshot');
for (let i = 0; i < allRawDays.length; i++) {
  equal(data.days[i].total, allRawDays[i].dayTotal, `trim keeps ${allRawDays[i].day} total`);
  equal(data.days[i].sourcePath.length, allRawDays[i].bySourcePathForDay.length, `trim keeps every ${allRawDays[i].day} source-path row`);
}

// Job one: correction and neighbouring claims, directly from raw snapshots.
const prefixes = ['/tools/', '/instruments/', '/terminal/', '/os/', '/arcade/', '/games/', '/lab/', '/ask/'];
const operator = new Set(['/os/', '/terminal/']);
const isTool = (path) => prefixes.some((prefix) => path.startsWith(prefix));
const inclusiveNumerator = sum(rawFlow.filter((row) => isTool(row.src) || isTool(row.dst)).map((row) => row.views));
const inclusiveDenominator = sum(rawFlow.map((row) => row.views));
const audienceRows = rawFlow.filter((row) => !operator.has(row.src) && !operator.has(row.dst));
const audienceNumerator = sum(audienceRows.filter((row) => isTool(row.src) || isTool(row.dst)).map((row) => row.views));
const audienceDenominator = sum(audienceRows.map((row) => row.views));
equal(inclusiveNumerator, 361, 'operator-inclusive numerator is 361');
equal(inclusiveDenominator, 767, 'operator-inclusive denominator is 767');
equal(audienceNumerator, 196, 'operator-free numerator is 196');
equal(audienceDenominator, 602, 'operator-free denominator is 602');
near(audienceNumerator / audienceDenominator, 0.32558139534883723, 1e-15, 'corrected operator-free share is 32.6%');
near(inclusiveNumerator / inclusiveDenominator, 0.4706649282920469, 1e-15, 'consistent inclusive share is 47.1%');
near(audienceNumerator / inclusiveDenominator, 0.25554106910039115, 1e-15, 'old mixed fraction reproduces the erroneous 25.6%');
equal(findings.toolSignal.flowTotalNoOperator, 602, 'analyser publishes the corrected denominator');
near(findings.toolSignal.flowToolShareNoOperator, audienceNumerator / audienceDenominator, 1e-15, 'analyser uses one population rule on both sides');

const toolPath = (path) => isTool(path) && !operator.has(path);
let toolViews = 0, toolPulses = 0, strataViews = 0, strataPulses = 0;
for (const day of rawDays) {
  for (const row of day.byPathForDay) {
    if (toolPath(row.path)) toolViews += row.views;
    if (row.path.startsWith('/strata/')) strataViews += row.views;
  }
  for (const row of day.pulseForDay.byPath) {
    if (toolPath(row.path)) toolPulses += row.views;
    if (row.path.startsWith('/strata/')) strataPulses += row.views;
  }
}
equal(toolPulses, 117, 'tool execution numerator is 117');
equal(toolViews, 323, 'tool execution denominator is 323');
equal(strataPulses, 226, 'strata execution numerator is 226');
equal(strataViews, 7607, 'strata execution denominator is 7,607');
near(toolPulses / toolViews, 0.3622291021671827, 1e-15, 'tool execution share is 36.2%');
near(strataPulses / strataViews, 0.029709478112265018, 1e-15, 'strata execution share is 3.0%');
near((toolPulses / toolViews) / (strataPulses / strataViews), 12.192375133565305, 1e-12, 'execution-rate ratio rounds to 12.2x');
const swRows = rawFlow.filter((row) => row.src.endsWith('sw.js'));
equal(swRows.length, 1, 'there is exactly one service-worker flow edge');
equal(sum(swRows.map((row) => row.views)), 24, 'service-worker edge carries 24 hops');

// Main coherent grid. Operator treatment and denominator population are one
// coupled rule because crossing them independently creates the published bug.
const toolSets = {
  published: prefixes,
  hands: ['/tools/', '/instruments/', '/terminal/', '/os/', '/arcade/', '/games/'],
};
const flowDims = [
  { name: 'toolSet', options: [{ value: 'published' }, { value: 'hands' }] },
  { name: 'population', options: [{ value: 'inclusive' }, { value: 'audience' }] },
];
const flowSpecs = M.grid(flowDims);
const flowRows = (spec) => data.flow.filter(([src, dst]) => spec.population === 'inclusive' || (!operator.has(src) && !operator.has(dst)));
const evaluateFlow = (spec, override) => {
  const tool = override ? (path) => override.has(path) : (path) => toolSets[spec.toolSet].some((prefix) => path.startsWith(prefix));
  const rows = flowRows(spec);
  const denominator = sum(rows.map((row) => row[2]));
  const numerator = sum(rows.filter(([src, dst]) => tool(src) || tool(dst)).map((row) => row[2]));
  return denominator ? { value: numerator / denominator, numerator, denominator } : null;
};
const flowResults = M.runSync(flowSpecs, (spec) => evaluateFlow(spec));
const flowCurve = M.curve(flowResults);
const flowAnchor = M.locate(flowResults, { toolSet: 'published', population: 'audience' });
const flowParts = M.decompose(flowDims, flowResults);
equal(flowCurve.n, 4, 'flow grid has four coherent specifications');
equal(flowCurve.nFailed, 0, 'flow grid has no undefined coherent specifications');
near(flowCurve.min, 154 / 602, 1e-15, 'flow curve minimum is 25.6%');
near(flowCurve.max, 361 / 767, 1e-15, 'flow curve maximum is 47.1%');
near(flowAnchor.percentile, 0.375, 1e-15, 'corrected anchor is at the 37.5th percentile');
equal(flowParts.factors[0].name, 'population', 'population rule carries the most flow variance');
near(flowParts.factors[0].share, 0.8554893512105078, 1e-12, 'population rule carries 85.5% of flow variance');
near(flowParts.interactionShare, 0.0020691760711891213, 1e-12, 'flow interaction share is 0.2%');
check(flowParts.exact, 'flow decomposition is exact on the complete balanced grid');

const shuffleFlow = (rng) => {
  const shuffled = {};
  for (const spec of flowSpecs) {
    const key = `${spec.toolSet}|${spec.population}`;
    if (shuffled[key]) continue;
    const paths = [...new Set(flowRows(spec).flatMap(([src, dst]) => [src, dst]))];
    const nTools = paths.filter((path) => toolSets[spec.toolSet].some((prefix) => path.startsWith(prefix))).length;
    shuffled[key] = new Set(M.shuffled(paths, rng).slice(0, nTools));
  }
  return shuffled;
};
const permutation = M.permutationTest(flowSpecs, flowResults, shuffleFlow,
  (spec, shuffled) => evaluateFlow(spec, shuffled[`${spec.toolSet}|${spec.population}`]),
  { iterations: 499, seed: 260726 });
near(permutation.pMedian, 0.802, 1e-15, '499-draw seeded permutation p-value is 0.802');
near(permutation.resolution, 0.002, 1e-15, 'permutation resolution is 0.002');

// Explicitly test the denominator refusal that the UI couples away.
const crossedPopulationDims = [
  { name: 'toolSet', options: [{ value: 'published' }, { value: 'hands' }] },
  { name: 'numeratorPopulation', options: [{ value: 'inclusive' }, { value: 'audience' }] },
  { name: 'denominatorPopulation', options: [{ value: 'inclusive' }, { value: 'audience' }] },
];
const refused = M.runSync(M.grid(crossedPopulationDims), (spec) => {
  if (spec.numeratorPopulation !== spec.denominatorPopulation) return { value: null, reason: 'numerator and denominator populations differ' };
  return evaluateFlow({ toolSet: spec.toolSet, population: spec.numeratorPopulation });
});
equal(M.curve(refused).nFailed, 4, 'all four mixed-population cells are refused');
check(refused.filter((row) => !row.ok).every((row) => /populations differ/.test(row.reason)), 'every refused flow cell names the mismatch');

// Human floor grid.
const humanDims = [
  { name: 'human', options: [{ value: 'uaHuman' }, { value: 'pulse' }, { value: 'pulseHuman' }] },
  { name: 'window', options: ['first', 'second', 'both'].map((value) => ({ value })) },
];
const selectDays = (window) => window === 'first' ? data.days.slice(0, 7)
  : window === 'second' ? data.days.slice(7, 14) : data.days;
const evaluateHuman = (spec) => {
  const days = selectDays(spec.window);
  const denominator = sum(days.map((day) => day.total));
  const numerator = sum(days.map((day) => day[spec.human]));
  return denominator ? { value: numerator / denominator, numerator, denominator } : null;
};
const humanResults = M.runSync(M.grid(humanDims), evaluateHuman);
const humanCurve = M.curve(humanResults);
const humanAnchor = M.locate(humanResults, { human: 'pulseHuman', window: 'first' });
equal(humanCurve.nOk, 9, 'human grid defines all nine specifications');
near(humanAnchor.value, 462 / 10187, 1e-15, 'strict seven-day human anchor is 462/10,187');
near(humanAnchor.percentile, 5 / 18, 1e-15, 'strict human anchor is at the 27.8th percentile');

// AI label grid.
const aiDims = [
  { name: 'enumeration', options: Array.from({ length: 10 }, (_, i) => ({ value: (50 + i * 5) / 100 })) },
  { name: 'polling', options: Array.from({ length: 7 }, (_, i) => ({ value: (10 + i * 10) / 100 })) },
  { name: 'index', options: [{ value: 'front' }, { value: 'published' }] },
  { name: 'window', options: ['first', 'second', 'both'].map((value) => ({ value })) },
  { name: 'vendor', options: [{ value: 'all' }, { value: 'openai' }] },
];
const evaluateAi = (spec, source = data) => {
  let characterised = 0, flagged = 0;
  const sourceDays = spec.window === 'first' ? source.days.slice(0, 7)
    : spec.window === 'second' ? source.days.slice(7, 14) : source.days;
  for (const day of sourceDays) {
    const grouped = new Map();
    for (const [vendor, path, count] of day.sourcePath) {
      if (!vendor.endsWith(':live') || (spec.vendor === 'openai' && vendor !== 'ai:openai:live')) continue;
      if (!grouped.has(vendor)) grouped.set(vendor, []);
      grouped.get(vendor).push([path, count]);
    }
    for (const rows of grouped.values()) {
      const volume = sum(rows.map((row) => row[1]));
      if (volume < 15) continue;
      characterised += volume;
      const singleton = rows.filter((row) => row[1] === 1).length / rows.length;
      const indexShare = sum(rows.filter((row) => row[0] === '/' || (spec.index === 'published' && row[0] === '/archive/')).map((row) => row[1])) / volume;
      if (singleton >= spec.enumeration || indexShare >= spec.polling) flagged += volume;
    }
  }
  return characterised ? { value: flagged / characterised, flagged, characterised } : null;
};
const aiResults = M.runSync(M.grid(aiDims), (spec) => evaluateAi(spec));
const aiCurve = M.curve(aiResults);
const aiAnchor = M.locate(aiResults, { enumeration: 0.9, polling: 0.5, index: 'published', window: 'first', vendor: 'all' });
const aiParts = M.decompose(aiDims, aiResults);
equal(aiCurve.n, 840, 'AI grid has 840 specifications');
equal(aiCurve.nFailed, 0, 'AI grid has no undefined specifications');
near(aiCurve.min, 0.7073490813648294, 1e-15, 'AI grid minimum is 70.7%');
near(aiCurve.median, 1, 1e-15, 'AI grid median is 100%');
near(aiAnchor.value, 1, 1e-15, 'published AI specification recomputes 100%');
near(aiAnchor.percentile, 0.55, 1e-15, 'published AI specification is at the 55.0th percentile');
equal(aiParts.factors[0].name, 'polling', 'polling threshold carries the most AI-grid variance');
near(aiParts.interactionShare, 0.6519733167728996, 1e-12, 'AI-grid interactions carry 65.2% of variance');
equal(evaluateAi({ enumeration: .9, polling: .5, index: 'published', window: 'both', vendor: 'all' }, { days: [] }), null, 'empty AI subsample is undefined');

// Static prose guards. These catch a stale sentence even when live code is right.
for (const phrase of [
  '26% = 196 / 767',
  '32.6% = 196 / 602',
  '47.1%, or 361 of 767',
  'increases the operator-free finding by 6.6 percentage points',
  'operator-free numerator divided by an operator-inclusive denominator',
  'Together these grids run 853 specifications',
  'Undefined: no source-day in this subsample cleared 15 views.',
  'not downsampled',
]) check(page.includes(phrase), `page source contains: ${phrase}`);
check(page.includes('src="/_kit/multiverse.js"'), 'page loads the shared multiverse kit');
check(page.includes('role="status"') && page.includes('aria-live="polite"'), 'live readouts expose an accessible status region');
check(page.includes('prefers-reduced-motion:reduce'), 'page retains its reduced-motion guard');
check(!/<script[^>]+src=["']https?:\/\//i.test(page), 'page makes no third-party script request');

console.log(`\n${assertions} assertions, ${failures} failures`);
process.exit(failures ? 1 : 0);
