import os,sys,pathlib,subprocess,time,selectors,json,textwrap
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent;side,checkout=sys.argv[1:];out=root/(side+'-capture');out.mkdir(exist_ok=True)
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
lines=[];events=[];start=time.monotonic()
header=[f'Issue #40756 | {side.upper()} | {sha[:10]}','REAL T3 server + CLI | Linux | Codex 0.172.0 | fresh isolated state','Synthetic ChatGPT auth | local HTTPS mock returning fixed SSE reply','View: sanitized command output; runId omitted from display only.','']
def frame():
 im=Image.new('RGB',(1920,1080),'#10141c');d=ImageDraw.Draw(im)
 for i,line in enumerate(header+lines[-37:]):
  color='#d6dde8'
  if line.startswith('>'):color='#90caf9'
  elif '"status": "failed"' in line:color='#ff9696'
  elif '"status": "completed"' in line:color='#9ee6b0'
  d.text((28,22+i*24),line,font=font,fill=color)
 return im
video=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1920x1080','-r','2','-i','-','-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(out/(side+'.mp4'))],stdin=subprocess.PIPE)
p=subprocess.Popen(['python3','-u',str(root/'driver.py'),side,checkout],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
sel=selectors.DefaultSelector();sel.register(p.stdout,selectors.EVENT_READ);nextframe=start;raw=[]
while True:
 for key,_ in sel.select(timeout=.1):
  line=key.fileobj.readline()
  if not line:sel.unregister(key.fileobj);continue
  raw.append(line)
  if line.startswith('RUN '):(out/'run-path.txt').write_text(line.strip()[4:]);continue
  clean=line.replace(str(root),'<isolated-state>')
  events.append([round(time.monotonic()-start,3),'o',clean.replace('\n','\r\n')])
  for l in clean.rstrip('\n').splitlines():lines.extend(textwrap.wrap(l,180,replace_whitespace=False,drop_whitespace=False) or [''])
  print(clean,end='',flush=True)
 if time.monotonic()>=nextframe:
  video.stdin.write(frame().tobytes());nextframe+=.5
 if p.poll() is not None and not sel.get_map():break
for i in range(6):video.stdin.write(frame().tobytes())
video.stdin.close();video.wait();frame().save(out/(side+'.png'))
(out/(side+'.cast')).write_text('\n'.join([json.dumps({'version':2,'width':180,'height':43,'timestamp':int(time.time()),'title':f'Issue 40756 {side} {sha[:10]}','env':{'TERM':'xterm-256color'}})]+[json.dumps(e) for e in events])+'\n')
(out/(side+'.txt')).write_text('\n'.join(header)+''.join(e[2].replace('\r\n','\n') for e in events))
print('Recording complete:',p.returncode,flush=True)
