#!/usr/bin/env python3
"""Render recorded CLI stdout as readable pages, preserving all output.
The .cast files retain original timing; the MP4 holds each page for reading.
Usage: python3 render.py RUN_DIRECTORY SIDE COMMIT
"""
import pathlib,sys,html,textwrap,subprocess
run=pathlib.Path(sys.argv[1]); side=sys.argv[2]; sha=sys.argv[3]
text=(run/'transcript.txt').read_text(); sections=text.split('\n$ ')
pages=[]
for i,section in enumerate(sections):
    if i: section='$ '+section
    lines=[]
    for line in section.splitlines():
        lines.extend(textwrap.wrap(line, width=116,replace_whitespace=False,drop_whitespace=False) or [''])
    for offset in range(0,len(lines),28):pages.append(lines[offset:offset+28])
for i,lines in enumerate(pages):
    svg=['<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1000"><rect width="1600" height="1000" fill="#111827"/>']
    def t(x,y,s,c,size):svg.append(f'<text x="{x}" y="{y}" fill="{c}" font-family="DejaVu Sans Mono" font-size="{size}">{html.escape(s)}</text>')
    t(36,48,f'{side.upper()} | {sha} | Shared-home CLI', '#93c5fd',26)
    t(36,84,'Linux x86_64 | fresh synthetic HOME | PID/network/UTS-isolated owner', '#cbd5e1',19)
    t(36,116,'Built app stdout capture | paths redacted | reading-paced replay; original timing in .cast', '#94a3b8',17)
    for j,line in enumerate(lines):t(36,168+j*27,line,'#e5e7eb',21)
    t(36,966,f'Page {i+1}/{len(pages)} | Synthetic hostname: evidence-host-a | No live service changed', '#94a3b8',18)
    svg.append('</svg>'); (run/f'page-{i}.svg').write_text(''.join(svg))
    subprocess.run(['convert','-background','#111827',str(run/f'page-{i}.svg'),str(run/f'page-{i}.png')],check=True)
with (run/'frames.txt').open('w') as f:
    for i in range(len(pages)):
        f.write(f"file 'page-{i}.png'\nduration 9\n")
    f.write(f"file 'page-{len(pages)-1}.png'\n")
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','concat','-safe','0','-i',str(run/'frames.txt'),'-vf','fps=10,format=yuv420p','-c:v','libx264','-preset','fast','-crf','20','-movflags','+faststart',str(run/(side+'.mp4'))],check=True)
print(str(run),len(pages))
