from PIL import Image,ImageDraw,ImageFont
import pathlib,json,textwrap,subprocess
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
for side,folder in [('before','base-final'),('after','head-capture')]:
    events=json.loads((root/folder/'events.json').read_text())
    def frame(t):
        im=Image.new('RGB',(1440,800),'#111827'); d=ImageDraw.Draw(im)
        d.text((28,20),'T3 Code CLI | captured output timeline | '+side.upper(),font=font,fill='#93c5fd')
        lines=[]
        for e in events:
            if e['seconds']<=t:
                for line in e['text'].splitlines():lines.extend(textwrap.wrap(line,112) or [''])
        for i,line in enumerate(lines):d.text((28,68+i*29),line,font=font,fill='#e5e7eb')
        d.text((28,755),'Linux / isolated loopback / fresh synthetic data / bundled real server',font=font,fill='#9ca3af')
        return im
    final=frame(1e9); final.save(root/(side+'.png'))
    duration=max(8,events[-1]['seconds']+3)
    p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x800','-framerate','10','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
    for n in range(int(duration*10)):p.stdin.write(frame(n/10).tobytes())
    p.stdin.close();p.wait()
