import json, pathlib, subprocess, math, sys
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(sys.argv[1])
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',25)
for side in ['before','after']:
    candidates=sorted(root.glob(side+'-*/transcript.json'))
    source=candidates[-1]
    records=json.loads(source.read_text())
    # Replay the recorded stdout at its original timestamps; no generated app output.
    cast=[json.dumps({'version':2,'width':120,'height':34,'title':f'{side}: real T3 server settle observation'})]
    cast += [json.dumps([r['time'],'o',r['text']+'\r\n']) for r in records]
    (root/f'{side}.cast').write_text('\n'.join(cast)+'\n')
    (root/f'{side}.txt').write_text(source.with_name('transcript.txt').read_text())
    def frame(t):
        im=Image.new('RGB',(1440,960),'#11151c'); d=ImageDraw.Draw(im)
        d.text((32,24),f'{side.upper()} | Settle action terminal',font=title,fill='#f1f5fa')
        d.text((32,66),'Real Linux server / CLI output replayed at recorded timestamps',font=small,fill='#aebccc')
        d.text((32,92),'Fresh synthetic state | Replay (dev) agent | Bash slow prompt',font=small,fill='#aebccc')
        d.line((32,125,1408,125),fill='#364255',width=1)
        y=147
        for r in records:
            if r['time']>t: continue
            line=f"[{r['time']:05.1f}s] {r['text']}"
            color='#e1e7ee'
            if 'ALIVE' in line or ('RESULT:' in line and side=='before'):color='#ffb5a9'
            if 'EXITED' in line or ('RESULT:' in line and side=='after'):color='#a4e2bb'
            # Long SHA line fits at this viewport and font.
            d.text((32,y),line,font=font,fill=color);y+=27
        d.text((32,923),f'Elapsed: {t:05.1f}s | timestamped runtime transcript',font=small,fill='#aebccc')
        return im
    duration=math.ceil(records[-1]['time'])+3
    final=frame(duration);final.save(root/f'{side}.png')
    proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x960','-framerate','2','-i','pipe:0','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(root/f'{side}.mp4')],stdin=subprocess.PIPE)
    for n in range(duration*2):proc.stdin.write(frame(n/2).tobytes())
    proc.stdin.close()
    if proc.wait():raise RuntimeError('ffmpeg failed')
    frame(max(r['time'] for r in records if 'Beginning' in r['text'])+5).save(root/f'{side}-during.png')
    print(side,source.parent.name,'duration',duration)
