#!/usr/bin/env python3
"""Render captured terminal output; never invent app output."""
from PIL import Image,ImageDraw,ImageFont
import pathlib,json,re,textwrap,subprocess,sys
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
sha={'before':'2bc7878fff','after':'411cd90708'}
def render(text,title,height=None):
    lines=[]
    for line in text.splitlines():
        lines.extend(textwrap.wrap(line,148,replace_whitespace=False,drop_whitespace=False) or [''])
    if height: lines=lines[-((height-145)//23):]
    im=Image.new('RGB',(1600,height or max(540,155+len(lines)*23)), '#10151d'); d=ImageDraw.Draw(im)
    d.text((30,22),title,font=titlefont,fill='#f4f7fb')
    d.text((30,61),'Linux x86_64 | fresh synthetic data | real CLI/server output',font=font,fill='#9daebe')
    d.text((30,87),'$CASE = isolated scratch directory; $CHECKOUT = the side’s checkout',font=font,fill='#9daebe')
    for i,line in enumerate(lines):
        color='#d9e2ec'
        if line.startswith('===') or line.startswith('$ '): color='#8cbaff'
        elif 'ENOENT' in line or 'not found' in line or 'not installed' in line: color='#ff9696'
        elif 'FAKE CODEX STARTED' in line or 'available via PATH' in line or 'exit=0' in line: color='#92e3b0'
        d.text((30,130+i*23),line,font=font,fill=color)
    return im
for side in ['before','after']:
    text=(root/(side+'.txt')).read_text()
    # Keep command output; omit only stack frames and generic --help global flags in visual excerpts.
    short=re.sub(r'^\s+at .*\n','',text,flags=re.M)
    short=re.sub(r'GLOBAL FLAGS\n.*?(?=\nexit=)', '[Generic --help flags omitted; see complete transcript]\n',short,flags=re.S)
    first=short.index('=== T3 Connect'); second=short.index('=== Launcher discovery')
    for name,body in [('triage',short[:first]),('connect-hints',short[first:second]),('launchers',short[second:])]:
        render(body,f'{side.upper()} {sha[side]} — {name} — transcript excerpt').save(root/f'{name}-{side}.png')
    events=[json.loads(x) for x in (root/f'service-{side}.cast').read_text().splitlines()[1:]]
    render(''.join(e[2] for e in events),f'{side.upper()} {sha[side]} — real server trial commit').save(root/f'service-{side}.png')
# Render the actual timestamped terminal events at 5fps, retaining recorded timing.
for name in ['before','after','service-before','service-after']:
    events=[json.loads(x) for x in (root/f'{name}.cast').read_text().splitlines()[1:]]
    duration=events[-1][0]+2
    out=root/f'{name}.mp4'
    ff=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1400','-r','5','-i','-','-c:v','libx264','-preset','ultrafast','-crf','23','-pix_fmt','yuv420p',str(out)],stdin=subprocess.PIPE)
    current='';j=0
    for frame in range(int(duration*5)+1):
        while j<len(events) and events[j][0]<=frame/5:
            data=events[j][2]
            if '\x1b[2J\x1b[H' in data: current='';data=data.replace('\x1b[2J\x1b[H','')
            current+=data;j+=1
        im=render(current,f'{name} — recorded terminal output — {frame/5:.1f}s',1400)
        ff.stdin.write(im.tobytes())
    ff.stdin.close(); assert ff.wait()==0
    print(out)
