from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
import json, subprocess, textwrap
root=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
for side in ['before','after']:
    events=[json.loads(x) for x in (root/(side+'.cast')).read_text().splitlines()][1:]
    lines=[]; frames=[]
    for i,event in enumerate(events):
        lines.extend(event[2].strip().splitlines())
        im=Image.new('RGB',(1280,720),'#111827'); d=ImageDraw.Draw(im)
        d.text((32,25),side.upper()+' | Linux / Node 26.13.1 | real server MCP transcript',font=font,fill='#93c5fd')
        y=80
        for line in lines:
            for part in textwrap.wrap(line,100) or ['']:
                d.text((32,y),part,font=font,fill='#e5e7eb'); y+=29
        path=root/(side+f'-frame-{i}.png'); im.save(path)
        duration=(events[i+1][0]-event[0]) if i+1<len(events) else 4
        frames.append((path,max(.1,duration)))
    (root/(side+'.png')).write_bytes(frames[-1][0].read_bytes())
    manifest=root/(side+'-frames.txt')
    manifest.write_text(''.join(f"file '{p}'\nduration {dur}\n" for p,dur in frames)+f"file '{frames[-1][0]}'\n")
    subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(manifest),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],check=True)
