import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..', '..');
const htmlPath = path.join(root, 'public', 'strata', 'the-number-under-the-fingernail', 'index.html');
const mdPath = path.join(root, 'src', 'content', 'strata', 'the-number-under-the-fingernail.md');
const readmePath = path.join(here, 'README.md');
const html = fs.readFileSync(htmlPath, 'utf8');
const markdown = fs.readFileSync(mdPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');

let passed = 0;
let failed = 0;

function report(label, ok, detail = '') {
  const mark = ok ? 'PASS' : 'FAIL';
  console.log(`${mark}  ${label}${detail ? ` | ${detail}` : ''}`);
  if (ok) passed += 1;
  else failed += 1;
}

function close(a, b, tolerance = 1e-12) {
  return Math.abs(a - b) <= tolerance;
}

function rate(events, pairs) {
  return 100 * events / pairs;
}

function wilson(events, pairs) {
  const z = 1.96;
  const p = events / pairs;
  const d = 1 + z * z / pairs;
  const centre = (p + z * z / (2 * pairs)) / d;
  const half = z * Math.sqrt(p * (1 - p) / pairs + z * z / (4 * pairs * pairs)) / d;
  return [100 * (centre - half), 100 * (centre + half)];
}

const evidenceMatch = html.match(/<script id="evidence-data" type="application\/json">([\s\S]*?)<\/script>/);
report('evidence JSON block exists', Boolean(evidenceMatch));
if (!evidenceMatch) process.exit(1);

let data;
try {
  data = JSON.parse(evidenceMatch[1]);
  report('evidence JSON parses', true);
} catch (error) {
  report('evidence JSON parses', false, error.message);
  process.exit(1);
}

const evidenceDigest = crypto.createHash('sha256').update(evidenceMatch[1].trim()).digest('hex');
const pinnedEvidenceDigest = '515f1e02b7d876d7a7299e60db3cd8e1b648fe78b82e9203f940e6418c7c1212';
report('pinned evidence record has not drifted', evidenceDigest === pinnedEvidenceDigest, evidenceDigest);

const sourceAnchors = {
  umich: { black: [88, 749, 11.7], white: [99, 2778, 3.6] },
  eicu: { black: [160, 939, 17.0], white: [546, 8795, 6.2] }
};

for (const [cohort, groups] of Object.entries(sourceAnchors)) {
  for (const [group, [events, pairs, printedRate]] of Object.entries(groups)) {
    const actual = data.headline[cohort][group];
    report(`${cohort} ${group} source counts`, actual.events === events && actual.pairs === pairs,
      `${actual.events}/${actual.pairs}`);
    report(`${cohort} ${group} exact rate`, close(rate(events, pairs), rate(actual.events, actual.pairs)),
      `${rate(actual.events, actual.pairs).toFixed(8)}%`);
    report(`${cohort} ${group} published rounded anchor`, rate(actual.events, actual.pairs).toFixed(1) === printedRate.toFixed(1),
      `${rate(actual.events, actual.pairs).toFixed(1)}% vs ${printedRate.toFixed(1)}%`);
  }
}

const u = data.headline.umich;
const directRiskRatio = (u.black.events / u.black.pairs) / (u.white.events / u.white.pairs);
const crossProductRiskRatio = (u.black.events * u.white.pairs) / (u.black.pairs * u.white.events);
const riskDifference = 100 * (u.black.events / u.black.pairs - u.white.events / u.white.pairs);
report('independent route: direct and cross-product risk ratios agree', close(directRiskRatio, crossProductRiskRatio),
  `${directRiskRatio.toFixed(9)} vs ${crossProductRiskRatio.toFixed(9)}`);
report('University of Michigan risk difference', close(riskDifference, 8.18528376207874, 1e-12),
  `${riskDifference.toFixed(8)} points`);

const poison = { events: 44, pairs: 749 };
const poisonRate = rate(poison.events, poison.pairs);
const poisonRejected = poisonRate.toFixed(1) !== sourceAnchors.umich.black[2].toFixed(1);
report('control on the control rejects 44/749', poisonRejected,
  `${poisonRate.toFixed(1)}% does not match published 11.7%`);

const expectedWilson = {
  '88/749': [9.63572498120062, 14.2526467559616],
  '99/2778': [2.93595464815623, 4.31972806217494],
  '160/939': [14.7700097106551, 19.5773928647085],
  '546/8795': [5.72262819790180, 6.73175670658381]
};
for (const [key, expected] of Object.entries(expectedWilson)) {
  const [events, pairs] = key.split('/').map(Number);
  const actual = wilson(events, pairs);
  report(`Wilson interval ${key}`, close(actual[0], expected[0], 1e-8) && close(actual[1], expected[1], 1e-8),
    `${actual[0].toFixed(3)}% to ${actual[1].toFixed(3)}%`);
}

const expectedBins = {
  92: { black: 82, white: 296 },
  93: { black: 118, white: 411 },
  94: { black: 124, white: 530 },
  95: { black: 176, white: 625 },
  96: { black: 213, white: 770 }
};
report('Figure 1 exact-display bin counts match transcription',
  JSON.stringify(data.headline.umich.figureBins) === JSON.stringify(expectedBins));
const blackFigureTotal = Object.values(expectedBins).reduce((sum, bin) => sum + bin.black, 0);
const whiteFigureTotal = Object.values(expectedBins).reduce((sum, bin) => sum + bin.white, 0);
report('Figure 1/text denominator gap remains exposed', blackFigureTotal === 713 && whiteFigureTotal === 2632 && 749 - blackFigureTotal === 36 && 2778 - whiteFigureTotal === 146,
  `figure ${blackFigureTotal}/${whiteFigureTotal}; gaps ${749 - blackFigureTotal}/${2778 - whiteFigureTotal}`);

const aggregateAnchors = {
  'sjoding-um': ['Black 88/749; White 99/2778'],
  'sjoding-eicu': ['Black 160/939; White 546/8795'],
  khanna: ['dark +0.20; light +0.12 points', 'dark 1.71; light 1.64 points', 'one dark-group observation reported'],
  gudelunas: ['dark 21.1%; medium 8.2%; light 1.1%'],
  fawzy: ['dark +1.05; lighter +0.34 points', 'dark 4.15; lighter 1.97 points', 'dark 2.1%; lighter 0.4%'],
  equiox: ['overall -1.70; dark -1.05; light -2.01 points', 'overall 3.87; dark 4.49 points', 'ear ARMS 4.90; finger ARMS 2.70 points', '2 instances in 1,760 total pairs']
};
report('six evidence records present', data.records.length === 6 && new Set(data.records.map(record => record.id)).size === 6);
for (const record of data.records) {
  const values = record.metrics.map(metric => metric.value);
  report(`${record.id} displayed aggregate values match source anchor`,
    JSON.stringify(values) === JSON.stringify(aggregateAnchors[record.id]), values.join(' | '));
}

const text = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ');

function shows(label, computed, decimals) {
  const rendered = computed.toFixed(decimals);
  report(`page displays ${label} as ${rendered}`, text.includes(rendered), JSON.stringify({ computed, rendered }));
}

const khannaArms = data.records.find(record => record.id === 'khanna').metrics.find(metric => metric.kind === 'arms').value;
const khannaBias = data.records.find(record => record.id === 'khanna').metrics.find(metric => metric.kind === 'bias').value;
const gudelunasMissedDiagnosis = data.records.find(record => record.id === 'gudelunas').metrics.find(metric => metric.kind === 'threshold').value;
const khannaLightArms = Number(khannaArms.match(/light ([0-9.]+) points/)[1]);
const khannaBiasGroups = khannaBias.match(/dark \+([0-9.]+); light \+([0-9.]+) points/);
const khannaMeanBiasDifference = Number(khannaBiasGroups[1]) - Number(khannaBiasGroups[2]);
const gudelunasDarkLowPerfusion = Number(gudelunasMissedDiagnosis.match(/dark ([0-9.]+)%/)[1]);
shows('Khanna light-group whole-range ARMS', khannaLightArms, 2);
const khannaMeanBiasRendered = khannaMeanBiasDifference.toFixed(2);
const khannaMeanBiasOccurrences = text.split(khannaMeanBiasRendered).length - 1;
report(`page displays Khanna whole-range mean-bias difference as ${khannaMeanBiasRendered} exactly once`,
  khannaMeanBiasOccurrences === 1,
  JSON.stringify({ computed: khannaMeanBiasDifference, rendered: khannaMeanBiasRendered, occurrences: khannaMeanBiasOccurrences }));
shows('Gudelunas dark-group low-perfusion missed-diagnosis frequency', gudelunasDarkLowPerfusion, 1);

function matches(record, selection) {
  return (selection.design === 'all' || record.design === selection.design) &&
    (selection.pigment === 'all' || record.pigment === selection.pigment) &&
    (selection.perfusion === 'all' || record.perfusion === selection.perfusion) &&
    (selection.device === 'all' || record.device === selection.device) &&
    (selection.metric === 'all' || record.metrics.some(metric => metric.kind === selection.metric));
}

const filterOptions = {
  design: ['all', 'retrospective', 'laboratory', 'prospective'],
  pigment: ['all', 'race', 'category', 'objective'],
  perfusion: ['all', 'unreported', 'excluded', 'varied', 'clinical'],
  device: ['all', 'unreported', 'single', 'two', 'routine'],
  metric: ['all', 'threshold', 'bias', 'arms', 'probe']
};
let filterStates = 0;
let refusalStates = 0;
for (const design of filterOptions.design) {
  for (const pigment of filterOptions.pigment) {
    for (const perfusion of filterOptions.perfusion) {
      for (const device of filterOptions.device) {
        for (const metric of filterOptions.metric) {
          filterStates += 1;
          if (!data.records.some(record => matches(record, { design, pigment, perfusion, device, metric }))) refusalStates += 1;
        }
      }
    }
  }
}
report('all filter states swept', filterStates === 2000, `${filterStates} states`);
report('refusal path has reachable tests', refusalStates === 1778 && html.includes('No compatible source record.') && html.includes('0 source records. Refusal shown.'),
  `${refusalStates} explicit empty states`);

const jsonLdMatches = [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
report('one JSON-LD block exists', jsonLdMatches.length === 1);
let jsonLd = null;
try {
  jsonLd = JSON.parse(jsonLdMatches[0][1]);
  report('JSON-LD parses', true);
} catch (error) {
  report('JSON-LD parses', false, error.message);
}
if (jsonLd) {
  report('JSON-LD has honest Article fields', jsonLd['@type'] === 'Article' && jsonLd.name === 'Pulse Oximeter Accuracy, Skin Pigmentation, and Bias' && jsonLd.headline === 'The Number Under the Fingernail' && jsonLd.datePublished === '2026-08-25' && jsonLd.dateModified === '2026-08-25');
}

const executableInlineScripts = [...html.matchAll(/<script(?![^>]*\bsrc=)(?![^>]*type="application\/(?:ld\+json|json)")[^>]*>([\s\S]*?)<\/script>/g)].map(match => match[1]);
let inlineSyntaxOk = true;
for (const [index, script] of executableInlineScripts.entries()) {
  try { new vm.Script(script, { filename: `inline-${index + 1}.js` }); }
  catch (error) { inlineSyntaxOk = false; console.error(error.message); }
}
report('every executable inline script parses', inlineSyntaxOk && executableInlineScripts.length === 1,
  `${executableInlineScripts.length} script checked`);
report('load-bearing closing tags present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));

const descriptionMatch = html.match(/<meta name="description" content="([^"]+)"/);
const frontmatterDekMatch = markdown.match(/^dek: "([^"]+)"$/m);
const seoTitleMatch = markdown.match(/^seoTitle: "([^"]+)"$/m);
report('meta description equals frontmatter dek', Boolean(descriptionMatch && frontmatterDekMatch && descriptionMatch[1] === frontmatterDekMatch[1]));
report('SEO title equals page title', Boolean(seoTitleMatch && html.includes(`<title>${seoTitleMatch[1]}</title>`)));
report('share surface stays within verified scope', html.includes('race, measured pigment, setting, perfusion, device, and error metric') && html.includes('aggregate results remain aggregates'));
report('frontmatter publish fields', markdown.includes('date: 2026-08-25') && markdown.includes('seam: "life"') && markdown.includes('draft: false') && markdown.includes('href: "/strata/the-number-under-the-fingernail/"'));
const plainMatch = markdown.match(/^plain: "([^"]+)"$/m);
const forbiddenDash = String.fromCodePoint(0x2014);
report('plain placard shape', Boolean(plainMatch && plainMatch[1].length >= 90 && plainMatch[1].length <= 420 && (plainMatch[1].match(/[.!?](?:\s|$)/g) || []).length <= 3 && !plainMatch[1].includes(forbiddenDash)),
  plainMatch ? `${plainMatch[1].length} characters` : 'missing');

