#!/usr/bin/env node
import fs from 'node:fs';
import vm from 'node:vm';

let assertions=0;
function ok(condition,message){assertions+=1;if(!condition)throw new Error(`assertion ${assertions} failed: ${message}`);console.log(`ok ${assertions} - ${message}`)}
function close(a,b,tol=1e-12){return Number.isNaN(a)&&Number.isNaN(b)||Math.abs(a-b)<=tol*Math.max(1,Math.abs(a),Math.abs(b))}

const html=fs.readFileSync(new URL('../../public/strata/error-bar-coverage/index.html',import.meta.url),'utf8');
const md=fs.readFileSync(new URL('../../src/content/strata/error-bar-coverage.md',import.meta.url),'utf8');
const ledgerText=fs.readFileSync(new URL('./data/ledger.json',import.meta.url),'utf8');
const islandText=html.match(/<script id="coverage-data" type="application\/json">([\s\S]*?)<\/script>/)[1];
const anchorText=fs.readFileSync(new URL('./data/anchor-rows.json',import.meta.url),'utf8');
const anchorIslandText=html.match(/<script id="anchor-data" type="application\/json">([\s\S]*?)<\/script>/)[1];
const packed=JSON.parse(ledgerText);
const anchorPacked=JSON.parse(anchorText);
const engine=html.match(/<script id="coverage-engine">([\s\S]*?)<\/script>/)[1];
const context={globalThis:{}};vm.createContext(context);vm.runInContext(engine,context);const page=context.globalThis.CoverageEngine;

function unpack(p){return p.r.map(a=>({q:p.q[a[0]],edition:a[1],value:a[2],up:a[3],down:a[4],compare:a[5],compareUnc:a[6],next:a[7],nextUnc:a[8],changed:Boolean(a[9]),si:Boolean(a[10])}))}
const records={codata:unpack(packed.codata),pdg:unpack(packed.pdg)};
function median(xs){if(!xs.length)return NaN;const a=[...xs].sort((x,y)=>x-y),m=Math.floor(a.length/2);return a.length%2?a[m]:(a[m-1]+a[m])/2}
function select(rows,filter){let a=rows.filter(r=>filter!=='changed'||r.changed).filter(r=>filter!=='si'||!r.si);if(filter==='one'){const seen=new Set();a=a.filter(r=>{if(seen.has(r.q))return false;seen.add(r.q);return true})}return a}
function independent(rows,{sigma=1,metric='point',filter='all'}={}){
  const base=select(rows,filter).filter(r=>metric!=='next'||Number.isFinite(r.next));let k=0;const zs=[];
  for(const r of base){const target=metric==='next'?r.next:r.compare,targetUnc=metric==='next'?r.nextUnc:r.compareUnc,d=target-r.value,u=d>=0?r.up:r.down;let limit=sigma*u;if(metric==='overlap')limit+=targetUnc;if(metric==='combined')limit=sigma*Math.hypot(u,targetUnc);if(Math.abs(d)<=limit)k+=1;zs.push(d/u)}
  return {k,n:base.length,rate:base.length?k/base.length:NaN,median:median(zs),removed:rows.length-base.length};
}
function erfc(x){const z=Math.abs(x),t=1/(1+z/2),r=t*Math.exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+t*(.09678418+t*(-.18628806+t*(.27886807+t*(-1.13520398+t*(1.48851587+t*(-.82215223+t*.17087277)))))))));return x>=0?r:2-r}
function independentBootstrap(rows,opt,reps=400){let base=select(rows,opt.filter||'all');if(opt.metric==='next')base=base.filter(r=>Number.isFinite(r.next));const groups=new Map();for(const r of base){if(!groups.has(r.q))groups.set(r.q,[]);groups.get(r.q).push(r)}const values=[...groups.values()],rates=[];let seed=12638714;function random(){seed^=seed<<13;seed^=seed>>>17;seed^=seed<<5;return (seed>>>0)/4294967296}if(!values.length)return {lo:NaN,hi:NaN,reps,clusters:0};for(let i=0;i<reps;i++){let k=0,n=0;for(let j=0;j<values.length;j++){const r=independent(values[Math.floor(random()*values.length)],{...opt,filter:'all'});k+=r.k;n+=r.n}rates.push(k/n)}rates.sort((a,b)=>a-b);return {lo:rates[Math.floor(.025*(reps-1))],hi:rates[Math.floor(.975*(reps-1))],reps,clusters:values.length}}

