import fs from 'node:fs';

const page = fs.readFileSync(new URL('../../public/strata/printer-that-lies/index.html', import.meta.url), 'utf8');
let pass=0, fail=0, refusals=0;
const ok=(c,m,{refusal=false}={})=>{c?pass++:fail++;if(refusal&&c)refusals++;console.log(`${c?'✓':'✗'} ${m}`)};
const near=(a,b,e=1e-9)=>Math.abs(a-b)<=e;
const fit=(x,y)=>{const xb=x.reduce((a,b)=>a+b)/x.length,yb=y.reduce((a,b)=>a+b)/y.length,den=x.reduce((s,v)=>s+(v-xb)**2,0);const a=x.reduce((s,v,i)=>s+(v-xb)*(y[i]-yb),0)/den,b=yb-a*xb,r=x.map((v,i)=>y[i]-(a*v+b));return{a,b,r,rms:Math.sqrt(r.reduce((s,v)=>s+v*v,0)/(x.length-2)),max:Math.max(...r.map(Math.abs))}};

console.log('published anchors');
const d=30, sector=31*d/30;
ok(sector===31,'1631 sector interval: 31 arcmin');
ok(sector-d===1,'1631 difference: 1 arcmin');
for(const [n,want] of [[5,.2],[10,.1],[20,.05]])ok(near(1/n,want),`direct vernier n=${n}: ${want} mm nominal least count`);
ok(near(8.5*25.4,215.9),'US Letter width: 8.5 in = 215.9 mm');
ok(near(11*25.4,279.4),'US Letter height: 11 in = 279.4 mm');
ok(page.includes('A4, 210 × 297 mm'),'A4 values rendered: 210 × 297 mm');

console.log('geometry and fit');
const coordinates=L=>Array.from({length:5},(_,i)=>20+i*(L-40)/4);
ok(JSON.stringify(coordinates(210))===JSON.stringify([20,62.5,105,147.5,190]),'A4 X coordinates');
ok(JSON.stringify(coordinates(297))===JSON.stringify([20,84.25,148.5,212.75,277]),'A4 Y coordinates');
ok(near(coordinates(210).at(-1)-20,170),'A4 horizontal baseline: 170 mm');
ok(near(coordinates(297).at(-1)-20,257),'A4 vertical baseline: 257 mm');
ok(near(coordinates(215.9).at(-1)-20,175.9),'Letter horizontal baseline: 175.9 mm');
ok(near(coordinates(279.4).at(-1)-20,239.4),'Letter vertical baseline: 239.4 mm');
for(const [name,h] of [['A4',297],['Letter',279.4]])ok(coordinates(h).at(-1)+3<=h,`${name} final cross fits its selected SVG height`);
const fx=fit(coordinates(210),[20.30,61.05,101.83,142.55,183.31]);
const fy=fit(coordinates(297),[19.70,82.71,145.77,208.70,271.75]);
ok(near(fx.a,0.9588705882352941,1e-12),'worked X fitted scale is pinned');
ok(near(fx.b,1.1265882352941077,1e-12),'worked X fitted offset is pinned');
ok(near(fy.a,0.9806848249027238,1e-12),'worked Y fitted scale is pinned');
ok(near(fy.b,0.09430350194551806,1e-12),'worked Y fitted offset is pinned');
ok(near(fx.rms,0.014605934866797631,1e-12),'worked X RMS residual is pinned');
ok(near(fy.rms,0.03321646178228697,1e-12),'worked Y RMS residual is pinned');
ok(fx.max<.75&&fy.max<.75,'worked example passes the fixed residual threshold');
ok(near(100/fx.a,104.28936003140949,1e-10),'worked X corrected 100 mm command');
ok(near(100/fy.a,101.96955990414067,1e-10),'worked Y corrected 100 mm command');
const u=2*Math.sqrt((.5/Math.sqrt(3))**2+(.2/Math.sqrt(3))**2+fx.rms**2);
ok(near(u,0.622511044078737,1e-12),'shown uncertainty recipe has a pinned result');
ok(near(Math.sqrt(2)*(.5/Math.sqrt(3))/170*100,.2401460532140371,1e-12),'170 mm baseline scale contribution: 0.2401%');

