"""Render captured CLI transcripts and replay their recorded output as readable video."""
import json,pathlib,subprocess,sys,textwrap,time
from PIL import Image,ImageDraw,ImageFont
p=pathlib.Path(sys.argv[1]);font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
def wrapped(lines):
    return [part for line in lines for part in (textwrap.wrap(line,125,replace_whitespace=False,drop_whitespace=False) or [''])]
def render(lines,height=None):
    lines=wrapped(lines);height=height or (90+len(lines)*25)
    im=Image.new('RGB',(1440,height),'#10151e');d=ImageDraw.Draw(im)
    d.text((22,16),'T3 Code | Real CLI output capture | Paths normalized to /sandbox',font=font,fill='#93b7d8')
    maxlines=(height-70)//25
    for i,line in enumerate(lines[-maxlines:]):
        color='#dbe4ee'
        if line.startswith('CHECK'):color='#a9e5ba'
        if line.startswith('Left ') or 'exit: 127' in line:color='#ffab91'
        if line.startswith(('CASE:','$ ')):color='#8dcfff'
        d.text((22,62+i*25),line,font=font,fill=color)
    return im
for side in ['before','after']:
    lines=(p/f'{side}.txt').read_text().splitlines()
    first=lines[:lines.index('CASE: direct-with-PATH')-1]
    a=render(first,800);time.sleep(0.5);b=render(first,800);assert a.tobytes()==b.tobytes();b.save(p/f'{side}.png')
    third=lines[:2]+['']+lines[lines.index('CASE: recorded-only'):]
    a=render(third,800);time.sleep(0.5);b=render(third,800);assert a.tobytes()==b.tobytes();b.save(p/f'{side}-recorded.png')
    events=[json.loads(l) for l in (p/f'{side}.cast').read_text().splitlines()[1:]]
    proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1440x1000','-r','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(p/f'{side}.mp4')],stdin=subprocess.PIPE)
    screen=[]
    for event in events:
        screen.extend(event[2].replace('\r','').rstrip('\n').split('\n'))
        frame=render(screen,1000).tobytes()
        repeats=3 if screen[-1].startswith(('CASE:','uninstall exit:','launcher exit:')) else 1
        for _ in range(repeats):proc.stdin.write(frame)
    for _ in range(6):proc.stdin.write(frame)
    proc.stdin.close();assert proc.wait()==0
print(str(p))
