import subprocess, sys, pathlib, threading, time
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(__file__).parent; side=sys.argv[2]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',27)
lines=[]; done=threading.Event(); directory=[]
p=subprocess.Popen([sys.executable,str(root/'driver.py'),*sys.argv[1:]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
def read():
    for line in p.stdout:
        if line.startswith('RUN_DIRECTORY='):directory.append(pathlib.Path(line.strip().split('=',1)[1]))
        else:lines.append(line.rstrip());print(line.rstrip(),flush=True)
    p.wait();done.set()
threading.Thread(target=read,daemon=True).start()
f=subprocess.Popen(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1100','-framerate','2','-i','-','-c:v','libx264','-preset','veryfast','-crf','23','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
def frame():
    im=Image.new('RGB',(1600,1100),'#111827');d=ImageDraw.Draw(im)
    d.text((32,22),f'{side.upper()} — real server lifecycle capture',font=title,fill='#f9fafb')
    d.text((32,65),'Issue #45905 | Linux | fresh data | real OpenCode 2.4.3 | 60-second observation',font=font,fill='#94a3b8')
    for i,line in enumerate(lines[-37:]):
        color='#f8fafc'
        if 'RUNNING' in line or 'STILL OPEN' in line or 'BUG REPRODUCED' in line:color='#fbbf24'
        elif 'EXITED' in line or 'EOF / closed' in line or 'FIX VERIFIED' in line:color='#4ade80'
        d.text((32,112+i*25),line,font=font,fill=color)
    return im
while not done.is_set():
    tick=time.monotonic();f.stdin.write(frame().tobytes());time.sleep(max(0,.5-(time.monotonic()-tick)))
for _ in range(4):f.stdin.write(frame().tobytes());time.sleep(.5)
f.stdin.close();f.wait()
im=frame();im.save(root/(side+'.png'));time.sleep(.5);second=frame();assert im.tobytes()==second.tobytes()
(root/(side+'-run.txt')).write_text(str(directory[0]) if directory else '')
sys.exit(p.returncode)
