from PIL import Image,ImageDraw,ImageFont
import pathlib,textwrap,json,subprocess,re
root=pathlib.Path(__file__).parent/'run-2'
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side,sha in [('before','43ce39595b'),('after','1f05a4f712')]:
    final=(root/(side+'.txt')).read_text()
    def frame(text,caption):
        im=Image.new('RGB',(1600,1000),'#10141b');d=ImageDraw.Draw(im)
        d.text((30,22),f'{side.upper()} | {sha} | Real CLI output (paths redacted)',font=font,fill='#70c7ff')
        d.text((30,52),caption,font=font,fill='#9da8b6')
        y=95
        for line in text.splitlines():
            for wrap in textwrap.wrap(line,137,replace_whitespace=False) or ['']:
                d.text((30,y),wrap,font=font,fill='#ff9f9f' if 'EADDRINUSE' in wrap else '#dce5ef');y+=25
        return im
    frame(final,'Linux | no live database copied | seed disabled | existing listener 0.0.0.0:3773').save(root/(side+'.png'))
    events=json.loads((root/(side+'-timeline.json')).read_text())
    stamps=re.findall(r'\[(\d+):(\d+):(\d+\.\d+)\]',final.split('$ T3CODE_DEV_SEED=0')[-1])
    seconds=[int(h)*3600+int(m)*60+float(s) for h,m,s in stamps]
    logged_elapsed=(seconds[-1]-seconds[0]+1) if len(seconds)>1 else 0
    duration=max(events[-1][0] if events else 0,logged_elapsed)+4
    p=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','2','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
    for n in range(int(duration*2)+1):
        t=n/2; shown='Starting real dev:server process...'
        for stamp,txt in events:
            if stamp<=t:shown=txt
        if t>duration-3:shown=final
        p.stdin.write(frame(shown,f'Timed stdout capture | elapsed {t:.1f}s | inherited PORT=3773 HOST=0.0.0.0 LAN=true').tobytes())
    p.stdin.close();p.wait()
