import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';

const root = process.cwd();
const pagePath = path.join(root, 'public/strata/ego-depletion-warning-in-plain-sight/index.html');
const dataPath = path.join(root, 'public/strata/ego-depletion-warning-in-plain-sight/data.js');
const analysisPath = path.join(root, 'public/strata/ego-depletion-warning-in-plain-sight/analysis.js');
const kitPath = path.join(root, 'public/_kit/hindsight.js');
const contentPath = path.join(root, 'src/content/strata/ego-depletion-warning-in-plain-sight.md');
const readmePath = path.join(root, 'research/ego-depletion-warning-in-plain-sight/README.md');

const page = fs.readFileSync(pagePath, 'utf8');
const dataSource = fs.readFileSync(dataPath, 'utf8');
const analysisSource = fs.readFileSync(analysisPath, 'utf8');
const content = fs.readFileSync(contentPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');

let passed = 0;
let total = 0;
const failures = [];

function check(name, condition, detail = '') {
  total += 1;
  if (condition) {
    passed += 1;
    console.log(`ok ${total} - ${name}`);
  } else {
    failures.push(`${name}${detail ? `: ${detail}` : ''}`);
    console.error(`not ok ${total} - ${name}${detail ? `: ${detail}` : ''}`);
  }
}

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

function loadUmd(source, filename) {
  const context = { module: { exports: {} }, exports: {}, console };
  vm.runInNewContext(source, context, { filename });
  return context.module.exports;
}

function extractCsv(source) {
  const match = source.match(/const rawCsv = String\.raw`([\s\S]*?)`;\n\s*const restored/);
  if (!match) throw new Error('could not locate embedded CSV');
  return match[1];
}

function parseIndependent(csv) {
  const lines = csv.trim().split(/\r?\n/);
  const header = lines.shift();
  if (header !== 'Study;d;n1;n2;sd;EC;p-value(H0);significance') throw new Error('unexpected independent CSV header');
  const rawValues = new Map([
    ['Muraven, Gagne, & Rosman (2008) 1 (OUTLIER! d=3.02, set at d=1.90)', 3.02],
    ['Tyler & Burns (2009) 2 S2 (OUTLIER! d=2.60, set at d=1.90)', 2.60],
    ['Wright , Stewart & Barnett (2008) 2 S1 (OUTLIER! d=-0.57, set at d=-0.11)', -0.57],
  ]);
  return lines.map((line, index) => {
    const c = line.split(';');
    if (c.length !== 8) throw new Error(`bad CSV row ${index + 2}`);
    const label = c[0].trim();
    const nums = c.slice(1).map(Number);
    if (nums.some(v => !Number.isFinite(v))) throw new Error(`nonnumeric CSV row ${index + 2}`);
    const ym = label.match(/\b(?:19|20)\d{2}\b/);
    const year = ym ? Number(ym[0]) : (label.includes('(in press)') ? 2009 : NaN);
    if (!Number.isInteger(year)) throw new Error(`undated CSV row ${index + 2}`);
    return { id: `effect-${String(index + 1).padStart(3, '0')}`, label, adjustedD: nums[0], rawD: rawValues.get(label) ?? nums[0], n1: nums[1], n2: nums[2], year, releaseDate: String(year) };
  });
}

function rows(records, mode = 'adjusted') {
  return records.map(r => {
    const d = mode === 'raw' ? r.rawD : r.adjustedD;
    const v = (r.n1 + r.n2) / (r.n1 * r.n2) + d * d / (2 * (r.n1 + r.n2));
    return { d, v, se: Math.sqrt(v) };
  });
}

function weighted(input) {
  const sw = input.reduce((s, r) => s + 1 / r.v, 0);
  return { mean: input.reduce((s, r) => s + r.d / r.v, 0) / sw, sw };
}

function anchor(input) {
  const fit = weighted(input);
  const q = input.reduce((s, r) => s + (r.d - fit.mean) ** 2 / r.v, 0);
  const df = input.length - 1;
  const spreadSe = Math.sqrt((q / fit.sw) / input.length);
  return { mean: fit.mean, q, i2: 100 * (q - df) / q, lo: fit.mean - 1.96 * spreadSe, hi: fit.mean + 1.96 * spreadSe };
}

function regression(input, predictor) {
  let s = 0, sx = 0, sy = 0, sxx = 0, sxy = 0;
  input.forEach(r => {
    const w = 1 / r.v, x = predictor(r);
    s += w; sx += w * x; sy += w * r.d; sxx += w * x * x; sxy += w * x * r.d;
  });
  const det = s * sxx - sx * sx;
  return { intercept: (sxx * sy - sx * sxy) / det, slope: (s * sxy - sx * sy) / det };
}

function ranksAbsolute(input, center) {
  const sorted = input.map((r, i) => ({ i, a: Math.abs(r.d - center) })).sort((a, b) => a.a - b.a);
  const ranks = new Array(input.length);
  for (let start = 0; start < sorted.length;) {
    let end = start + 1;
    while (end < sorted.length && Math.abs(sorted[end].a - sorted[start].a) < 1e-12) end += 1;
    const rank = (start + 1 + end) / 2;
    for (let j = start; j < end; j += 1) ranks[sorted[j].i] = rank;
    start = end;
  }
  return ranks;
}

function trimFillIndependent(input) {
  const original = input.map(r => ({ ...r }));
  let working = original.slice(), k0 = 0;
  for (let iteration = 0; iteration < 100; iteration += 1) {
    const center = weighted(working).mean;
    const ranks = ranksAbsolute(original, center);
    const tPlus = original.reduce((s, r, i) => s + (r.d > center ? ranks[i] : 0), 0);
    const next = Math.max(0, Math.round((4 * tPlus - original.length * (original.length + 1)) / (2 * original.length - 1)));
    if (iteration > 0 && next === k0) break;
    k0 = Math.min(next, original.length - 2);
    working = original.slice().sort((a, b) => a.d - b.d).slice(0, original.length - k0);
  }
  const center = weighted(working).mean;
  const donors = original.slice().sort((a, b) => b.d - a.d).slice(0, k0);
  const filled = original.concat(donors.map(r => ({ d: 2 * center - r.d, v: r.v, se: r.se })));
  return { k0, mean: weighted(filled).mean };
}

function externalRequests(html) {
  const violations = [];
  const resourcePattern = /<(script|img|iframe|source|video|audio)\b[^>]*?\bsrc=["']([^"']+)["'][^>]*>/gi;
  let match;
  while ((match = resourcePattern.exec(html))) {
    if (/^https?:\/\//i.test(match[2]) || /^\/\//.test(match[2])) violations.push(`${match[1]}:${match[2]}`);
  }
  const stylePattern = /<link\b[^>]*?rel=["'](?:stylesheet|preload)["'][^>]*?href=["']([^"']+)["'][^>]*>/gi;
  while ((match = stylePattern.exec(html))) {
    if (/^https?:\/\//i.test(match[1]) || /^\/\//.test(match[1])) violations.push(`link:${match[1]}`);
  }
  const apiPatterns = [/(?:^|[^\w])fetch\s*\(/, /new\s+XMLHttpRequest\s*\(/, /new\s+WebSocket\s*\(/, /new\s+EventSource\s*\(/, /sendBeacon\s*\(/];
  apiPatterns.forEach(re => { if (re.test(html)) violations.push(`runtime:${re.source}`); });
  return violations;
}

const csv = extractCsv(dataSource);
const independent = parseIndependent(csv);
const adjustedRows = rows(independent, 'adjusted');
const rawRows = rows(independent, 'raw');
const independentAnchor = anchor(adjustedRows);
const independentTrim = trimFillIndependent(adjustedRows);
const rawPet = regression(rawRows, r => r.se);
const rawPeese = regression(rawRows, r => r.v);
const EgoData = loadUmd(dataSource, dataPath);
const EgoAudit = loadUmd(analysisSource, analysisPath);
const hindsight = loadUmd(fs.readFileSync(kitPath, 'utf8'), kitPath);
const shipped = EgoAudit.summarize(EgoData.records, 'adjusted');

check('embedded data has 198 effects', independent.length === 198, `got ${independent.length}`);
check('participant total is 10,782', independent.reduce((s, r) => s + r.n1 + r.n2, 0) === 10782);
check('all archive years resolve and end in 2009', independent.every(r => Number.isInteger(r.year)) && Math.max(...independent.map(r => r.year)) === 2009);
check('three adjusted outliers have raw sensitivity values', independent.filter(r => r.adjustedD !== r.rawD).length === 3);
check('independent fixed mean reproduces d=.62', close(independentAnchor.mean, 0.6225696452987998, 1e-12));
check('independent Q reproduces 301.79', close(independentAnchor.q, 301.7898187066513, 1e-9));
check('independent I2 reproduces 34.72%', close(independentAnchor.i2, 34.72278129054782, 1e-9));
check('independent Hagger-style interval rounds to [.57,.67]', independentAnchor.lo.toFixed(2) === '0.57' && independentAnchor.hi.toFixed(2) === '0.67');
check('independent L0 trim-and-fill finds 73 and d=.48', independentTrim.k0 === 73 && independentTrim.mean.toFixed(2) === '0.48', JSON.stringify(independentTrim));
check('independent raw PET reproduces published coefficients', close(rawPet.intercept, -0.11079100629700399, 1e-10) && close(rawPet.slope, 2.7371122002217634, 1e-10));
check('independent raw PEESE reproduces d=.25', rawPeese.intercept.toFixed(2) === '0.25' && rawPeese.slope.toFixed(2) === '4.77');
check('browser analysis agrees with independent anchor', close(shipped.fixed.mean, independentAnchor.mean, 1e-12) && close(shipped.fixed.q, independentAnchor.q, 1e-10));
check('browser analysis agrees with independent L0 result', shipped.trim.k0 === independentTrim.k0 && close(shipped.trim.mean, independentTrim.mean, 1e-12));

const gate = hindsight.gate(EgoData.records, '2010-07-31T23:59:59Z', { dateField: 'releaseDate' });
check('cutoff buckets balance 198/0/0/0', gate.counts.used === 198 && gate.counts.later === 0 && gate.counts.excluded === 0 && gate.counts.undated === 0 && gate.total === 198);
check('used set has no post-cutoff violation', hindsight.violations(gate.used, '2010-07-31T23:59:59Z', { dateField: 'releaseDate' }).length === 0);
const runner = records => {
  const g = hindsight.gate(records, '2010-07-31T23:59:59Z', { dateField: 'releaseDate' });
  const s = EgoAudit.summarize(g.used, 'adjusted');
  return { used: g.used, value: { k: s.k, mean: Number(s.fixed.mean.toFixed(12)) } };
};
const plantAudit = hindsight.auditFirewall(runner, EgoData.records, '2010-07-31T23:59:59Z', { id: 'FUTURE-PLANT', releaseDate: '2099-01-01', adjustedD: 99, rawD: 99, n1: 5, n2: 5 }, { dateField: 'releaseDate' });
check('2099 plant traverses the real runner but cannot enter or move it', plantAudit.pass && !plantAudit.enteredFit && !plantAudit.answerMoved);

let cutoffRefused = false;
try { hindsight.gate(EgoData.records, 'not-a-cutoff', { dateField: 'releaseDate' }); } catch { cutoffRefused = true; }
check('invalid cutoff is refused', cutoffRefused);
let malformedRefused = false;
try { EgoData.parse('Study;d;n1;n2;sd;EC;p-value(H0);significance\nbad;not-a-number;1;1;0;0;0;0'); } catch { malformedRefused = true; }
check('malformed data is refused', malformedRefused);
let thinRefused = false;
try { EgoAudit.summarize([], 'adjusted'); } catch { thinRefused = true; }
check('undersized analysis is refused', thinRefused);

const years = [...new Set(EgoData.records.map(r => r.year))].sort((a, b) => a - b);
const annual = years.map(year => {
  const used = EgoData.records.filter(r => r.year <= year);
  const s = EgoAudit.summarize(used, 'adjusted');
  return { year, warning: s.warning, k: s.k };
});
const firstWarning = annual.find(r => r.warning);
check('annual replay reaches every archive year and the 2009 endpoint', annual.length === years.length && annual.at(-1).year === 2009 && annual.at(-1).k === 198);
check('frozen rule first warns in 2003', firstWarning?.year === 2003);
check('warning has no hidden reversal after first crossing', annual.slice(annual.indexOf(firstWarning)).every(r => r.warning));

const methodDates = [
  ['Egger', '1997-09-13'],
  ['trim-and-fill', '2000-03-01'],
  ['excess significance', '2007-06-01'],
  ['PET', '2007-09-19'],
  ['contour funnel', '2008-10-01'],
  ['PEESE variance regression', '2009-01-09'],
];
const historicalCutoff = Date.parse('2010-07-31T23:59:59Z');
check('every applied method date precedes the historical cutoff', methodDates.every(([, date]) => Date.parse(`${date}T00:00:00Z`) <= historicalCutoff));
check('page states venue and publication timing for every applied method', ['BMJ 315:629-634, published September 13, 1997', 'Journal of the American Statistical Association 95:89-98, published March 2000', 'Clinical Trials 4:245-253, published June 2007', 'Oxford Bulletin of Economics and Statistics 70:103-127, first published online September 19, 2007', 'BMC Medical Research Methodology 9:2, published January 9, 2009', 'Journal of Clinical Epidemiology 61:991-996, published October 2008'].every(text => page.includes(text)));
const laterStart = page.indexOf('<section id="later-methods">');
const laterEnd = page.indexOf('</section>', laterStart);
const laterPanel = page.slice(laterStart, laterEnd);
check('post-cutoff methods are confined to a labeled later-methods panel', laterStart > 0 && laterPanel.includes('POST-CUTOFF') && laterPanel.includes('Conditional PET-PEESE') && laterPanel.includes('P-curve') && laterPanel.includes('Anytime-valid e-process'));
check('historical rule names only pre-cutoff ingredients', page.includes('Every ingredient was published before the July 2010 cutoff') && !page.slice(page.indexOf('Frozen before viewing 2016'), page.indexOf('Complete annual replay')).includes('p-curve'));

check('Control 3 preserves the mixed outcome', page.includes('The warning wins. The corrections do not.') && page.includes('Still far above the 2016 estimate of .04') && page.includes('It predicted the later result better'));
check('2016 registered result is stated completely', page.includes('23 laboratories, N = 2,141, 95% CI [-.07, .15]') && page.includes('d = .04'));
check('Control 4 names the genuinely unavailable quantity and counterfactual limit', page.includes('Control 4 / The unavailable quantity') && page.includes('Those observations did not exist') && page.includes('It does not claim knowledge of the branch history did not take'));
check('monitoring simulation exposes rates at increasing peek horizons', page.includes('Ever-crossing rate as peeks accumulate') && page.includes('horizons = [20, 50, 100, 198]') && page.includes('simHorizon'));
check('external-resource scan finds no third-party request', externalRequests(page).length === 0, externalRequests(page).join(', '));
const mutantViolations = externalRequests(`${page}<script>fetch("https://example.com")</script>`);
check('external-resource scanner catches planted network mutant', mutantViolations.some(v => v.startsWith('runtime:')));

check('head contains canonical, social cards, JSON-LD, and self-hosted fonts', page.includes('<link rel="canonical"') && page.includes('property="og:title"') && page.includes('name="twitter:card"') && page.includes('application/ld+json') && page.includes('href="/fonts/fonts.css"'));
check('page uses shared kit and has visible live status regions', page.includes('src="/_kit/hindsight.js"') && page.includes('role="status"') && page.includes('aria-live="polite"'));
check('reduced motion and focus-visible styles ship', page.includes('@media (prefers-reduced-motion: reduce)') && page.includes(':focus-visible'));
let inlineSyntaxOk = false;
try {
  const runtime = [...page.matchAll(/<script(?:\s[^>]*)?>([\s\S]*?)<\/script>/g)].map(match => match[1]).find(source => source.includes("const cutoff = '2010-07-31"));
  if (runtime) { new vm.Script(runtime); inlineSyntaxOk = true; }
} catch { inlineSyntaxOk = false; }
check('inline browser runtime parses as JavaScript', inlineSyntaxOk);
check('document and article close cleanly', /<\/article>\s*<\/main>[\s\S]*<\/body>\s*<\/html>\s*$/.test(page));
check('content registry entry is published and linked', content.includes('href: "/strata/ego-depletion-warning-in-plain-sight/"') && content.includes('draft: false') && content.includes('to: every-prediction-we-wrote-down-first'));
const emDash = String.fromCodePoint(0x2014);
check('owned files contain no em dash', ![page, dataSource, analysisSource, content, readme, fs.readFileSync(new URL(import.meta.url), 'utf8')].some(text => text.includes(emDash)));

if (failures.length) {
  console.error(`FAIL ${passed}/${total}`);
  failures.forEach(failure => console.error(`  ${failure}`));
  process.exit(1);
}

console.log(`PASS ${passed}/${total}`);