const frontmatterDate=(md.match(/^date:\s*(\d{4}-\d{2}-\d{2})$/m)||[])[1];
ok(frontmatterDate==='2026-08-01','publication date is read from markdown frontmatter');
ok(islandText===ledgerText,'the browser ships the exact committed ledger bytes');
ok(packed.anchor.n===40&&packed.anchor.publishedPercent===57&&packed.anchor.threshold===2.33,'the ledger anchor fields match Table I');
const independentNormal=erfc(2.33/Math.SQRT2),pageNormal=page.normalOutside(2.33);
ok(close(independentNormal,pageNormal),'independent normal-tail anchor agrees with the page engine');
ok((100*independentNormal).toFixed(1)==='2.0','the published calibrated-normal 2 percent anchor is reproduced');

// Henrion and Fischhoff Table I, recommended values 1928-1973, recomputed from the committed transcription.
function unpackAnchorRows(p){return p.rows.map(a=>{const v=p.reviews[a[0]],q=p.quantities[a[1]];return {review:v.label,year:v.year,quantity:q.label,value:a[2],uncertainty:a[3],target:q.target}})}
function anchorIndependent(rows,threshold){let k=0,inner=0,ss=0,near=null;for(const r of rows){const z=(r.value-r.target)/r.uncertainty;ss+=z*z;if(Math.abs(z)>threshold)k+=1;if(Math.abs(z)<=.675)inner+=1;const gap=Math.abs(Math.abs(z)-threshold);if(!near||gap<near.gap)near={gap,z,row:r}}const n=rows.length;return {k,n,rate:n?k/n:NaN,quartile:n?inner/n:NaN,rms:n?Math.sqrt(ss/n):NaN,nearest:near}}

