#!/usr/bin/env python3
"""Render timestamped, allowlisted CLI output as a terminal transcript video at original speed."""
import pathlib,json,subprocess,html,sys,math
root=pathlib.Path(sys.argv[1])
for side in ['before','after']:
 name=side+'-4000';events=json.loads((root/(name+'.json')).read_text());frames=root/(name+'-frames');frames.mkdir(exist_ok=True)
 duration=math.ceil(events[-1][0])+3
 def render(t,target):
  lines=[f'{side.upper()} | 4,000 routes | elapsed {t:04.1f}s', 'Filtered real CLI transcript (credentials omitted)', 'Video replays captured event timing; no test runner', '']
  lines += [f'[{ts:06.3f}s] {s}' for ts,s in events if ts<=t]
  svg='<svg xmlns="http://www.w3.org/2000/svg" width="1440" height="720"><rect width="1440" height="720" fill="#10151c"/>'
  for i,line in enumerate(lines):
   color='#e7edf5'
   if 'Timeout' in line or 'Failed' in line:color='#ff8e8e'
   if 'configured' in line or 'applied=true' in line:color='#90e3ab'
   svg+=f'<text x="32" y="{40+i*34}" font-family="DejaVu Sans Mono" font-size="20" fill="{color}">{html.escape(line)}</text>'
  svg+='</svg>'
  subprocess.run(['convert','svg:-',str(target)],input=svg.encode(),check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
 for i in range(duration*2): render(i/2,frames/f'{i:04d}.png')
 render(duration,root/(name+'.png'))
 subprocess.run(['ffmpeg','-v','error','-y','-framerate','2','-i',str(frames/'%04d.png'),'-c:v','libx264','-pix_fmt','yuv420p','-r','30','-movflags','+faststart',str(root/(name+'.mp4'))],check=True)
 # A portable terminal recording containing the same exact allowlisted stream.
 with (root/(name+'.cast')).open('w') as f:
  f.write(json.dumps({'version':2,'width':120,'height':24,'title':side+' real T3 CLI (filtered)'})+'\n')
  for ts,s in events:f.write(json.dumps([ts,'o',s+'\r\n'])+'\n')
print(root)
