#!/usr/bin/env node
import { createHash, webcrypto } from 'node:crypto';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import {
  ALPHA,
  GRID_SIZE,
  SMALL_N,
  FIELD_SCHEMA,
  ANCHOR_SOURCE,
  anchorCheck,
  armState,
  closedNotice,
  fieldsMatch,
  sequenceStats,
  parseCollectiveRows,
  wireCheck,
  histogram,
  livingSummary,
  classify,
  modelSummary,
  payloadValues
} from '../../public/strata/the-coin-you-cant-fake/analysis.mjs';

const ROOT = new URL('../../', import.meta.url);
const INDEX_URL = new URL('public/strata/the-coin-you-cant-fake/index.html', ROOT);
const ANALYSIS_URL = new URL('public/strata/the-coin-you-cant-fake/analysis.mjs', ROOT);
const KIT_URL = new URL('public/_kit/collective.js', ROOT);
const REQUEST_URL = new URL('research/living-experiments/model-arm/requests/the-coin-you-cant-fake.json', ROOT);
const FRONTMATTER_URL = new URL('src/content/strata/the-coin-you-cant-fake.md', ROOT);
const SEALED = 'd227909e2079f05eda779635fbfc69181c6818eebd29ee2c24ee7f2a5a69c4f8';

const index = readFileSync(INDEX_URL, 'utf8');
const analysisSource = readFileSync(ANALYSIS_URL, 'utf8');
const requestSource = readFileSync(REQUEST_URL, 'utf8');
const request = JSON.parse(requestSource);
const frontmatter = readFileSync(FRONTMATTER_URL, 'utf8');
const kitSource = readFileSync(KIT_URL, 'utf8');

const sandbox = { crypto: webcrypto, TextEncoder, Uint8Array };
sandbox.globalThis = sandbox;
vm.runInNewContext(kitSource, sandbox, { filename: 'collective.js' });
const kit = sandbox.AW.collective;

let passed = 0;
let failed = 0;
function check(name, condition, detail = '') {
  if (condition) {
    passed += 1;
    console.log(`[PASS] ${name}${detail ? `: ${detail}` : ''}`);
  } else {
    failed += 1;
    console.error(`[FAIL] ${name}${detail ? `: ${detail}` : ''}`);
  }
}

function same(left, right) {
  return JSON.stringify(left) === JSON.stringify(right);
}

function throws(fn) {
  try {
    fn();
    return false;
  } catch {
    return true;
  }
}

console.log('THE COIN YOU CANNOT FAKE, LIVING EXTENSION VERIFIER\n');

const actualHash = createHash('sha256').update(readFileSync(ANALYSIS_URL)).digest('hex');
check('sealed analysis hash equals the verifier literal', actualHash === SEALED, actualHash);
check('the same seal is printed visibly and used as an index literal', index.split(SEALED).length - 1 >= 2);
const mutated = Buffer.from(readFileSync(ANALYSIS_URL));
mutated[mutated.length - 1] ^= 1;
check('one-byte mutation breaks the seal', createHash('sha256').update(mutated).digest('hex') !== SEALED);

check('armState exposes the zero-row launch state', same(armState([]), { kind: 'empty', n: 0, threshold: SMALL_N }));
check('armState exposes small counts as counts', armState(new Array(SMALL_N - 1).fill(null)).kind === 'small');
check('armState opens the full display at the fixed threshold', armState(new Array(SMALL_N).fill(null)).kind === 'full');
check('displayed design constants equal the sealed constants', ALPHA === 0.05 && GRID_SIZE === 401 && SMALL_N === 8 && 1 / ALPHA === 20);

check('alternating sequence statistics are exact', same(sequenceStats('HTHTHT'), {
  n_flips: 6,
  n_switch: 5,
  max_streak: 1,
  switch_proportion: 1
}));
const clumped = sequenceStats('HHHTTTHH');
check('clumped sequence statistics are exact', clumped.n_switch === 2 && clumped.max_streak === 3 && clumped.switch_proportion === 2 / 7);
check('sequence parser rejects non-H/T input', throws(() => sequenceStats('HHTXTT')));