ok(anchorIslandText===anchorText,'the browser ships the exact committed anchor-row bytes');
ok(anchorPacked.anchor.n===40&&anchorPacked.anchor.surprisePercent===57&&anchorPacked.anchor.threshold===2.33&&anchorPacked.anchor.birgeRatio===7.42&&anchorPacked.anchor.interquartilePercent===22,'the committed anchor metadata matches Table I');
ok(anchorPacked.rows.length===40&&anchorPacked.reviews.length===8&&anchorPacked.quantities.length===5,'the transcription is five constants across eight reviews, 40 rows');
ok(anchorPacked.reviews.every(r=>/^10\.1103\//.test(r.doi))&&new Set(anchorPacked.rows.map(r=>r[0]+':'+r[1])).size===40,'every review carries a DOI and every constant-review pair appears once');
const anchorRows=unpackAnchorRows(anchorPacked),pageAnchorRows=page.unpackAnchor(anchorPacked);
ok(anchorRows.length===pageAnchorRows.length&&anchorRows.every((r,i)=>close(r.value,pageAnchorRows[i].value)&&close(r.uncertainty,pageAnchorRows[i].uncertainty)&&close(r.target,pageAnchorRows[i].target)),'the page engine unpacks the anchor rows to the same numbers');
const ownAnchor=anchorIndependent(anchorRows,anchorPacked.anchor.threshold),shippedAnchor=page.anchorIndex(pageAnchorRows,anchorPacked.anchor.threshold);
ok(ownAnchor.k===23&&ownAnchor.n===40,'the committed rows independently give 23 of 40 outside 2.33 quoted standard uncertainties');
const nearPublished=[...Array(41).keys()].filter(k=>Math.abs(100*k/40-anchorPacked.anchor.surprisePercent)<=1);
ok((100*ownAnchor.rate).toFixed(1)==='57.5'&&nearPublished.length===1&&nearPublished[0]===23,'the recomputed surprise index is 57.5 percent, and 23 is the only count out of 40 within one point of the published 57 percent');
ok(ownAnchor.k===shippedAnchor.k&&ownAnchor.n===shippedAnchor.n&&close(ownAnchor.rate,shippedAnchor.rate)&&close(ownAnchor.rms,shippedAnchor.rms)&&close(ownAnchor.quartile,shippedAnchor.quartile),'the shipped page engine reproduces the anchor count, rate, residual scale and interquartile index');
ok(ownAnchor.rms.toFixed(2)==='7.68'&&ownAnchor.rms>anchorPacked.anchor.birgeRatio,'the published Birge ratio 7.42 is not reproduced; these rows give 7.68');
ok((100*ownAnchor.quartile).toFixed(1)==='12.5','the published interquartile index 22 percent is not reproduced either');
ok(ownAnchor.nearest.row.year===1929&&ownAnchor.nearest.row.quantity==='inverse fine-structure constant'&&ownAnchor.nearest.z.toFixed(2)==='2.31','the closest row to the threshold is the 1929 inverse fine-structure constant at 2.31 sigma');
for(const t of [1,2,2.33,3]){const own=anchorIndependent(anchorRows,t),shipped=page.anchorIndex(pageAnchorRows,t);ok(own.k===shipped.k&&close(own.rms,shipped.rms)&&own.nearest.row.year===shipped.nearest.row.year,`anchor engine agrees at ${t} sigma`)}
const alphaRow=anchorPacked.rows.findIndex(r=>r[1]===0&&anchorPacked.reviews[r[0]].year===1929);
ok(alphaRow>=0&&anchorPacked.rows[alphaRow][2]===137.29,'the 1929 inverse fine-structure value is transcribed as 137.29, the value Birge quotes in his text');
const mutatedAnchor=unpackAnchorRows({...anchorPacked,rows:anchorPacked.rows.map((r,i)=>i===alphaRow?[r[0],r[1],137.30,r[3]]:r)});
const mutatedResult=anchorIndependent(mutatedAnchor,anchorPacked.anchor.threshold);
ok(mutatedResult.k===24&&mutatedResult.k!==ownAnchor.k,'moving the 1929 inverse fine-structure value to 137.30 turns the anchor count red at 24 of 40');
ok(page.anchorIndex(mutatedAnchor,anchorPacked.anchor.threshold).k===mutatedResult.k,'the shipped engine sees the same mutation');
const mutatedUnc=unpackAnchorRows({...anchorPacked,rows:anchorPacked.rows.map(r=>[r[0],r[1],r[2],r[3]*4])});
ok(anchorIndependent(mutatedUnc,anchorPacked.anchor.threshold).k!==ownAnchor.k,'inflating every transcribed uncertainty turns the anchor count red');

for(const name of ['codata','pdg']){
  ok(records[name].length===packed[name].r.length,`${name} packed rows decode independently`);
  for(const sigma of [.5,1,2.33,3])for(const metric of ['point','overlap','combined','next'])for(const filter of ['all','changed','si','one']){
    const own=independent(records[name],{sigma,metric,filter}),shipped=page.compute(records[name],{sigma,metric,filter});
    ok(own.k===shipped.k&&own.n===shipped.n&&own.removed===shipped.removed&&close(own.rate,shipped.rate)&&close(own.median,shipped.median),`${name} agrees at ${sigma} sigma, ${metric}, ${filter}`);
  }
  const editions=new Map();for(const row of records[name]){if(!editions.has(row.edition))editions.set(row.edition,[]);editions.get(row.edition).push(row)}
  const shippedEditions=page.editions(records[name],{sigma:1});ok(shippedEditions.length===editions.size,`${name} edition family has the expected size`);
  for(const x of shippedEditions){const own=independent(editions.get(Number(x.edition))||editions.get(x.edition),{sigma:1});ok(own.k===x.result.k&&own.n===x.result.n,`${name} edition ${x.edition} agrees`)}
  for(const opt of [{sigma:1,metric:'point',filter:'all'},{sigma:1,metric:'overlap',filter:'changed'}]){const own=independentBootstrap(records[name],opt,40),shipped=page.bootstrap(records[name],opt,40);ok(close(own.lo,shipped.lo)&&close(own.hi,shipped.hi)&&own.clusters===shipped.clusters,`${name} cluster bootstrap agrees for ${opt.metric}, ${opt.filter}`)}
}

const probe=[{value:0,up:1,down:1,compare:.5,compareUnc:.1,next:.6,nextUnc:.1,q:'x',edition:1,changed:true,si:false},{value:0,up:1,down:1,compare:2,compareUnc:2,next:0,nextUnc:.1,q:'y',edition:1,changed:false,si:true}];
ok(independent(probe).k===1,'point-containment probe contains one of two rows');
ok(independent(probe,{metric:'overlap'}).k===2,'latest-interval overlap changes the probe result');
ok(independent(probe,{metric:'next'}).k===2,'next-edition target changes the probe result');
ok(independent(probe,{filter:'changed'}).n===1&&independent(probe,{filter:'si'}).n===1,'both exclusion families can remove a row');
const mutated=probe.map(r=>({...r,up:r.up*3,down:r.down*3}));ok(independent(mutated).k!==independent(probe).k,'uncertainty mutation turns the point check red');
const mutatedLatest=probe.map(r=>({...r,compareUnc:0}));ok(independent(mutatedLatest,{metric:'overlap'}).k!==independent(probe,{metric:'overlap'}).k,'latest-uncertainty mutation turns overlap red');
const mutatedNext=probe.map(r=>({...r,next:r.next+5}));ok(independent(mutatedNext,{metric:'next'}).k!==independent(probe,{metric:'next'}).k,'next-value mutation turns next-edition coverage red');
const bootProbe=[...probe,{...probe[0],q:'z',compare:8,next:8}];ok(independentBootstrap(bootProbe,{sigma:1,metric:'point',filter:'all'},40).hi!==independentBootstrap(bootProbe.map(r=>({...r,up:r.up*20,down:r.down*20})),{sigma:1,metric:'point',filter:'all'},40).hi,'uncertainty mutation turns cluster bootstrap red');
ok(page.compute(probe,{sigma:1}).k===1,'the shipped engine executes in isolation');
console.log(`1..${assertions}`);
