import os,sys,json,time,threading,subprocess,pathlib,http.server,socket
root=pathlib.Path(__file__).parent
side,checkout,sha=sys.argv[1:]
out=root/(side+'-'+time.strftime('%Y%m%dT%H%M%S'));out.mkdir()
start=time.monotonic();events=[];lock=threading.Lock()
def record(**kw):
    row={'seconds':round(time.monotonic()-start,2),**kw}
    with lock:
        events.append(row)
        with (out/'receiver.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
    print(json.dumps(row),flush=True)
class Receiver(http.server.BaseHTTPRequestHandler):
    def log_message(self,*args):pass
    def do_POST(self):
        elapsed=time.monotonic()-start
        body=self.rfile.read(int(self.headers.get('Content-Length',0)))
        status=503 if self.path=='/v1/logs' or (self.path=='/v1/metrics' and 35<=elapsed<60) else 200
        data=json.loads(body);series=[];names=[]
        for r in data.get('resourceMetrics',[]):
            for s in r.get('scopeMetrics',[]):
                for m in s.get('metrics',[]):
                    names.append(m['name'])
                    if m['name']=='t3_otlp_export_attempt_failures_total':
                        series.append(m)
        # Only synthetic failure-counter points; resource attributes and startup logs stay private.
        record(endpoint=self.path,status=status,metricCount=len(names),failureCounter=series)
        self.send_response(status);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(b'{}')
server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Receiver)
threading.Thread(target=server.serve_forever,daemon=True).start()
s=socket.socket();s.bind(('127.0.0.1',0));port=s.getsockname()[1];s.close()
env={k:v for k,v in os.environ.items() if not k.startswith(('OTEL_','T3CODE_OTLP_'))}
env.update(T3CODE_DEV_SEED='0',T3CODE_OTLP_LOGS_URL=f'http://127.0.0.1:{server.server_port}/v1/logs',T3CODE_OTLP_METRICS_URL=f'http://127.0.0.1:{server.server_port}/v1/metrics',T3CODE_OTLP_PROTOCOL='http/json')
record(event='start',side=side,commit=sha,conditions='Default log level and 10s export interval; logs always 503; metrics 503 at t=35..60s, otherwise 200; fresh isolated data')
with (out/'private-console.log').open('w') as console:
    p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(out/'home'),'--no-browser'],cwd=checkout,env=env,stdout=console,stderr=subprocess.STDOUT)
    try:
        p.wait(timeout=140)
        record(event='unexpected_exit',code=p.returncode)
    except subprocess.TimeoutExpired:pass
    finally:
        p.terminate()
        try:p.wait(timeout=15)
        except subprocess.TimeoutExpired:p.kill();p.wait()
server.shutdown()
console=(out/'private-console.log').read_text()
record(event='console_check',exportFailureMention=any(x in console.lower() for x in ['failed to export','status_503','otlp export failed']),serverListening='Listening' in console or 'listening' in console)
(root/(side+'-output.txt')).write_text(str(out))
