import pathlib,json,textwrap,subprocess,math,sys
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).resolve().parent
run=pathlib.Path(sys.argv[1])
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side in ['before','after']:
    out=run/side; events=json.loads((out/'events.json').read_text());sha=json.loads((out/'result.json').read_text())['sha']
    def lines(es):
        result=[]
        for e in es:
            result+=['[%6.2fs] '%e['seconds']]+[w for l in e['text'].splitlines() for w in (textwrap.wrap(l,116,replace_whitespace=False,drop_whitespace=False) or [''])]+['']
        return result
    def draw(ls,h,scroll=False):
        im=Image.new('RGB',(1600,h),'#111820');d=ImageDraw.Draw(im)
        d.text((30,20),side.upper()+' | Linux source CLI | '+sha[:10],font=font,fill='#f2f5f8')
        d.text((30,55),'Actual command output; isolated paths redacted. Timestamped transcript replay.',font=small,fill='#aab9c8')
        if scroll:ls=ls[-31:]
        for n,l in enumerate(ls):
            color='#dce5ed'
            if 'ENOENT' in l or 'MISSING' in l:color='#ff9393'
            if '200 OK' in l:color='#8be6ab'
            if l.startswith('$'):color='#91c6ff'
            d.text((30,105+n*27),l,font=font,fill=color)
        return im
    all_lines=lines(events);im=draw(all_lines,145+27*len(all_lines));im.save(out/'capture.png')
    duration=math.ceil(events[-1]['seconds'])+4
    p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','2','-i','pipe:0','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(out/'capture.mp4')],stdin=subprocess.PIPE)
    for i in range(duration*2):p.stdin.write(draw(lines([e for e in events if e['seconds']<=i/2]),1000,True).tobytes())
    p.stdin.close();p.wait()
print(run)
