"""Render timestamped, privacy-filtered real server stdout as terminal transcripts/videos.
Idle intervals are compressed; displayed times are the actual elapsed times.
Usage: python3 render.py RUN_DIRECTORY SIDE COMMIT
"""
import sys,json,re,pathlib,subprocess,textwrap
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(sys.argv[1]);side,sha=sys.argv[2:]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
allow=['Listening on http://127.0.0.1:18401','T3 Code server is ready.',
'Relay client process started; waiting for tunnel connection','Relay client tunnel connection registered',
'T3 Connect desired link reconciled on startup','T3 Connect managed tunnel recovery registered',
'T3 Connect is reachable from other devices.','Installing the pinned relay client',
'Relay client installed; moving the connector to it','Skipping an incompatible relay client on PATH',
'T3CODE_CLOUDFLARED_PATH must point to cloudflared 2026.10.3 or newer',
'Failed to install the pinned relay client','Could not install the pinned relay client','Relay client did not start after the update']
all_records=[]; full=[]
for case in ['path','override','managed']:
    events=json.loads((root/(case+'-events-private.json')).read_text())
    records=[];buffer='';seen=set()
    for stamp,chunk in events:
        buffer+=chunk
        while '\n' in buffer:
            line,buffer=buffer.split('\n',1)
            content=None
            if any(a in line for a in allow):
                content=re.sub(r'^.*?\): ', '', line)
                # Repeated registration details do not add evidence; keep the first.
                if 'tunnel connection registered' in content:
                    if 'registered' in seen: continue
                    seen.add('registered')
            elif re.match(r"\s*(source|version|previousVersion|minimumVersion): ",line): content=line.strip()
            elif re.match(r"\s*\{ version: '[0-9.]+',?",line):
                content='; '.join(re.findall(r"(?:previousVersion|version): '[0-9.]+'",line))
            if content:
                content=re.sub(r'\x1b\[[0-9;?]*[a-zA-Z]','',content)
                records.append((stamp,content))
    header=f'{side.upper()}  {sha[:10]}  |  {case.upper()}\nLinux x86_64 / Node CLI server / isolated fresh T3 state\nOfficial cloudflared 2026.9.3; stage relay; no production data\n'
    full.append(header+'\n'.join(f'[{t:07.3f}s] {v}' for t,v in records))
    all_records.append((case,header,records))
(root/'transcript.txt').write_text('\n\n'.join(full)+'\n')
video=root/(side+'.mp4')
proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1440x900','-r','5','-i','pipe:0','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(video)],stdin=subprocess.PIPE)
for case,header,records in all_records:
    lines=[]
    for index,(stamp,content) in enumerate([(0,'SERVER START'),*records]):
        lines.extend(textwrap.wrap(f'[{stamp:07.3f}s] {content}',width=100,subsequent_indent='             '))
        im=Image.new('RGB',(1440,900),'#10151d');d=ImageDraw.Draw(im)
        d.text((32,24),header,font=font,fill='#c1d7f0',spacing=10)
        d.text((32,144),'Real server stdout excerpt • elapsed times preserved • idle waits compressed',font=small,fill='#97a4b3')
        d.multiline_text((32,192),'\n'.join(lines[-22:]),font=font,fill='#e2e8f0',spacing=9)
        frames=10 if index==len(records) else 4
        for _ in range(frames):proc.stdin.write(im.tobytes())
    im.save(root/(case+'.png'))
proc.stdin.close();proc.wait()
print(video)
print((root/'transcript.txt').read_text())
