import subprocess,sys,time,json,pathlib,textwrap
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
side,checkout,port=sys.argv[1:]
start=time.monotonic(); events=[]; output=''
p=subprocess.Popen(['node',str(root/'driver.mjs'),checkout,side,port],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
for line in p.stdout:
    if line.startswith('RUN_DIR='): continue
    output+=line;events.append((time.monotonic()-start,line));print(line,end='',flush=True)
code=p.wait()
if code: sys.exit(code)
(root/f'{side}.txt').write_text(output)
with (root/f'{side}.cast').open('w') as f:
    f.write(json.dumps({'version':2,'width':110,'height':40,'timestamp':int(time.time()),'title':f'{side}: real T3 CLI/MCP rename'})+'\n')
    for t,line in events:f.write(json.dumps([round(t,3),'o',line.replace('\n','\r\n')])+'\n')
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
def frame(text):
    im=Image.new('RGB',(1440,1080),'#10151e');d=ImageDraw.Draw(im)
    lines=[]
    for line in text.splitlines():lines.extend(textwrap.wrap(line,112,replace_whitespace=False,drop_whitespace=False) or [''])
    for i,line in enumerate(lines[-42:]):d.text((28,22+i*24),line,font=font,fill='#e4eaf2')
    return im
frame(output).save(root/f'{side}.png')
enc=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1440x1080','-r','5','-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p',str(root/f'{side}.mp4')],stdin=subprocess.PIPE)
for n in range(int((events[-1][0]+4)*5)):
    t=n/5;text=''.join(line for et,line in events if et<=t)
    enc.stdin.write(frame(text).tobytes())
enc.stdin.close();enc.wait()
