"""Convert the timestamped, unedited client-console .cast recording to PNG/MP4.
No app screenshots are synthesized: these frames display the captured server-client console.
"""
import sys,json,pathlib,math,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
run=pathlib.Path(sys.argv[1]); records=[json.loads(s) for s in (run/'session.cast').read_text().splitlines()]
header=records.pop(0); events=[(r[0],r[2].rstrip('\r\n')) for r in records]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',24)
W,H=1600,1000
side=run.name.split('-')[0].upper(); sha=events[0][1].split(' | ')[-1]
def frame(t):
    img=Image.new('RGB',(W,H),'#101419'); d=ImageDraw.Draw(img)
    d.text((28,18),'T3 Code | Recorded real-server client console | '+side,font=title,fill='#f3f4f6')
    d.text((28,58),'Commit '+sha+' | Linux | fresh isolated state | default 4-worker pool',font=small,fill='#bac4d0')
    d.line((28,91,W-28,91),fill='#364152')
    lines=[]
    for when,text in events:
        if when>t: break
        lines.extend(textwrap.wrap(text,124,subsequent_indent='          ') or [''])
    for n,line in enumerate(lines[-29:]):
        color='#ffb4ab' if 'TIMEOUT' in line or 'timeout in' in line else '#dbe6f2'
        d.text((28,112+n*28),line,font=font,fill=color)
    d.line((28,H-53,W-28,H-53),fill='#364152')
    d.text((28,H-40),f'Elapsed {t:05.1f}s | Original timing; output captured from real HTTP / WebSocket requests',font=small,fill='#bac4d0')
    return img
# Capture the completed fourth cycle plus the bounded/blocked scan, before release.
critical=next(t for t,line in events if 'Release the stalled FUSE listing' in line)
# Static rendering of the recorded console at the pre-release endpoint.
frame(critical).save(run/'blocked-state.png')
frame(events[-1][0]).save(run/'recovered-state.png')
end=math.ceil(events[-1][0])+3
proc=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size',f'{W}x{H}','-framerate','1','-i','pipe:0','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p','-movflags','+faststart',str(run/'recording.mp4')],stdin=subprocess.PIPE)
for t in range(end): proc.stdin.write(frame(t).tobytes())
proc.stdin.close(); assert proc.wait()==0
# Public structured data excludes server-private response bodies, credentials and local paths.
r=json.loads((run/'results.json').read_text())
def public(x):
    if isinstance(x,list): return [public(v) for v in x]
    if isinstance(x,dict): return {k:public(v) for k,v in x.items() if k not in ['body','exit']}
    return x
(run/'public-results.json').write_text(json.dumps(public(r),indent=2))
print(str(run/'recording.mp4'))
