from PIL import Image,ImageDraw,ImageFont
import pathlib,json,sys,subprocess,textwrap
folder=pathlib.Path(sys.argv[1]); events=json.loads((folder/'terminal-recording.json').read_text()); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21); small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
width,height=1600,1000
lines=[]
def frame(elapsed):
 im=Image.new('RGB',(width,height),'#10151c'); d=ImageDraw.Draw(im)
 d.text((28,20),'T3 Code | real server / CLI evidence | '+sys.argv[2],font=font,fill='#e4ecf6')
 d.text((28,57),'Recorded stdout, rendered as a terminal. Synthetic data only. '+f'{elapsed:.1f}s',font=small,fill='#8fa4b9')
 d.line((28,88,width-28,88),fill='#40536a')
 for n,line in enumerate(lines[-28:]): d.text((28,110+n*30),line,font=font,fill='#b7e4c7' if 'RESULT' in line or 'copies' in line else '#dce5ef')
 return im
p=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pixel_format','rgb24','-video_size',f'{width}x{height}','-framerate','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(folder/'terminal-recording.mp4')],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
i=0; duration=events[-1]['seconds']+4
for tick in range(int(duration*2)+1):
 t=tick/2
 while i<len(events) and events[i]['seconds']<=t:
  lines.extend(textwrap.wrap(events[i]['line'],width=116,subsequent_indent='  ')); i+=1
 im=frame(t); p.stdin.write(im.tobytes())
p.stdin.close(); assert p.wait()==0
frame(duration).save(folder/'result.png')
