import pathlib,textwrap,subprocess,json
r=pathlib.Path(__file__).parent
for side in ['before','after']:
 p=r/(side+'-final')
 def render(text,file):
  wrapped='\n'.join(y for x in text.splitlines() for y in (textwrap.wrap(x,104,replace_whitespace=False,drop_whitespace=False) or ['']))
  subprocess.run(['convert','-background','#10151f','-fill','#e6edf3','-font','DejaVu-Sans-Mono','-pointsize','18','-interline-spacing','4','label:'+wrapped.replace('\\','\\\\').replace('%','%%'),'-bordercolor','#10151f','-border','24',str(file)],check=True)
 render(side.upper()+' — recorded server responses (formatted transcript)\n\n'+(p/'transcript.txt').read_text(),p/(side+'.png'))
 # Render the actual timestamped terminal capture into a scrollback video.
 events=[json.loads(x) for x in (p/'session.cast').read_text().splitlines()[1:]]
 offset=events[0][0]; current=''; frames=[]
 for i,event in enumerate(events):
  current+=event[2].replace('\r','')
  frame=p/('frame-%03d.png'%i)
  render(side.upper()+' / real MCP output recording\n'+ '\n'.join(current.splitlines()[-42:]),frame)
  # Normalize dimensions so terminal scrolling doesn't resize the video.
  subprocess.run(['convert',str(frame),'-gravity','NorthWest','-background','#10151f','-extent','1200x1200',str(frame)],check=True)
  duration=max(.3,events[i+1][0]-event[0]) if i+1<len(events) else 4
  frames+=['file '+str(frame),'duration '+str(duration)]
 (p/'frames.txt').write_text('\n'.join(frames)+'\n')
 subprocess.run(['ffmpeg','-loglevel','error','-y','-f','concat','-safe','0','-i',str(p/'frames.txt'),'-vf','fps=10,format=yuv420p','-c:v','libx264','-movflags','+faststart',str(p/(side+'.mp4'))],check=True)
