from PIL import Image,ImageDraw,ImageFont
from pathlib import Path
import json,sys,textwrap,subprocess
root=Path(sys.argv[1]); data=json.loads((root/'recording.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',21)
duration=data['durationSeconds']
def frame(t):
 im=Image.new('RGB',(1600,1000),'#11161d');d=ImageDraw.Draw(im)
 d.text((28,22),f"T3 Connect loopback authorization | {data['side'].upper()}",font=bold,fill='#ffffff')
 d.text((28,58),f'Linux interactive PTY | fresh data | test stage | no keys / no callback | elapsed {t:.1f}s',font=font,fill='#aab8c8')
 d.text((28,90),'Recording replay at 30x speed; final result held for reading. Authorization URL and paths redacted.',font=font,fill='#aab8c8')
 text=''.join(s for ts,s in data['events'] if ts<=t)
 lines=[]
 for line in text.splitlines():
  lines.extend(textwrap.wrap(line,145,replace_whitespace=False,drop_whitespace=False) or [''])
 if t>=duration: lines+=['',f"Elapsed: {duration:.3f} seconds; exit code: {data['exitCode']}"]
 for i,line in enumerate(lines[-37:]):
  color='#ffd27f' if 'Error' in line or 'Timed out' in line else '#d9e2ec'
  d.text((28,140+i*22),line,font=font,fill=color)
 return im
frame(duration).save(root/'result.png')
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1000','-r','10','-i','-','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(root/'recording.mp4')],stdin=subprocess.PIPE)
for i in range(int(duration/3)+1):p.stdin.write(frame(min(i*3,duration)).tobytes())
for i in range(80):p.stdin.write(frame(duration).tobytes())
p.stdin.close();assert p.wait()==0
