#!/usr/bin/env python3
"""Real-server trace comparison. No code patches, clock changes, or seeded databases.
Usage: python3 driver.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIRECTORY
Requires Python/Pillow, Node, ffmpeg, and installed checkout dependencies.
XDG_RUNTIME_DIR is unset only for the test servers to exercise fallback Claude descendant polling.
Recordings cover 195 seconds at 10x speed. Final stills use the final export,
which is read after checking the Claude outcome and may follow the recording by a few seconds.
Only structural trace fields are copied to shareable output; no log bodies or attributes.
"""
import os, sys, json, time, subprocess, pathlib, urllib.request, signal, collections, datetime, socket
from PIL import Image, ImageDraw, ImageFont
BASE_SHA='b4d93997eb707075b105ae35280bfc5f71e53224'
HEAD_SHA='737f8d290853ca26efa28a7df2d69e80e7a07e92'
TARGETS=['ScheduledTaskService.runDueTasks','UsageLimitRecoveryWorker.sweep','ScheduledTaskService.dispatchPendingWebhooks','ThreadSettlementServiceV2.sweep','PullRequestSyncReactor.sweep','ClaudeAgentSdkQueryRunner.trackDescendants']
DURATION=195
root=pathlib.Path(sys.argv[3])/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); root.mkdir(parents=True)
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; mono='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
def f(n, m=False): return ImageFont.truetype(mono if m else font,n)
runs=[]
def read(run):
 p=run['dir']/'data/userdata/logs/server.trace.ndjson'; rows=[]
 if p.exists():
  for line in p.read_text().splitlines():
   try: rows.append(json.loads(line))
   except ValueError: pass
 return rows

def stats(rows):
 return {name:{'ticks':len(rr:=[r for r in rows if r.get('name')==name]),'traces':len(set(r['traceId'] for r in rr)), 'roots':sum(not r.get('parentSpanId') for r in rr)} for name in TARGETS}

def render(run,elapsed,rows,path):
 im=Image.new('RGB',(1920,1080),'#0b1220'); d=ImageDraw.Draw(im)
 def t(x,y,s,size=24,color='#e5edf8',m=False): d.text((x,y),str(s),font=f(size,m),fill=color)
 t(65,40,'REAL SERVER  /  TRACE OWNERSHIP',30,'#94b8d9'); t(65,95,run['side'].upper()+'   '+run['sha'][:10],44)
 t(65,160,f'Fresh database · Linux · Node serve · Debug trace retention · elapsed {elapsed:03d}s',25)
 t(65,202,'15 HTTP requests; real Claude hash computation, without systemd scopes; unchanged background loops at wall-clock cadence.',22,'#a9b9ce')
 for x,label in [(65,'EXPORTED TICK SPAN'),(1000,'TICKS'),(1210,'TRACES'),(1430,'ROOTS'),(1630,'LARGEST TRACE')]: t(x,270,label,20,'#91a4bf')
 counts=stats(rows)
 for i,name in enumerate(TARGETS):
  y=325+i*70; rr=[r for r in rows if r.get('name')==name]; st=counts[name]; largest=max(collections.Counter(r['traceId'] for r in rr).values(),default=0)
  d.line((65,y+65,1855,y+65),fill='#26364c',width=1)
  t(65,y,name,23,m=True)
  for x,k in [(1000,'ticks'),(1210,'traces'),(1430,'roots')]: t(x,y,st[k],30,'#9be7c4' if st['roots']==st['ticks'] and st['ticks'] else '#ffca8a',True)
  t(1630,y,largest,30,m=True)
 t(65,770,'Most recent worker / Claude polls (trace ID / parent span ID):',23,'#91a4bf')
 for i,name in enumerate(TARGETS[3:6]):
  rr=[r for r in rows if r.get('name')==name][-3:]
  t(65,815+i*65,name,21,m=True)
  t(65,843+i*65,'   '.join(r['traceId'][:12]+' / '+str(r.get('parentSpanId') or 'ROOT') for r in rr),20,m=True)
 t(65,1005,'Source: live server.trace.ndjson. Counts include idle ticks retained at Debug. No shutdown spans included.',21,'#a9b9ce')
 im.save(path)
