from PIL import Image,ImageDraw,ImageFont
import pathlib,json,re,subprocess
root=pathlib.Path(__file__).parent
font='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
f=ImageFont.truetype(font,20);small=ImageFont.truetype(font,17);large=ImageFont.truetype(font,29)
for side,dirname,sha in [('before','before-20261127-081920','656a1ac2e5'),('after','after-20261127-082016','e7c6ac15f9')]:
 run=root/dirname
 if not (run/'summary.json').exists():continue
 lines=(run/'transcript.txt').read_text().splitlines()
 spans=[]
 for line in (run/'home/userdata/logs/server.trace.ndjson').read_text().splitlines():
  d=json.loads(line)
  if d.get('name') in ['TextGeneration.generateThreadTitle','ThreadTitleRegenerationService.execute']:
   spans.append({k:d[k] for k in ['name','traceId','spanId','parentSpanId','durationMs']}|{'exit':d['exit']['_tag']})
 thread=json.loads((run/'thread.json').read_text())['thread']
 report={'commit':lines[0].split('commit ')[1],'runtime':'Real T3 dev server, fresh database, Linux; public CLI -> MCP service','codexVersion':'0.172.0','prompt':'Fix the flaky login test','chat':{'provider':thread['providerInstanceId'],'model':thread['model'],'status':thread['status'],'title':thread['title']},'titleModel':'codex/gpt-6-luna','http403Requests':sum('HTTP POST' in x for x in lines),'titleGenerationAttempts':sum(x['name']=='TextGeneration.generateThreadTitle' for x in spans),'spans':spans,'transcript':lines}
 (root/(side+'-runtime.json')).write_text(json.dumps(report,indent=2))
 start=float(next(x.split('s ')[0] for x in lines if 'Replay Showcase' in x))
 duration=float(lines[-1].split('s ')[0])-start
 ev=[(max(0,float(x.split('s ')[0])-start),x.split('s ',1)[1]) for x in lines if float(x.split('s ')[0])>=start]
 def frame(t):
  im=Image.new('RGB',(1280,900),'#101820');d=ImageDraw.Draw(im)
  d.text((35,24),side.upper()+' | '+sha, font=large,fill='#f1f5f9')
  d.text((35,75),'REAL SERVER OUTPUT | timestamped runtime transcript',font=f,fill='#9baec3')
  d.text((35,110),'Chat: Replay / Showcase    Title: Codex / gpt-6-luna',font=f,fill='#9baec3')
  d.text((35,145),'Prompt: Fix the flaky login test',font=f,fill='white')
  n=sum('HTTP POST' in text for ts,text in ev if ts<=t)
  d.text((35,192),f'Elapsed: {t:05.1f}s     Refused HTTP requests: {n}',font=large,fill='#ffad66')
  visible=[(ts,text) for ts,text in ev if ts<=t]
  for i,(ts,text) in enumerate(visible[-23:]):d.text((35,245+24*i),f'{ts:05.2f}s  {text}',font=small,fill='#d4dfea')
  if t>=duration:
   d.text((35,825),f"Title-generation calls: {report['titleGenerationAttempts']} | Chat: completed | Title: New thread",font=f,fill='#a4e3b4')
  return im
 frame(duration).save(root/(side+'.png'))
 proc=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1280x900','-r','5','-i','-','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
 for n in range(int((duration+2)*5)+1):proc.stdin.write(frame(min(n/5,duration)).tobytes())
 proc.stdin.close();proc.wait()
