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

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pagePath = path.join(root, 'public/strata/challenger-o-ring-information-set/index.html');
const modelPath = path.join(root, 'public/strata/challenger-o-ring-information-set/model.js');
const kitPath = path.join(root, 'public/_kit/hindsight.js');
const frontmatterPath = path.join(root, 'src/content/strata/challenger-o-ring-information-set.md');
const readmePath = path.join(here, 'README.md');
const html = fs.readFileSync(pagePath, 'utf8');
const modelSource = fs.readFileSync(modelPath, 'utf8');
const kitSource = fs.readFileSync(kitPath, 'utf8');
const frontmatter = fs.readFileSync(frontmatterPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');

const context = { window: {} };
vm.runInNewContext(kitSource, context, { filename: kitPath });
vm.runInNewContext(modelSource, context, { filename: modelPath });
const model = context.window.ChallengerSelectionModel;
const hindsight = context.window.AW.hindsight;

let passed = 0;
let total = 0;

function check(condition, label) {
  total += 1;
  if (!condition) {
    console.error('FAIL ' + label);
    process.exitCode = 1;
    return;
  }
  passed += 1;
  console.log('ok ' + passed + ' ' + label);
}

function equal(actual, expected, label) {
  check(JSON.stringify(actual) === JSON.stringify(expected), label + ' | got ' + JSON.stringify(actual));
}

function close(actual, expected, tolerance, label) {
  check(Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance,
    label + ' | got ' + actual + ', expected ' + expected + ' within ' + tolerance);
}

function extractLedger(source) {
  const match = source.match(/<script id="challenger-ledger" type="application\/json">([\s\S]*?)<\/script>/);
  if (!match) throw new Error('shipped page has no Challenger ledger');
  return JSON.parse(match[1]);
}

function logistic(x) {
  if (x >= 0) return 1 / (1 + Math.exp(-x));
  const e = Math.exp(x);
  return e / (1 + e);
}

function log1pExp(x) {
  return x > 35 ? x + Math.log1p(Math.exp(-x)) : Math.log1p(Math.exp(x));
}

function independentLogLik(rows, intercept, slope, binary = false) {
  return rows.reduce((sum, row) => {
    const y = binary ? Number(row.distress > 0) : row.distress;
    const trials = binary ? 1 : 6;
    const eta = intercept + slope * row.temp;
    return sum + y * eta - trials * log1pExp(eta);
  }, 0);
}

function independentFit(rows, binary = false) {
  let intercept = 0;
  let slope = 0;
  for (let iter = 0; iter < 100; iter += 1) {
    let g0 = 0, g1 = 0, h00 = 0, h01 = 0, h11 = 0;
    for (const row of rows) {
      const y = binary ? Number(row.distress > 0) : row.distress;
      const trials = binary ? 1 : 6;
      const p = logistic(intercept + slope * row.temp);
      const weight = trials * p * (1 - p);
      g0 += y - trials * p;
      g1 += (y - trials * p) * row.temp;
      h00 -= weight;
      h01 -= weight * row.temp;
      h11 -= weight * row.temp * row.temp;
    }
    const determinant = h00 * h11 - h01 * h01;
    const deltaIntercept = (g0 * h11 - g1 * h01) / determinant;
    const deltaSlope = (h00 * g1 - h01 * g0) / determinant;
    intercept -= deltaIntercept;
    slope -= deltaSlope;
    if (Math.max(Math.abs(deltaIntercept), Math.abs(deltaSlope)) < 1e-13) break;
  }
  return { intercept, slope, logLikelihood: independentLogLik(rows, intercept, slope, binary) };
}

function independentDeviance(rows, fit) {
  let value = 0;
  for (const row of rows) {
    const p = logistic(fit.intercept + fit.slope * row.temp);
    if (row.distress > 0) value += 2 * row.distress * Math.log(row.distress / (6 * p));
    if (row.distress < 6) value += 2 * (6 - row.distress) * Math.log((6 - row.distress) / (6 * (1 - p)));
  }
  return value;
}

function independentProfileLogLik(rows, targetTemp, eta) {
  function score(slope) {
    return rows.reduce((sum, row) => {
      const x = row.temp - targetTemp;
      return sum + (row.distress - 6 * logistic(eta + slope * x)) * x;
    }, 0);
  }
  let lo = -1;
  let hi = 1;
  while (score(lo) < 0) lo *= 2;
  while (score(hi) > 0) hi *= 2;
  for (let i = 0; i < 150; i += 1) {
    const mid = (lo + hi) / 2;
    if (score(mid) > 0) lo = mid;
    else hi = mid;
  }
  const slope = (lo + hi) / 2;
  return independentLogLik(rows, eta - slope * targetTemp, slope, false);
}

function independentProfile95(rows, targetTemp) {
  const fit = independentFit(rows);
  const etaHat = fit.intercept + fit.slope * targetTemp;
  const threshold = 3.841458820694124;
  const loss = eta => 2 * (fit.logLikelihood - independentProfileLogLik(rows, targetTemp, eta));
  function solve(direction) {
    let step = 1;
    let outside = etaHat + direction * step;
    while (loss(outside) < threshold) {
      step *= 1.5;
      outside = etaHat + direction * step;
    }
    let lo = Math.min(etaHat, outside);
    let hi = Math.max(etaHat, outside);
    for (let i = 0; i < 120; i += 1) {
      const mid = (lo + hi) / 2;
      if (direction < 0) {
        if (loss(mid) >= threshold) lo = mid;
        else hi = mid;
      } else if (loss(mid) < threshold) lo = mid;
      else hi = mid;
    }
    return logistic((lo + hi) / 2);
  }
  return { estimate: logistic(etaHat), lower: solve(-1), upper: solve(1) };
}

function externalRequests(source) {
  const violations = [];
  const assetPattern = /<(?:script|img|source|iframe|audio|video)\b[^>]*?\b(?:src|href|srcset)\s*=\s*["']([^"']+)["'][^>]*>/gi;
  let match;
  while ((match = assetPattern.exec(source))) {
    if (/^(?:https?:)?\/\//i.test(match[1])) violations.push(match[1]);
  }
  const linkPattern = /<link\b([^>]+)>/gi;
  while ((match = linkPattern.exec(source))) {
    const rel = match[1].match(/\brel\s*=\s*["']([^"']+)["']/i);
    const href = match[1].match(/\bhref\s*=\s*["']([^"']+)["']/i);
    if (rel && href && /(?:stylesheet|icon|preload|prefetch|manifest|apple-touch-icon)/i.test(rel[1]) && /^(?:https?:)?\/\//i.test(href[1])) {
      violations.push(href[1]);
    }
  }
  const cssPattern = /url\(\s*["']?((?:https?:)?\/\/[^)'"\s]+)/gi;
  while ((match = cssPattern.exec(source))) violations.push(match[1]);
  return violations;
}

function dynamicNetworkCalls(source) {
  const patterns = [/\bfetch\s*\(/, /\bXMLHttpRequest\b/, /\bWebSocket\s*\(/, /\bEventSource\s*\(/, /\bsendBeacon\s*\(/];
  return patterns.filter(pattern => pattern.test(source)).map(String);
}

function visibleClaim(name) {
  const match = html.match(new RegExp('data-claim="' + name + '"[^>]*>([^<]+)<'));
  return match ? match[1].trim() : null;
}

const records = extractLedger(html);
const eligible = records.filter(row => row.kind === 'flight' && row.id !== 'STS-4' && row.id !== 'STS-51-L');
const rows = eligible.map(row => ({ id: row.id, temp: row.temp, distress: row.distress }));
const incidentRows = rows.filter(row => row.distress > 0);
const fit = independentFit(rows);
const binaryFit = independentFit(rows, true);
const profile31 = independentProfile95(rows, 31);
const p31 = logistic(fit.intercept + fit.slope * 31);
const pageResult = model.runAt(records, model.CUTOFF);

check(fs.existsSync(pagePath) && fs.existsSync(modelPath) && fs.existsSync(frontmatterPath) && fs.existsSync(readmePath), 'all owned entry and research files exist');
equal(records.length, 36, 'complete Commission Figure 2 archive has 36 rows');
equal(new Set(records.map(row => row.id)).size, 36, 'all archive identifiers are unique');
equal(records.filter(row => row.kind === 'flight').length, 25, 'archive has 25 Shuttle flights through STS-51-L');
equal(records.filter(row => row.kind === 'static-motor').length, 11, 'archive has 11 excluded development or qualification motors');
equal(records.filter(row => row.kind === 'static-motor').map(row => row.id), ['DM-1','DM-2','DM-3','DM-4','QM-1','QM-2','QM-3','DM-5','QM-4','DM-6','DM-7'], 'static-motor identities match Figure 2');
check(records.every(row => !Object.hasOwn(row, 'launchDate') && !Object.hasOwn(row, 'date')), 'shipped ledger contains no launch-date field');
check(records.filter(row => row.id !== 'STS-51-L').every(row => row.eligibleBy === '1986-01-19'), 'all prior records use the documented inspection ceiling, not event dates');
equal(rows.length, 23, 'eligible model ledger has 23 usable flights');
equal(incidentRows.length, 7, 'incident-only selection has seven flights');
equal(rows.filter(row => row.distress === 0).length, 16, 'selection hides exactly sixteen zero-incident flights');
equal(rows.reduce((sum, row) => sum + row.distress, 0), 9, 'eligible ledger has nine distressed primary rings');
equal([Math.min(...rows.map(row => row.temp)), Math.max(...rows.map(row => row.temp))], [53, 81], 'usable observations span 53 F to 81 F');
equal([records.find(row => row.id === 'STS-3').temp, records.find(row => row.id === 'STS-9').temp, records.find(row => row.id === 'STS-41-G').temp], [69, 70, 78], 'three known HTML transcription conflicts use cross-checked temperatures');
equal(records.find(row => row.id === 'STS-51-C').distress, 2, 'STS-51-C counts two primary distressed rings, not its secondary-ring note');

close(fit.intercept, 5.084977233038443, 1e-10, 'independent grouped-binomial intercept reproduces anchor');
close(fit.slope, -0.11560116667193518, 1e-12, 'independent grouped-binomial slope reproduces anchor');
close(independentDeviance(rows, fit), 18.086326742497448, 1e-10, 'independent deviance reproduces 18.086327 on 21 df');
close(p31, 0.8177744062827564, 1e-12, 'independent per-ring probability at 31 F is 0.817774');
close(6 * p31, 4.906646437696539, 1e-12, 'independent expected distressed rings at 31 F is 4.906646');
close(1 - Math.pow(1 - p31, 6), 0.999963385235651, 1e-14, 'six-independent-ring flight probability is 0.999963');
close(binaryFit.intercept, 15.042901647702438, 1e-10, 'independent flight-binary intercept reproduces 15.042902');
close(binaryFit.slope, -0.23216274421859642, 1e-12, 'independent flight-binary slope reproduces -0.232163');
close(logistic(binaryFit.intercept + binaryFit.slope * 31), 0.9996087828849319, 1e-13, 'flight-binary probability at 31 F is 0.999609');
close(profile31.lower, 0.14185158052563296, 1e-10, 'independent 95% profile lower endpoint is 0.141852');
close(profile31.upper, 0.9905216459968065, 1e-10, 'independent 95% profile upper endpoint is 0.990522');

close(pageResult.value.intercept, fit.intercept, 1e-12, 'page pipeline fit matches independent intercept');
close(pageResult.value.slope, fit.slope, 1e-12, 'page pipeline fit matches independent slope');
close(pageResult.value.deviance, independentDeviance(rows, fit), 1e-10, 'page pipeline deviance matches independent computation');
close(pageResult.value.flight31Binary, logistic(binaryFit.intercept + binaryFit.slope * 31), 1e-12, 'page flight-binary result matches independent computation');
const pageProfile = model.profileInterval(pageResult.rows, 31);
close(pageProfile.lower, profile31.lower, 1e-10, 'page profile lower endpoint matches independent profile');
close(pageProfile.upper, profile31.upper, 1e-10, 'page profile upper endpoint matches independent profile');
const incidentFit = independentFit(incidentRows);
close(incidentFit.slope, 0.0014158837533996466, 1e-12, 'incident-only descriptive refit is nearly flat and positive');
close(logistic(incidentFit.intercept + incidentFit.slope * 31), 0.2065848641138992, 1e-12, 'incident-only descriptive p31 is 0.206585');

equal(pageResult.gate.counts, { used:23, later:1, excluded:12, undated:0 }, 'page firewall exposes all four balanced buckets');
equal(pageResult.gate.total, 36, 'firewall buckets balance to the full 36-row archive');
equal(hindsight.violations(pageResult.used, model.CUTOFF, { dateField:'eligibleBy' }).length, 0, 'no used row is dated after the cutoff');
check(pageResult.used.some(row => row.id === 'STS-61-C'), 'STS-61-C is included in the eligible fit');
check(pageResult.gate.later.some(item => item.record.id === 'STS-51-L'), 'STS-51-L outcome is visibly later than the cutoff');
check(pageResult.gate.excluded.some(item => item.record.id === 'STS-4' && /lost at sea/.test(item.reason)), 'STS-4 is excluded with its documented missing-outcome reason');
equal(pageResult.gate.excluded.filter(item => item.record.kind === 'static-motor').length, 11, 'all eleven motors are visibly excluded for population scope');
const audit = model.audit(records);
check(audit.pass && audit.plantReportedLater, 'real page pipeline rejects and reports the planted future flight');
check(!audit.enteredFit && !audit.answerMoved, 'planted future flight neither enters nor changes the fit');
const leakyRunner = input => ({ used:input, value:{ n:input.length } });
const caughtLeak = hindsight.auditFirewall(leakyRunner, records, model.CUTOFF, { id:'LEAK', kind:'flight', eligibleBy:'2099-01-01', temp:31, distress:6 }, { dateField:'eligibleBy', idField:'id' });
check(!caughtLeak.pass && caughtLeak.enteredFit && caughtLeak.answerMoved, 'firewall negative control fails under a leaky runner');

check(model.profileInterval(rows, 'not-a-number').refused, 'profile control refuses nonnumeric temperature');
check(model.profileInterval(rows, 30).refused, 'profile control refuses a temperature outside the displayed domain');
let badSelectionRefused = false;
try { model.select(rows, 'future'); } catch { badSelectionRefused = true; }
check(badSelectionRefused, 'selection control refuses an unknown mode');
let badCutoffRefused = false;
try { model.runAt(records, 'January sometime'); } catch { badCutoffRefused = true; }
check(badCutoffRefused, 'firewall refuses an unparseable cutoff');
let badOutcomeRefused = false;
try { model.fitLogistic([{ temp:60, distress:7 }, { temp:70, distress:0 }], false); } catch { badOutcomeRefused = true; }
check(badOutcomeRefused, 'fit refuses an outcome above six rings');

equal(Number(visibleClaim('intercept')), Number(fit.intercept.toFixed(6)), 'visible intercept fallback matches independent fit');
equal(Number(visibleClaim('slope')), Number(fit.slope.toFixed(6)), 'visible slope fallback matches independent fit');
equal(Number(visibleClaim('deviance')), Number(independentDeviance(rows, fit).toFixed(6)), 'visible deviance fallback matches independent fit');
equal(Number(visibleClaim('p31')), Number(p31.toFixed(6)), 'visible p31 fallback matches independent fit');
equal(Number(visibleClaim('expected31')), Number((6 * p31).toFixed(6)), 'visible expected-ring fallback matches independent fit');
equal(visibleClaim('profile31'), profile31.lower.toFixed(6) + ' to ' + profile31.upper.toFixed(6), 'visible profile interval fallback matches independent profile');

equal(externalRequests(html), [], 'request-bearing HTML and CSS assets are local');
check(externalRequests(html + '<script src="https://example.invalid/tracker.js"></script>').includes('https://example.invalid/tracker.js'), 'external-request negative control catches a planted remote script');
equal(dynamicNetworkCalls(html + modelSource), [], 'page code contains no dynamic network primitive');
check(dynamicNetworkCalls('const endpoint="https://example.invalid/x"; fetch(endpoint);').length === 1, 'network negative control catches a variable-based fetch');
check(html.includes('<script src="/_kit/hindsight.js"></script>'), 'page loads the shared hindsight kit');
check(html.includes('role="status"') && html.includes('aria-live="polite"'), 'page carries accessible live readouts');
check(html.includes(':focus-visible'), 'page defines visible keyboard focus');
check(html.includes('prefers-reduced-motion: reduce'), 'page includes a reduced-motion guard');
check(html.includes('<link rel="stylesheet" href="/fonts/fonts.css" />'), 'page uses self-hosted fonts');
check(html.includes('<link rel="canonical" href="https://artwaste.land/strata/challenger-o-ring-information-set/" />'), 'canonical URL matches the slug');
check(/<script type="application\/ld\+json">[\s\S]*?"@type":"Article"/.test(html), 'page includes honest Article JSON-LD');
check(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'load-bearing closing tags are present');
check(!/[\u2013\u2014]/.test(html + modelSource + frontmatter + readme), 'owned prose contains no en dash or em dash');
check(/never treats a launch date as an observation date/.test(html), 'page explicitly separates launch dates from availability dates');
check(/This page makes no release-by-release time series/.test(html), 'page explicitly refuses the invalid time-series construction');
check(/not a claim that the seven points were the only engineering evidence/i.test(html), 'page limits the incident-only reconstruction');
check(/does not identify the unchosen branch/i.test(html), 'page bounds the delay counterfactual');
check(/asked to quantify the timing concern and could not/i.test(html), 'page names Boisjoly evidence for the unavailable quantity');

check(frontmatter.includes('seam: "mind"'), 'frontmatter declares the specified seam');
check(frontmatter.includes('href: "/strata/challenger-o-ring-information-set/"'), 'frontmatter href matches the page');
check(frontmatter.includes('date: 2026-08-14'), 'frontmatter date is correct');
check(frontmatter.includes('draft: false'), 'frontmatter is published');
check(/relates:\s*[\s\S]*?- to:/.test(frontmatter), 'frontmatter declares constellation edges');
check(/Work of the US Gov\. Public Use Permitted/.test(readme), 'research README records the government-data licence');

console.log('PASS ' + passed + '/' + total);
if (passed !== total) process.exitCode = 1;
