import sys,json,pathlib,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
sys.path.insert(0,str(pathlib.Path(__file__).parent/'python'))
import pyte
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
for side,sha in [('before','63e3dfc951'),('after','903a199b8d')]:
 folder=next(root.glob(side+'-*'))
 cast=[json.loads(l) for l in (folder/'terminal.cast').read_text().splitlines()][1:]
 events=json.loads((folder/'events.json').read_text())
 screen=pyte.Screen(120,32);stream=pyte.Stream(screen);idx=0
 width,height=1500,1120
 p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s',f'{width}x{height}','-r','10','-i','-','-an','-c:v','libx264','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
 for frame in range(190):
  t=frame/10
  while idx<len(cast) and cast[idx][0]<=t:
   stream.feed(cast[idx][2]);idx+=1
  im=Image.new('RGB',(width,height),'#10151e');d=ImageDraw.Draw(im)
  d.text((22,16),f'{side.upper()}  {sha}  | Linux / bash PTY / Codex 0.174.0 | elapsed {t:04.1f}s',font=small,fill='#e9f0fa')
  d.text((22,50),'Recorded real CLI output (private paths redacted):',font=small,fill='#93b7dc')
  for n,line in enumerate(screen.display):d.text((22,82+n*20),line,font=font,fill='#e0e5ed')
  d.line((20,736,1480,736),fill='#45607b')
  d.text((22,750),'Process observations from /proc (same clock as PTY recording):',font=small,fill='#93b7dc')
  lines=[]
  for et,msg in events:
   if et<=t:
    lines.extend(textwrap.wrap(f'{et:6.3f}s  {msg}',width=138))
  for n,line in enumerate(lines[-14:]):d.text((22,782+n*22),line,font=small,fill='#f3d48d' if 'RESULT' in line else '#e0e5ed')
  p.stdin.write(im.tobytes())
  if frame in [55,180]:im.save(root/(side+('-session.png' if frame==55 else '-result.png')))
 p.stdin.close();assert p.wait()==0
 print(side,'rendered')
