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/titanic-ice-warning-firewall/index.html');
const modelPath = path.join(root, 'public/strata/titanic-ice-warning-firewall/model.js');
const kitPath = path.join(root, 'public/_kit/hindsight.js');
const frontmatterPath = path.join(root, 'src/content/strata/titanic-ice-warning-firewall.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 context = { window: {} };
vm.runInNewContext(kitSource, context, { filename: kitPath });
vm.runInNewContext(modelSource, context, { filename: modelPath });
const model = context.window.TitanicWarningModel;
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 extractLedger(source) {
  const match = source.match(/<script id="warning-ledger" type="application\/json">([\s\S]*?)<\/script>/);
  if (!match) throw new Error('shipped page has no warning ledger');
  return JSON.parse(match[1]);
}

function independentSummary(rows) {
  const bridge = rows.filter(row => row.bridgeDelivered);
  const areaRows = rows.filter(row => row.geometry && row.geometry.type === 'area');
  const wreck = { lat: 41 + 46 / 60, lon: -(50 + 14 / 60) };
  const inRect = row => wreck.lat >= row.geometry.latMin && wreck.lat <= row.geometry.latMax &&
    wreck.lon >= row.geometry.lonMin && wreck.lon <= row.geometry.lonMax;
  const containing = areaRows.filter(inRect);
  return {
    total: rows.length,
    formal: rows.filter(row => row.formal).length,
    bridge: bridge.length,
    wirelessOnly: rows.length - bridge.length,
    identified: rows.filter(row => row.identifiedRecipient).length,
    areaRows: areaRows.length,
    containing: containing.map(row => row.id),
    historicalContaining: containing.filter(row => row.bridgeDelivered).length
  };
}

function externalRequests(source) {
  const violations = [];
  const attrPattern = /<(?:script|img|source|iframe|audio|video)\b[^>]*?\b(?:src|href|srcset)\s*=\s*["']([^"']+)["'][^>]*>/gi;
  let match;
  while ((match = attrPattern.exec(source))) {
    if (/^(?:https?:)?\/\//i.test(match[1])) violations.push(match[1]);
  }
  const linkPattern = /<link\b([^>]+)>/gi;
  while ((match = linkPattern.exec(source))) {
    const attrs = match[1];
    const rel = attrs.match(/\brel\s*=\s*["']([^"']+)["']/i);
    const href = attrs.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*\(/,
    /\bimport\s*\(\s*["']https?:\/\//
  ];
  return patterns.filter(pattern => pattern.test(source)).map(pattern => String(pattern));
}

const records = extractLedger(html);
const independent = independentSummary(records);
const shipped = model.runAt(records, model.FINAL_CUTOFF);
const summary = shipped.value;

check(fs.existsSync(pagePath) && fs.existsSync(modelPath) && fs.existsSync(frontmatterPath), 'all three shipped entry files exist');
equal(records.length, 6, 'complete ledger has six rows');
equal(new Set(records.map(row => row.id)).size, 6, 'all ledger identifiers are unique');
equal(independent.formal, 5, 'published anchor has five formal messages');
equal(independent.bridge, 3, 'historical bridge handoff count is three');
equal(independent.wirelessOnly, 3, 'wireless-only count is three');
equal(independent.identified, 2, 'identified officer recipient count is two');
equal(records.filter(row => row.bridgeDelivered).map(row => row.id), ['caronia', 'baltic', 'californian-antillian'], 'bridge-side identities match the inquiry ledger');
equal(records.filter(row => !row.bridgeDelivered).map(row => row.id), ['amerika', 'mesaba', 'californian-final'], 'wireless-only identities match the inquiry ledger');
equal(records.filter(row => row.formal).map(row => row.id), ['caronia', 'baltic', 'amerika', 'californian-antillian', 'mesaba'], 'formal sequence ends with Mesaba');

equal(summary.received, independent.total, 'page model recomputes complete received count');
equal(summary.formal, independent.formal, 'page model recomputes formal anchor');
equal(summary.bridge, independent.bridge, 'page model recomputes historical handoff score');
equal(summary.wirelessOnly, independent.wirelessOnly, 'page model recomputes wireless-only balance');
equal(summary.identifiedRecipient, independent.identified, 'page model recomputes identified recipients');
equal(summary.frozenBridge, 6, 'frozen universal-delivery rule scores six of six');

equal(independent.areaRows, 1, 'only one message defines a bounded warning area');
equal(independent.containing, ['mesaba'], 'Mesaba area contains inquiry wreck position');
equal(summary.historicalAreaAtWreck, 0, 'historical bridge set had no area containing wreck point');
equal(summary.frozenAreaAtWreck, 1, 'frozen rule adds the one area containing wreck point');
check(model.contains(records.find(row => row.id === 'mesaba').geometry, model.WRECK), 'model containment uses the shipped Mesaba bounds');

equal(shipped.gate.counts, { used: 6, later: 0, excluded: 0, undated: 0 }, 'final firewall exposes all four balanced buckets');
equal(shipped.gate.total, 6, 'final firewall total equals complete archive');
equal(hindsight.violations(shipped.used, model.FINAL_CUTOFF, { dateField: 'gateAt' }).length, 0, 'no final used row is dated after the cutoff');
const beforeMesaba = model.runAt(records, '1912-04-14T21:39:59');
equal(beforeMesaba.gate.counts, { used: 4, later: 2, excluded: 0, undated: 0 }, 'pre-Mesaba cutoff refuses both later rows');
equal(beforeMesaba.value.bridge, 3, 'later wireless records cannot change the earlier bridge count');

const trajectory = model.trajectory(records);
equal(trajectory.total, 6, 'complete replay reaches all six release steps');
equal(trajectory.nOk, 6, 'every declared release step produces a result');
equal(trajectory.rows.map(row => row.nUsed), [1, 2, 3, 4, 5, 6], 'trajectory advances exactly one release at a time');
equal(trajectory.rows.map(row => row.value.bridge), [1, 2, 2, 3, 3, 3], 'complete bridge trajectory includes both plateaus');
equal(trajectory.rows.map(row => row.value.wirelessOnly), [0, 0, 1, 1, 2, 3], 'complete wireless-only trajectory reaches three');

const audit = model.audit(records);
check(audit.pass, 'real page pipeline rejects the planted future message');
check(audit.plantReportedLater, 'planted future message is visible in the later bucket');
check(!audit.enteredFit && !audit.answerMoved, 'plant neither enters the fit nor changes its answer');
const leakyRunner = rows => ({ used: rows, value: independentSummary(rows) });
const caughtLeak = hindsight.auditFirewall(leakyRunner, records, model.FINAL_CUTOFF, {
  id: 'NEGATIVE-CONTROL', gateAt: '1912-04-15T00:01:00', formal: true, bridgeDelivered: true
}, { dateField: 'gateAt', idField: 'id' });
check(!caughtLeak.pass && caughtLeak.enteredFit && caughtLeak.answerMoved, 'negative control fails when a leaky pipeline is substituted');

const wreckProbe = model.probe(records, 41 + 46 / 60, -(50 + 14 / 60));
check(!wreckProbe.refused, 'wreck coordinate is inside probe domain');
equal(wreckProbe.covering, ['mesaba'], 'position probe reproduces Mesaba containment');
equal(wreckProbe.unscored, 5, 'position probe names five geometrically unscored rows');
check(model.probe(records, 'not-a-number', -50).refused, 'probe refuses nonnumeric input');
check(model.probe(records, 60, -50).refused, 'probe refuses an out-of-domain coordinate');
let badCutoffRefused = false;
try { model.runAt(records, '14 April sometime'); } catch { badCutoffRefused = true; }
check(badCutoffRefused, 'firewall refuses an unparseable cutoff');

equal(externalRequests(html), [], 'request-bearing HTML attributes use only local assets');
const requestNegative = externalRequests(html + '<script src="https://example.invalid/tracker.js"></script>');
check(requestNegative.includes('https://example.invalid/tracker.js'), 'external-request negative control catches a planted remote script');
equal(dynamicNetworkCalls(html + '\n' + 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/titanic-ice-warning-firewall/" />'), 'canonical URL matches the slug');
check(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'load-bearing closing tags are present');
check(!/[\u2013\u2014]/.test(html + modelSource + frontmatter), 'owned page prose contains no en dash or em dash');

check(frontmatter.includes('seam: "groundtruth"'), 'frontmatter declares the required seam');
check(frontmatter.includes('href: "/strata/titanic-ice-warning-firewall/"'), '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');

const claim = name => {
  const match = html.match(new RegExp('data-claim="' + name + '"[^>]*>([^<]+)<'));
  return match ? match[1].trim() : null;
};
equal(Number(claim('received')), independent.total, 'visible received fallback matches recomputation');
equal(Number(claim('bridge')), independent.bridge, 'visible bridge fallback matches recomputation');
equal(Number(claim('identified')), independent.identified, 'visible recipient fallback matches recomputation');
equal(Number(claim('formal')), independent.formal, 'visible formal anchor matches recomputation');
check(records.find(row => row.id === 'californian-final').approximatePlacement === true, 'final call carries an explicit approximation flag');
check(/no exact Titanic-(?:clock|time) conversion is claimed/i.test(html), 'page surfaces the incompatible clock basis');
check(html.includes('none of Titanic\'s message records survived') || html.includes('none of Titanic&#39;s message records survived'), 'page surfaces the lost original log');
check(html.includes('not a claim that Titanic would have avoided the collision'), 'page limits the collision counterfactual in headline apparatus');

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