// Run from apps/server: node ./evidence-driver.ts <output.json> <round>
// Copy this file to that location in each checkout; no test runner or mocks.
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as McpProviderSessions from '@t3tools/provider-core/server/McpProviderSessions';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import { FetchHttpClient } from 'effect/http';
import * as HtmlRender from './src/htmlRender/HtmlRender.ts';
import * as PreviewBrowser from './src/preview/PreviewBrowser.ts';
import * as ServerConfig from './src/config.ts';
import { writeFileSync, mkdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { performance } from 'node:perf_hooks';
const scratch = process.env.EVIDENCE_DIR!;
mkdirSync(scratch, { recursive: true });
const png = scratch + '/shot.png';
writeFileSync(png, Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]));
const layer = HtmlRender.layer.pipe(
 Layer.provide(PreviewBrowser.layer.pipe(Layer.provide(FetchHttpClient.layer))),
 Layer.provideMerge(McpProviderSessions.layer),
 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), scratch + '/state')),
 Layer.provideMerge(NodeServices.layer),
);
const median = (xs:number[]) => [...xs].sort((a,b)=>a-b)[Math.floor(xs.length/2)];
const result = {commit:execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim(), environment:{platform:process.platform,arch:process.arch,node:process.version}, round:Number(process.argv[3]), warmups:3, samples:15, cases:[] as unknown[]};
await Effect.runPromise(Effect.scoped(Effect.gen(function*(){
 const service = yield* HtmlRender.HtmlRender;
 for(const mib of [4,24]) {
  const line = 'lorem ipsum dolor sit amet 📸 consectetur adipiscing elit\r\n';
  const comment = '<!-- ' + line.repeat(Math.ceil(mib*1024*1024/line.length)) + ' <img src="/t3-missing/shot.png"> -->';
  const html = '<!doctype html><html><head><title>Shots</title></head><body>' + comment + '<h1>Visible</h1><img src="'+png+'"></body></html>';
  const timings:number[]=[]; const hashes = new Set<string>();
  for(let i=-3;i<15;i++) {
   const start = performance.now();
   const output = yield* service.prepare(html);
   const elapsed = performance.now()-start;
   if(!output.includes(comment) || !output.includes('<h1>Visible</h1>') || !output.includes('<img src="data:image/png;base64,iVBORw0KGgo=">') || output.includes(png)) throw new Error('Output changed or image handling failed');
   const hash = createHash('sha256').update(output).digest('hex');
   hashes.add(hash);
   if(i>=0) timings.push(elapsed);
  }
  if(hashes.size!==1) throw new Error('Unstable output');
  const entry={mib,bytes:Buffer.byteLength(html),timingsMs:timings,medianMs:median(timings),minMs:Math.min(...timings),maxMs:Math.max(...timings),sha256:[...hashes][0],imageInlined:true,commentUnchanged:true};
  result.cases.push(entry);
  console.log(JSON.stringify({round:result.round,...entry}));
 }
})).pipe(Effect.provide(layer)));
writeFileSync(process.argv[2],JSON.stringify(result,null,2));