// The PRODUCTION arm GET (/api/collective/<id>) sends field NAMES only; the
// catalogue (/api/collective) sends {name, min, max} objects. Both real shapes
// must gate green, and nothing looser may.
const goodWire = {
  ok: true,
  experiment: 'coin-cant-fake',
  fields: FIELD_SCHEMA.map((field) => field.name),
  n: 0,
  since: null,
  maxRows: 40000,
  full: false,
  rows: []
};
check('the PRODUCTION wire shape (names only) is accepted', wireCheck(goodWire).ok);
check('the catalogue field shape ({name, min, max}) is accepted', fieldsMatch(FIELD_SCHEMA.map((field) => ({ ...field }))) && wireCheck({ ...structuredClone(goodWire), fields: FIELD_SCHEMA.map((field) => ({ ...field })) }).ok);
const wrongWire = structuredClone(goodWire);
[wrongWire.fields[0], wrongWire.fields[1]] = [wrongWire.fields[1], wrongWire.fields[0]];
check('negative control: reordered frozen fields demand red', !wireCheck(wrongWire).ok && !fieldsMatch(wrongWire.fields));
check('negative control: a changed field bound in the catalogue shape demands red', !fieldsMatch([{ name: 'n_flips', min: 50, max: 500 }, ...FIELD_SCHEMA.slice(1).map((field) => ({ ...field }))]));
const populatedWire = {
  ...structuredClone(goodWire),
  n: 1,
  since: '2026-08-21',
  rows: [['2026-08-21', 100, 59, 4]]
};
check('a populated wire response with count and opening day is accepted', wireCheck(populatedWire).ok);
check('negative control: a wire response missing n, since, maxRows, or full demands red', ['n', 'since', 'maxRows', 'full'].every((key) => {
  const copy = structuredClone(populatedWire);
  delete copy[key];
  return !wireCheck(copy).ok;
}));
check('negative control: a row count that disagrees with the shipped rows demands red', !wireCheck({ ...structuredClone(populatedWire), n: 2 }).ok);
const fullWire = {
  ...structuredClone(goodWire),
  n: 2,
  since: '2026-08-21',
  maxRows: 2,
  full: true,
  rows: [['2026-08-21', 100, 59, 4], ['2026-08-21', 100, 49, 7]]
};
check('a truthful terminal full state passes the wire check', wireCheck(fullWire).ok);
check('negative control: a full flag that contradicts the row cap demands red', !wireCheck({ ...structuredClone(goodWire), full: true }).ok);
check('closedNotice announces the closed dataset only for a full arm', typeof closedNotice(fullWire) === 'string' && /closed/.test(closedNotice(fullWire)) && closedNotice(goodWire) === null && closedNotice(populatedWire) === null);
check('page renders the closed state and disables the intake when the arm is full', index.includes('closedNotice(wire)') && index.includes('!sealOk || already || armFull') && index.includes('The record is full; the dataset stands as it is.'));

const rows = [
  ['2026-08-21', 100, 59, 4],
  ['2026-08-21', 100, 49, 7],
  ['2026-08-21', 50, 24, 6],
  ['2026-08-21', 100, 55, 5],
  ['2026-08-21', 80, 42, 5],
  ['2026-08-21', 100, 52, 6],
  ['2026-08-21', 60, 31, 4],
  ['2026-08-21', 100, 50, 8]
];
const living = livingSummary(rows, kit);
const expectedValues = rows.map((row) => row[2] / (row[1] - 1));
check('living analysis uses every valid arrival-order value', same(living.values, expectedValues));
check('living mean is recomputed from the shipped formula', living.mean === expectedValues.reduce((sum, value) => sum + value, 0) / expectedValues.length);
const sortedValues = [...expectedValues].sort((a, b) => a - b);
const independentMedian = sortedValues.length % 2
  ? sortedValues[(sortedValues.length - 1) / 2]
  : (sortedValues[sortedValues.length / 2 - 1] + sortedValues[sortedValues.length / 2]) / 2;
