#!/usr/bin/env python3
"""Render the recorded real terminal byte stream, preserving original timings (5 fps)."""
import json,sys,pathlib,subprocess,pyte
from PIL import Image,ImageDraw,ImageFont
src=pathlib.Path(sys.argv[1]); rows=[json.loads(x) for x in src.read_text().splitlines()]; header=rows.pop(0)
screen=pyte.Screen(header['width'],header['height']); stream=pyte.Stream(screen)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
width,height=1440,1000
fps=5; duration=rows[-1][0]+2
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s',f'{width}x{height}','-r',str(fps),'-i','-','-an','-c:v','libx264','-preset','ultrafast','-crf','23','-pix_fmt','yuv420p',str(src.with_suffix('.mp4'))],stdin=subprocess.PIPE)
i=0; samples=[]; pending=False
for frame in range(int(duration*fps)+1):
    t=frame/fps
    while i<len(rows) and rows[i][0]<=t:
        stream.feed(rows[i][2]); pending=pending or 'RESULT:' in rows[i][2]; i+=1
    img=Image.new('RGB',(width,height),'#10151d'); draw=ImageDraw.Draw(img)
    draw.text((24,15),'T3 Code installer | real-time terminal capture | '+src.stem,font=font,fill='#8bc4ff')
    for y,line in enumerate(screen.display): draw.text((24,52+y*22),line,font=font,fill='#e4e9f0')
    p.stdin.write(img.tobytes())
    if pending:
        samples.append(img.resize((720,500))); pending=False
p.stdin.close(); assert p.wait()==0
sheet=Image.new('RGB',(720*3,500*((len(samples)+2)//3)),'#10151d')
for n,img in enumerate(samples): sheet.paste(img,((n%3)*720,(n//3)*500))
sheet.save(src.with_name(src.stem+'-inspection.jpg'))
print(src.with_suffix('.mp4'))
