import pathlib,json,sys,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
large=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
for cast in root.glob('run-*/*.cast'):
    rows=[json.loads(x) for x in cast.read_text().splitlines()][1:]
    title=cast.stem.replace('-',' / ')
    proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x900','-framerate','2','-i','-','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(cast.with_suffix('.mp4'))],stdin=subprocess.PIPE)
    for frame in range(169):
        now=frame/2; im=Image.new('RGB',(1440,900),'#101820');d=ImageDraw.Draw(im)
        d.text((28,20),'T3 Code | process group metrics | '+title,fill='#eef4ff',font=large)
        d.text((28,60),f'Linux x64 | built server CLI | fresh isolated home | elapsed {now:05.1f}s',fill='#a9c3da',font=font)
        d.text((28,90),'Real-time replay of recorded server logs and local OTLP receiver output (1x)',fill='#a9c3da',font=font)
        lines=[]
        for tm,_,msg in rows:
            if tm<=now:
                for line in textwrap.wrap(msg.strip(),width=126,subsequent_indent='    '):lines.append(line)
        for i,line in enumerate(lines[-32:]):
            color='#ffcb77' if 'WARN' in line or 'cause' in line else '#9ce5b1' if 'OTLP' in line or 'recovered' in line else '#e0e7ef'
            d.text((28,140+i*22),line,fill=color,font=font)
        proc.stdin.write(im.tobytes())
    proc.stdin.close();proc.wait();im.save(cast.with_suffix('.png'))
    print(cast.with_suffix('.mp4'))