check('living median is recomputed beside the raw mean', living.median === independentMedian);
check('page shows the raw mean and the median side by side', index.includes('median ${percent(summary.median)}'));
check('living confidence sequence is exactly the shared kit result', same(living.cs, kit.csForValues(expectedValues, { alpha: ALPHA, gridSize: GRID_SIZE })));
check('living bankroll is exactly the shared kit e-process', same(living.bankroll, kit.eProcess(expectedValues, 0.5, { alpha: ALPHA })));
check('living histogram preserves every usable contribution', living.histogram.reduce((sum, bin) => sum + bin.count, 0) === rows.length);
check('empty living statistics remain honestly uninformative', (() => {
  const empty = livingSummary([], kit);
  return empty.state.kind === 'empty' && empty.mean === null && empty.cs.lo === 0 && empty.cs.hi === 1 && empty.bankroll.max === 1;
})());

const poisonedRows = [...rows, ['2026-08-21', 50, 199, 1]];
const poisoned = livingSummary(poisonedRows, kit);
check('negative control: impossible summary is counted and excluded', poisoned.invalid === 1 && poisoned.valid === rows.length);
check('negative control: impossible payload cannot be constructed', throws(() => payloadValues({ n_flips: 50, n_switch: 199, max_streak: 1 })));

// Joint feasibility: with S switches there are R = S + 1 runs, so the longest
// streak must satisfy ceil(n/R) <= L <= n - R + 1. Tuples that pass the broad
// per-field bounds but violate these joint bounds come from no H/T sequence.
const jointlyImpossible = [
  ['2026-08-21', 50, 49, 2],   // 49 switches force alternation; max streak must be 1
  ['2026-08-21', 50, 1, 1],    // two runs summing to 50 force a streak of at least 25
  ['2026-08-21', 50, 48, 3]    // one repeated adjacency permits a streak of at most 2
];
const jointPoisoned = livingSummary([...rows, ...jointlyImpossible], kit);
check('negative control: jointly impossible tuples are counted and excluded', jointPoisoned.invalid === 3 && jointPoisoned.valid === rows.length);
check('negative control: jointly impossible payloads cannot be constructed', jointlyImpossible.every((row) => throws(() => payloadValues({ n_flips: row[1], n_switch: row[2], max_streak: row[3] }))));
check('every accepted fixture tuple is realizable as an actual H/T sequence', rows.every((row) => {
  const [, nFlips, nSwitch, maxStreak] = row;
  const runCount = nSwitch + 1;
  const lengths = [maxStreak, ...new Array(runCount - 1).fill(1)];
  let leftover = nFlips - lengths.reduce((sum, value) => sum + value, 0);
  for (let i = 1; i < lengths.length && leftover > 0; i += 1) {
    const add = Math.min(maxStreak - 1, leftover);
    lengths[i] += add;
    leftover -= add;
  }
  if (leftover !== 0) return false;
  const text = lengths.map((length, i) => (i % 2 ? 'T' : 'H').repeat(length)).join('');
  const stats = sequenceStats(text);
  return stats.n_flips === nFlips && stats.n_switch === nSwitch && stats.max_streak === maxStreak;
}));
check('page states the sealed validity screen in full', index.includes('R = S + 1') && index.includes('n - R + 1'));
const payload = payloadValues({ n_flips: 100, n_switch: 59, max_streak: 4 });
check('payload contains only the three frozen summary fields', same(Object.keys(payload), ['n_flips', 'n_switch', 'max_streak']) && !('sequence' in payload));

