import http from 'node:http';
import {ROOT_CONTEXT,trace,SpanStatusCode} from '@opentelemetry/api';
import {TracerProvider,SimpleSpanProcessor,InMemorySpanExporter} from '@opentelemetry/sdk-trace';
const exporter=new InMemorySpanExporter(),provider=new TracerProvider({spanProcessors:[new SimpleSpanProcessor({exporter})]}),tracer=provider.getTracer('zyel-local-report');
let count=0,good=0,inFlight=0;const durations=[];
const server=http.createServer(async(req,res)=>{
 if(req.url==='/metrics'){res.writeHead(200,{'Content-Type':'text/plain; version=0.0.4'});res.end(`# TYPE lab_requests_total counter\nlab_requests_total{route="/report"} ${count}\n# TYPE lab_latency_good_total counter\nlab_latency_good_total{route="/report"} ${good}\n# TYPE lab_in_flight gauge\nlab_in_flight ${inFlight}\n`);return;}
 if(req.url==='/traces'){await provider.forceFlush();res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(exporter.getFinishedSpans().map(s=>({name:s.name,traceId:s.spanContext().traceId,parent:s.parentSpanContext?.spanId||null,duration:s.duration}))));return;}
 if(req.url!=='/report'){res.writeHead(404).end();return;}
 if(inFlight>=4){res.writeHead(429).end('Fixture capacity reached');return;}inFlight++;const started=performance.now();
 const root=tracer.startSpan('GET /report',{},ROOT_CONTEXT),ctx=trace.setSpan(ROOT_CONTEXT,root),db=tracer.startSpan('db.fixture',{},ctx);const delay=(count+inFlight)%8===0?180:8;
 try{await new Promise(r=>setTimeout(r,delay));db.end();root.setStatus({code:SpanStatusCode.OK});root.end();const ms=performance.now()-started;count++;if(ms<=100)good++;durations.push(ms);if(durations.length>100)durations.shift();if(exporter.getFinishedSpans().length>200)exporter.reset();res.writeHead(200,{'Content-Type':'application/json'}).end(JSON.stringify({fixture:true,traceId:root.spanContext().traceId,durationMs:ms}));}finally{inFlight--;}
});
server.listen(4201,process.env.LAB_CONTAINER==='1'?'0.0.0.0':'127.0.0.1',()=>console.log('Local report /report, /traces and /metrics on port 4201'));