try:
 for side,checkout,sha,port in [('before',sys.argv[1],BASE_SHA,38621),('after',sys.argv[2],HEAD_SHA,38622)]:
  rd=root/side; rd.mkdir(); (rd/'frames').mkdir()
  log=open(rd/'private-server.log','w')
  env=dict(os.environ,T3CODE_DEV_SEED='0',T3CODE_TRACE_MIN_LEVEL='Debug',T3CODE_TRACE_MAX_BYTES='104857600',T3CODE_TRACE_MAX_FILES='1')
  env.pop('XDG_RUNTIME_DIR',None)
  cmd=['node','apps/server/src/bin.ts','serve','--base-dir',str(rd/'data'),'--port',str(port),'--host','127.0.0.1',checkout]
  p=subprocess.Popen(cmd,cwd=checkout,env=env,stdout=log,stderr=subprocess.STDOUT,process_group=0)
  (rd/'private-server.pid').write_text(str(p.pid))
  run=dict(side=side,sha=sha,port=port,dir=rd,p=p,log=log,checkout=checkout); runs.append(run)
 for run in runs:
  deadline=time.monotonic()+90
  while True:
   if run['p'].poll() is not None: raise RuntimeError('server exited: '+run['side'])
   try:
    
    if 'T3 Code server is ready.' not in (run['dir']/'private-server.log').read_text(): raise OSError('starting')
    socket.create_connection(('127.0.0.1',run['port']),timeout=1).close()
    break
   except urllib.error.HTTPError: break
   except OSError:
    if time.monotonic()>deadline: raise RuntimeError('server did not listen')
    time.sleep(.25)
  results=[]
  for method,path in [('GET','/mcp'),('POST','/mcp'),('GET','/api/preview/tunnel')]:
   for i in range(5):
    req=urllib.request.Request(f'http://127.0.0.1:{run["port"]}{path}',method=method,data=b'{}' if method=='POST' else None,headers={'Content-Type':'application/json'})
    try:
     with urllib.request.urlopen(req,timeout=5) as res: status=res.status
    except urllib.error.HTTPError as e: status=e.code
    results.append(dict(method=method,path=path,status=status))
  (run['dir']/'requests.json').write_text(json.dumps(results,indent=2))
 for run in runs:
  workspace=run['dir']/'workspace'; workspace.mkdir(); (workspace/'README.md').write_text('Synthetic trace polling proof.\n')
  cli=['node','apps/server/src/bin.ts']
  common=['--base-dir',str(run['dir']/'data')]
  def call(args):
   result=subprocess.run(cli+args+common,cwd=run['checkout'],capture_output=True,text=True,timeout=40)
   if result.returncode: raise RuntimeError('seeding CLI failed: '+result.stderr[:200])
   return result.stdout
  call(['project','add',str(workspace),'--title','Trace polling proof'])
  launched=json.loads(call(['thread','start',str(workspace),'Use Bash to run this synthetic hash computation exactly: python3 -c \'import hashlib; print(hashlib.pbkdf2_hmac("sha256",b"trace-proof",b"synthetic",100000000).hex())\' . After it completes, reply only OK. Do not read or modify files.' ,'--provider','claudeAgent','--model','claude-haiku-5-5','--title','Trace polling proof','--json']))
  run['threadId']=launched['threadId']
 start=time.monotonic()
 for second in range(DURATION+1):
  for run in runs:
   rows=read(run); render(run,second,rows,run['dir']/f'frames/{second:04d}.png')
   if second%30==0: print(run['side'],second,json.dumps(stats(rows)),flush=True)
  if second<DURATION: time.sleep(max(0,start+second+1-time.monotonic()))
 for run in runs:
  state=subprocess.run(['node','apps/server/src/bin.ts','thread','show',run['threadId'],'--base-dir',str(run['dir']/'data'),'--json'],cwd=run['checkout'],capture_output=True,text=True,timeout=30)
  if state.returncode==0:
   result=json.loads(state.stdout)
   (run['dir']/'claude-outcome.json').write_text(json.dumps({'status':result['thread']['status'],'model':result['thread']['model'],'messages':result.get('messages'),'error':result.get('error')},indent=2))
  rows=read(run)
  keys=['type','name','traceId','spanId','parentSpanId','startTimeUnixNano','endTimeUnixNano','durationMs']
  (run['dir']/'trace-structure.ndjson').write_text('\n'.join(json.dumps({**{k:r[k] for k in keys if k in r}, **({'httpPath': r.get('attributes',{}).get('url.path',r.get('attributes',{}).get('http.url','')).split('?')[0]} if r.get('attributes',{}).get('url.path',r.get('attributes',{}).get('http.url','')) in ['/mcp','/api/preview/tunnel'] else {})}) for r in rows)+'\n')
  (run['dir']/'summary.json').write_text(json.dumps(stats(rows),indent=2))
  final_second=round(time.monotonic()-start)
  render(run,final_second,rows,run['dir']/'final.png'); time.sleep(.5); render(run,final_second,rows,run['dir']/'final-stability.png')
  subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','10','-i',str(run['dir']/'frames/%04d.png'),'-c:v','libx264','-crf','21','-pix_fmt','yuv420p',str(run['dir']/'trace-growth.mp4')],check=True)
 print('OUTPUT',root,flush=True)
finally:
 for run in runs:
  if run['p'].poll() is None:
   run['p'].send_signal(signal.SIGINT)
   try: run['p'].wait(timeout=15)
   except subprocess.TimeoutExpired: run['p'].terminate(); run['p'].wait(timeout=15)
  run['log'].close()
