import json, html
from http.server import BaseHTTPRequestHandler, HTTPServer
spans=[]
class Handler(BaseHTTPRequestHandler):
 def log_message(self,*args): pass
 def do_DELETE(self):
  spans.clear(); self.send_response(200); self.end_headers(); self.wfile.write(b'{}')
 def do_GET(self):
  if self.path == '/report':
   creates=[s for s in spans if s['name']=='orchestrationV2.dispatch.threadCreate']
   ids={s['traceId'] for s in creates}
   selected=[s for s in spans if s['traceId'] in ids]
   failed=[s for s in selected if s['name']=='ProjectionStore.getThread' and s.get('status',{}).get('code')==2]
   rows=''.join('<tr><td>'+html.escape(s['name'])+'</td><td>'+str(s.get('status',{}).get('code',0))+'</td><td>'+html.escape(s.get('status',{}).get('message',''))+'</td></tr>' for s in selected)
   body='<html><style>body{font:16px system-ui;margin:40px;color:#172033;background:#f8fafc}h1{font-size:27px}table{border-collapse:collapse;width:100%;background:white}td,th{padding:14px;border:1px solid #cbd5e1;text-align:left}td:first-child{font-family:monospace}p{line-height:1.6}.stat{font-size:22px;font-weight:600}</style><h1>Thread creation — exported OTLP spans</h1><p>Source: real T3 development server → local HTTP/JSON collector.<br>Replay provider; fresh database; first message creates the thread.<br>Status codes: 0 = UNSET (no error), 2 = ERROR.</p><p class="stat">Successful threadCreate spans: '+str(len(creates))+'<br>Failed ProjectionStore.getThread spans in those traces: '+str(len(failed))+'</p><table><tr><th>Span</th><th>Status</th><th>Message</th></tr>'+rows+'</table><p>Only spans sharing a threadCreate trace ID are shown.</p></html>'
   self.send_response(200); self.send_header('Content-Type','text/html'); self.end_headers(); self.wfile.write(body.encode()); return
  self.send_response(200); self.send_header('Content-Type','application/json'); self.end_headers(); self.wfile.write(json.dumps(spans).encode())
 def do_POST(self):
  data=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0'))) or b'{}')
  for resource in data.get('resourceSpans',[]):
   for scope in resource.get('scopeSpans',[]):
    for span in scope.get('spans',[]):
     if span.get('name') in ['orchestrationV2.dispatch.threadCreate','ProjectionStore.getThread','ProjectionStore.findThread']:
      clean={k:span[k] for k in ['name','traceId','spanId','parentSpanId','status'] if k in span}
      clean['events']=[{'name':e.get('name'),'attributes':[a for a in e.get('attributes',[]) if a.get('key') in ['exception.type','exception.message']]} for e in span.get('events',[])]
      spans.append(clean)
  self.send_response(200); self.send_header('Content-Type','application/json'); self.end_headers(); self.wfile.write(b'{}')
HTTPServer(('127.0.0.1',4318),Handler).serve_forever()