const relatedSlugs = [...markdown.matchAll(/^  - to: ([a-z0-9-]+)$/gm)].map(match => match[1]);
report('frontmatter has 2 to 4 object-shaped related edges', relatedSlugs.length >= 2 && relatedSlugs.length <= 4 && relatedSlugs.every(slug => markdown.includes(`  - to: ${slug}\n    note: "`)));
for (const slug of relatedSlugs) {
  report(`related slug exists: ${slug}`, fs.existsSync(path.join(root, 'src', 'content', 'strata', `${slug}.md`)));
}

const allAuthored = html + markdown + readme + fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
report('no em dash in authored files', !allAuthored.includes(forbiddenDash));
report('zero third-party runtime requests', !/<(?:script|img|link)[^>]+(?:src|href)="https?:\/\//i.test(html.replace(/<link rel="canonical"[^>]+>/g, '').replace(/<meta[^>]+>/g, '')));
report('accessible changing readouts', html.includes('role="status" aria-live="polite"') && html.includes(':focus-visible') && html.includes('prefers-reduced-motion:reduce'));

const surfaceAnchors = [
  '11.75%', '3.56%', '1.71 points', '1.64', '21.1%', '8.2%', '1.1%', '12-person', '631 ICU participants',
  'short by 36 and 146', '2026-08-25', 'SpO2 minus SaO2', 'aggregate transcription'
];
for (const anchor of surfaceAnchors) report(`rendered surface contains ${anchor}`, html.includes(anchor));

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