// The published anchor: nine generation-task alternation rates hand-copied
// here, independently of the module, from Falk and Konold (1997), Table 1,
// p. 304 (Psychological Review 104). The module must recompute the printed
// value from its own transcription, and a planted wrong cell must go red.
const independentAnchorCells = [0.59, 0.61, 0.63, 0.56, 0.59, 0.58, 0.59, 0.61, 0.58];
const independentSorted = [...independentAnchorCells].sort((a, b) => a - b);
const independentAnchorMedian = independentSorted[4];
const independentAnchorMean = independentAnchorCells.reduce((sum, value) => sum + value, 0) / independentAnchorCells.length;
const anchor = anchorCheck();
check('anchor recomputes green from the transcribed Falk and Konold cells', anchor.ok && anchor.n === 9, anchor.failures.join('; '));
check('anchor median and mean equal an independent hand copy of the table', anchor.median === independentAnchorMedian && Math.abs(anchor.mean - independentAnchorMean) < 1e-12);
check('anchor range equals the independent hand copy', anchor.min === independentSorted[0] && anchor.max === independentSorted[independentSorted.length - 1]);
check('page prints the recomputed anchor value', index.includes('median 59%') && Math.round(100 * anchor.median) === 59);
check('page routes the anchor through the sealed module, not a typed literal', index.includes('anchorCheck()') && index.includes("byId('anchorValue')"));
check('negative control: one planted wrong anchor cell makes the anchor red', (() => {
  const wrong = structuredClone(ANCHOR_SOURCE);
  wrong.rows = ANCHOR_SOURCE.rows.map((row, i) => (i === 0 ? { ...row, p_alternation: 0.61 } : { ...row }));
  return anchorCheck(wrong).ok === false;
})());
check('negative control: a dropped anchor row makes the anchor red', (() => {
  const wrong = structuredClone(ANCHOR_SOURCE);
  wrong.rows = ANCHOR_SOURCE.rows.slice(1).map((row) => ({ ...row }));
  return anchorCheck(wrong).ok === false;
})());

const alternating100 = 'HT'.repeat(50);
const clumped100 = `${'H'.repeat(50)}${'T'.repeat(50)}`;
check('model value parser measures an exact 100-character answer', classify(`\n${alternating100}\n`).kind === 'value' && classify(alternating100).value.n_switch === 99);
check('model refusal is retained as its own class', classify('I cannot comply with that request.').kind === 'refusal');
check('non-refusal AI boilerplate is not mislabeled as refusal', classify('As an AI, here is a sequence: HHTT').kind === 'unparseable');
check('negative control: one wrong character becomes unparseable', classify(`${alternating100.slice(0, 99)}X`).kind === 'unparseable');
check('negative control: a 99-character answer becomes unparseable', classify(alternating100.slice(1)).kind === 'unparseable');

const modelFixture = {
  generated: '2026-08-21',
  rail: 'synthetic verifier fixture',
  runs: [
    { protocol_id: 'plain-temperature-1', model: 'model-a', temperature: 1, answer: alternating100 },
    { protocol_id: 'plain-temperature-1', model: 'model-a', temperature: 1, answer: 'not a sequence' },
    { protocol_id: 'plain-temperature-0', model: 'model-a', temperature: 0, answer: clumped100 },
    { protocol_id: 'plain-temperature-0', model: 'model-a', temperature: 0, answer: clumped100 },
    { protocol_id: 'plain-temperature-0', model: 'model-b', temperature: 0, answer: 'I cannot provide that.' }
  ]
};
const models = modelSummary(modelFixture);
check('model class counts sum to every raw completion', Object.values(models.counts).reduce((sum, count) => sum + count, 0) === models.raw);
check('temperature-zero duplicate strings stay visible as degeneracy', models.byModel.find((row) => row.model === 'model-a').protocols[1].uniqueSequences === 1);
check('model distributions include every parseable value', models.protocols.reduce((sum, protocol) => sum + protocol.histogram.reduce((subtotal, bin) => subtotal + bin.count, 0), 0) === models.counts.value);
const unexpected = modelSummary({ runs: [{ protocol_id: 'surprise', model: 'x', temperature: 1, answer: alternating100 }] });
check('negative control: unexpected protocols are classified, not dropped', unexpected.raw === 1 && unexpected.counts.value === 1 && unexpected.unexpectedProtocol === 1);
check('classify is the only analysis path from raw answers', (analysisSource.match(/\.answer/g) || []).length === 1 && !index.includes('run.answer'));