console.log('refusal paths');
const parse=s=>{const fields=s.split(',');if(fields.length!==5||fields.some(v=>v.trim()===''))return null;const a=fields.map(v=>Number(v.trim()));return a.every(v=>Number.isFinite(v)&&v>0)&&a.every((v,i)=>i===0||v>a[i-1])?a:null};
const acceptedFit=(x,y)=>{const fx=fit(coordinates(210),x),fy=fit(coordinates(297),y);return fx.a>=.9&&fx.a<=1.1&&fy.a>=.9&&fy.a<=1.1&&fx.max<=.75&&fy.max<=.75};
ok(parse('')===null,'refuses empty readings',{refusal:true});
ok(parse(',,,,')===null,'refuses five empty tokens',{refusal:true});
ok(parse('1,2,3,4')===null,'refuses four readings',{refusal:true});
ok(parse('1,2,3,4,5,6')===null,'refuses six readings',{refusal:true});
ok(parse('1,2,no,4,5')===null,'refuses non-numeric readings',{refusal:true});
ok(parse('0,1,2,3,4')===null,'refuses zero readings',{refusal:true});
ok(parse('-5,-4,-3,-2,-1')===null,'refuses negative readings',{refusal:true});
ok(parse('1,2,2,4,5')===null,'refuses non-increasing readings',{refusal:true});
const bad=fit(coordinates(210),[20,62.5,109,147.5,190]);
ok(bad.max>.75,'rejects a pinned non-affine outlier',{refusal:true});
ok(!acceptedFit(coordinates(210).map(v=>v*.5),coordinates(297).map(v=>v*.5)),'rejects a perfect 50% affine sequence',{refusal:true});
ok(!acceptedFit(coordinates(210).map(v=>v*1.11),coordinates(297).map(v=>v)),'rejects a perfect 111% affine sequence',{refusal:true});
ok(page.includes("fx.max>.75||fy.max>.75"),'page applies threshold to both axes',{refusal:true});
ok(page.includes("fx.a<.9||fx.a>1.1||fy.a<.9||fy.a>1.1"),'page applies plausibility gate to both fitted scales',{refusal:true});
ok(page.includes('if(!accepted||!P.state().calibrated'),'validation print refuses without an accepted fit',{refusal:true});
ok(page.includes("physical&&scaleChecked"),'validation refuses simulated values and an unchecked ruler',{refusal:true});
ok(page.includes('if(!xo||!yo)'),'page refuses invalid input before fitting',{refusal:true});
ok(page.includes("P.setMeasurement"),'shared ruler refusal is wired',{refusal:true});
ok(page.includes('more than 10% from nominal'),'implausible shared-ruler reading is explained',{refusal:true});
ok(page.includes('No correction was retained'),'bad shared-ruler reading clears correction',{refusal:true});
ok(page.includes('Stop if any cross is clipped'),'clipping refusal is printed on the artifact',{refusal:true});
ok(page.includes("const printHeight=size.h"),'selected paper height controls local SVG geometry',{refusal:true});

console.log('shareable surface and document integrity');
ok(!/[—]/.test(page),'page contains no em dash');
ok(page.includes('<meta name="description" content="Print a two-axis calibration sheet, measure it with your own ruler, and test whether an estimated correction survives a second physical print."'),'meta description does not claim earned accuracy');
ok((page.match(/estimated correction survives a second physical print/g)||[]).length===2,'meta and JSON-LD descriptions stay conditional');
ok(page.includes('estimates printer scale and edge position, then checks both on a second physical sheet'),'OG description names both validation targets');
ok(page.includes('then test the estimated correction on a second sheet'),'rendered dek does not pre-announce success');
ok(page.includes('cross 35.0 mm from LEFT, 55.0 mm from TOP'),'validation artifact renders both edge-position targets');
ok(page.includes('bars 100.0 mm'),'validation artifact renders the corrected length target');
ok(page.includes('U = 2√[(δ/√3)² + (s/√q)² + RMS²]'),'rendered uncertainty equation matches the implementation');
ok(page.includes('not achieved accuracies')&&page.includes('only when <span class="mono">a=1</span>'),'rendered vernier copy refuses circular accuracy');
ok(page.includes('</script>\n</body>\n</html>'),'load-bearing closing tags present');
ok(!page.includes('https://')||[...page.matchAll(/(?:src|href)="(https:\/\/[^\"]+)/g)].every(m=>m[1].startsWith('https://books.google.com')||m[1].startsWith('https://www.w3.org')||m[1].startsWith('https://www.nist.gov')||m[1].startsWith('https://www.itl.nist.gov')||m[1].startsWith('https://ftp.pwg.org')||m[1].startsWith('https://artwaste.land')),'external URLs are links or first-party metadata, not requests');

console.log(`\n${pass} passed, ${fail} failed; ${refusals} assertions cover refusal paths`);
process.exit(fail?1:0);
