# Render the timestamped real-server terminal recording, with no inferred events.
import json, pathlib, subprocess, html, math, sys
root=pathlib.Path(sys.argv[1])
for side,sha in [('before','43915a4064b341cd040f24c1b906d87222e403de'),('after','dde45b95b3a04f9c77d8f2bd1f061b407067b56d')]:
    runs=sorted(p for p in root.glob(side+'-*') if p.is_dir())
    run=runs[-1]; events=json.loads((run/'events.json').read_text())
    frames=run/'frames';frames.mkdir(exist_ok=True)
    total=math.ceil(events[-1]['time'])+3
    for sec in range(total+1):
        shown=[e for e in events if e['time']<=sec]
        phase=shown[-1]['phase'] if shown else 'setup'
        counts={p:sum(e['phase']==p and e['message']=='SCAN /proc/net/tcp' for e in shown) for p in ['foreground','background','explicit-background','resumed']}
        text=[]
        def t(x,y,s,size=20,color='#dbe4ed'):
            text.append(f'<text x="{x}" y="{y}" fill="{color}" font-family="DejaVu Sans Mono" font-size="{size}">{html.escape(s)}</text>')
        t(38,48,side.upper()+' | '+sha[:10],28)
        t(38,84,'Linux | bundled real T3 server | fresh synthetic project + thread',18)
        t(38,114,'RPC-driven foreground state | retained discovery | real thread terminal',18)
        t(38,150,'Timestamped runtime recording; observer logs actual /proc listener-table reads.',16,'#9daebf')
        t(38,196,f'Time: {sec:02d}s    Phase: {phase}',24,'#7dd3fc')
        t(38,238,'Observed listener scans (one /proc/net/tcp read per scan):',18)
        t(38,274,'Foreground: '+str(counts['foreground'])+'   Background: '+str(counts['background'])+'   Explicit phase: '+str(counts['explicit-background'])+'   Resumed: '+str(counts['resumed']),20,'#facc15')
        # Show one line per scan instead of both IPv4/IPv6 reads. Raw cast retains both.
        lines=[e for e in shown if e['message']!='SCAN /proc/net/tcp6'][-14:]
        y=326
        import textwrap
        for e in lines:
            message=f"{e['time']:6.2f}s  "+e['message']
            for line in textwrap.wrap(message,108):
                t(38,y,line,17,'#86efac' if 'SCAN' in line else '#dbe4ed');y+=25
        t(38,775,'Observed output only. Browser visibility events and other clients are not exercised.',15,'#9daebf')
        svg='<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800"><rect width="1280" height="800" fill="#101820"/>'+''.join(text)+'</svg>'
        svgfile=frames/f'{sec:03d}.svg';svgfile.write_text(svg)
        subprocess.run(['convert',str(svgfile),str(frames/f'{sec:03d}.png')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    output=root/(side+'.mp4')
    subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','1','-i',str(frames/'%03d.png'),'-c:v','libx264','-r','10','-pix_fmt','yuv420p',str(output)],check=True)
    # Contact sheet from the actual encoded recording for visual inspection.
    subprocess.run(['ffmpeg','-y','-loglevel','error','-i',str(output),'-vf','fps=1/10,scale=640:400,tile=3x2','-frames:v','1',str(root/(side+'-review.png'))],check=True)
    (root/(side+'.cast')).write_bytes((run/'recording.cast').read_bytes())
    (root/(side+'-events.json')).write_bytes((run/'events.json').read_bytes())