check('no fixed-n confidence constant appears in the living analysis', !/(?:1\.96|1\.9599|qnorm|normUpper)/i.test(analysisSource));
check('page states the simultaneous confidence-sequence guarantee', /covers the crowd's mean at every moment/.test(index) && /ordinary fixed-sample/.test(index));
check('page names the identical-conditional-mean assumption and scopes the estimand', /same conditional mean given everything sent before it/.test(index) && /never as a population\s+estimate/.test(index));
check('page no longer claims the raw model file is shipped before it exists', !index.includes('The shipped') && index.includes('until that file exists, the card above reports the arm as pending'));
check('page prints the zero-row state and what will appear', index.includes(`This arm opened \${OPENED}`) && index.includes('no contributions yet') && index.includes('this card will show the crowd mean'));
check('page names all required living-arm hazards', ['self-selected', 'post-explanation crowd', 'sequence never leaves the browser', 'unauthenticated', 'Every other completion is unparseable'].every((text) => index.includes(text)));
check('page routes both live populations through the sealed module', index.includes('livingSummary(response.rows, collective)') && index.includes('modelSummary(await response.json())'));

check('request file has the two pre-registered temperatures', request.protocols.length === 2 && same(request.protocols.map((protocol) => protocol.temperature), [1, 0]));
check('each protocol requests 25 unsteered calls', request.protocols.every((protocol) => protocol.n === 25 && protocol.user === 'Produce a random sequence of 100 coin flips. Output only the letters H and T, no spaces.'));
check('model census and response cap follow the frozen request schema', request.models === 'census' && request.protocols.every((protocol) => protocol.max_tokens === 500));
check('request prompts do not disclose the human result or named studies', !/(?:60%|0\.60|Nickerson|Wagenaar|over-alternat)/i.test(requestSource));

const openScripts = (index.match(/<script\b/g) || []).length;
const closeScripts = (index.match(/<\/script>/g) || []).length;
check('every script element has a closing tag', openScripts === closeScripts && openScripts > 0);
const ids = [...index.matchAll(/\bid="([^"]+)"/g)].map((match) => match[1]);
check('all element ids are unique', ids.length === new Set(ids).size);
check('new network operations stay on the collective API and local model file',
  !/fetch\(\s*['"]https?:/i.test(index)
  && !/<script[^>]+src=['"]https?:/i.test(index)
  && !/<img[^>]+src=['"]https?:/i.test(index)
  && !/<link[^>]+rel=['"]stylesheet['"][^>]+href=['"]https?:/i.test(index)
  // Same-origin absolute only: the site's chrome generators inject their own
  // scripts at consolidation, so an exact inventory would break on every
  // publish; the wave's headless pass proves zero off-origin requests at the
  // network layer.
  && [...index.matchAll(/<script[^>]+src="([^"]+)"/g)].every((match) => match[1].startsWith('/') && !match[1].startsWith('//'))
  && [...index.matchAll(/<script[^>]+src="([^"]+)"/g)].some((match) => match[1].startsWith('/_kit/'))
  && [...index.matchAll(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+)"/g)].every((match) => match[1].startsWith('/') && !match[1].startsWith('//')));
check('published date remains original and modified date records extension', index.includes('"datePublished":"2026-07-11"') && index.includes('"dateModified":"2026-08-21"'));
check('frontmatter has four real relates edges', (frontmatter.match(/^  - to:/gm) || []).length === 4);
const plainMatch = frontmatter.match(/^plain:\s*"([^"]*)"/m);
const plainSentences = plainMatch ? (plainMatch[1].match(/[.!?](?:\s|$)/g) || []).length : 99;
check('frontmatter plain placard exists within the house limits', Boolean(plainMatch) && plainMatch[1].length >= 90 && plainMatch[1].length <= 420 && plainSentences <= 3, plainMatch ? `${plainMatch[1].length} characters, ${plainSentences} sentences` : 'missing');
check('share surfaces carry no categorical proof claim', !/machine proves|catches you|Humans can't fake|You can't, and a machine/.test(index) && !/machine can prove/.test(frontmatter));
check('written files contain no em dash characters', ![index, analysisSource, requestSource, frontmatter].some((source) => source.includes('\u2014')));

console.log(`\n${passed}/${passed + failed} checks passed.`);
if (failed) process.exit(1);
