import os, sys, time, json, threading, subprocess, signal, re, http.server, pathlib, socket
root=pathlib.Path(__file__).parent
out=root/time.strftime('run-%Y%m%d-%H%M%S');out.mkdir()
side, checkout=sys.argv[1:3]
active={}; start=0; events=[]; lock=threading.Lock()
def emit(msg):
    with lock:
        t=round(time.monotonic()-start,3);events.append([t,msg]);print(f'{t:07.3f}s {msg}',flush=True)
class Receiver(http.server.BaseHTTPRequestHandler):
    def log_message(self,*args): pass
    def do_POST(self):
        raw=self.rfile.read(int(self.headers.get('Content-Length',0)))
        try:
            data=json.loads(raw)
            metrics=[m for r in data.get('resourceMetrics',[]) for s in r.get('scopeMetrics',[]) for m in s.get('metrics',[]) if m['name'].startswith('t3_process_group_')]
            for m in metrics:
                points=m.get('gauge',{}).get('dataPoints',[])
                vals=[{'group':next((a['value'].get('stringValue') for a in p.get('attributes',[]) if a['key']=='group'),None),'value':p.get('asDouble',p.get('asInt'))} for p in points]
                emit('OTLP '+m['name']+' '+json.dumps(vals))
        except Exception as e: emit('RECEIVER ERROR '+str(e))
        self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(b'{}')
server=http.server.ThreadingHTTPServer(('127.0.0.1',4318),Receiver)
threading.Thread(target=server.serve_forever,daemon=True).start()
for mode in ['working','missing']:
    events=[];start=time.monotonic()
    env=os.environ.copy();env.update(T3CODE_DEV_SEED='0',T3CODE_OTLP_METRICS_URL='http://127.0.0.1:4318/v1/metrics',T3CODE_RESOURCE_MONITOR_PATH=str(root/('t3-resource-monitor' if mode=='working' else 'unavailable-monitor')))
    # Stable public resource identity avoids disclosing the host in any exported data.
    env['OTEL_RESOURCE_ATTRIBUTES']='host.name=evidence-linux,service.instance.id='+side+'-'+mode
    cmd=['node','apps/server/dist/bin.mjs','serve','--host','127.0.0.1','--port','14380','--base-dir',str(out/(mode+'-home')),'--no-browser']
    emit(f'START {side} / {mode}; Linux x64; built CLI; isolated fresh T3 home; local OTLP receiver; observe 82 seconds')
    p=subprocess.Popen(cmd,cwd=checkout,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,start_new_session=True)
    def read():
        with open(out/(mode+'-private.log'),'w') as rawlog:
            for line in p.stdout:
                rawlog.write(line);rawlog.flush()
                plain=re.sub(r'\x1b\[[0-9;]*m','',line).rstrip()
                if any(x in plain.lower() for x in ['process group metrics','sidecar is not running','resource monitor binary','resourcemonitorbinary','resource monitor executable']):
                    plain=plain.replace(checkout,'<checkout>').replace(str(root),'<scratch>')
                    plain=re.sub(r'"(?:candidates|searchedPaths)":.*','"paths": "redacted"',plain)
                    emit('SERVER '+plain)
    t=threading.Thread(target=read,daemon=True);t.start()
    try:
        p.wait(timeout=82)
        emit('SERVER EXITED EARLY code='+str(p.returncode))
    except subprocess.TimeoutExpired:
        emit('OBSERVATION COMPLETE; stopping captured process group')
        os.killpg(p.pid,signal.SIGTERM)
        try:p.wait(timeout=10)
        except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
    t.join(timeout=2)
    (out/(side+'-'+mode+'.txt')).write_text('\n'.join(f'{t:07.3f}s {m}' for t,m in events)+'\n')
    with open(out/(side+'-'+mode+'.cast'),'w') as f:
        f.write(json.dumps({'version':2,'width':140,'height':35,'timestamp':int(time.time()),'title':side+' '+mode+' process group metrics'})+'\n')
        for tm,msg in events:f.write(json.dumps([tm,'o',f'{tm:07.3f}s {msg}\r\n'])+'\n')
server.shutdown()
print('ARTIFACTS '+str(out))
