#!/usr/bin/env python3
"""Render the timestamped, allowlisted terminal output to MP4 without changing timing."""
import pathlib,json,subprocess,html,os
root=pathlib.Path(os.environ['EVIDENCE_ROOT'])
for side in ['before','after']:
 run=pathlib.Path((root/(side+'-final-path')).read_text());data=(run/'session.cast').read_text().splitlines();events=[json.loads(l) for l in data[1:]]
 frames=run/'frames';frames.mkdir(exist_ok=True);lines=[];concat=[]
 for i,e in enumerate(events):
  lines.extend(e[2].strip('\r\n').split('\r\n'))
  body=''.join('<text x="28" y="'+str(32+j*17)+'">'+html.escape(t)+'</text>' for j,t in enumerate(lines[-49:]))
  svg='<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="900"><rect width="1280" height="900" fill="#10151c"/><g font-family="DejaVu Sans Mono" font-size="15" fill="#eef3f8">'+body+'</g></svg>'
  (frames/(str(i)+'.svg')).write_text(svg);png=frames/(str(i)+'.png')
  subprocess.run(['convert',str(frames/(str(i)+'.svg')),str(png)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
  duration=max(.04,(events[i+1][0]-e[0]) if i+1<len(events) else 6)
  concat.extend(["file '"+str(png)+"'",'duration '+str(duration)])
 concat.append("file '"+str(png)+"'");(frames/'concat.txt').write_text('\n'.join(concat)+'\n')
 subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(frames/'concat.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],check=True)
 subprocess.run(['ffmpeg','-y','-v','error','-sseof','-1','-i',str(root/(side+'.mp4')),'-frames:v','1',str(root/(side+'-review.png'))],check=True)
