import sys,json,pathlib,subprocess,math
sys.path.insert(0,str(pathlib.Path(__file__).parent/'python-deps'))
import pyte
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1]);font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
for side,sha in [('before','5b643a4913'),('after','ecbc32a78c')]:
  rows=(root/(side+'.cast')).read_text().splitlines();events=[json.loads(l) for l in rows[1:]]
  screen=pyte.Screen(120,32);stream=pyte.Stream(screen);idx=0;saved=False;duration=events[-1][0]+3;fps=5
  proc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1280x800','-r',str(fps),'-i','-','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
  for frame in range(math.ceil(duration*fps)):
    t=frame/fps
    while idx<len(events) and events[idx][0]<=t:
      stream.feed(("\x1b[2J\x1b[H" if "=== " in events[idx][2] else "")+events[idx][2]);idx+=1
    im=Image.new('RGB',(1280,800),'#10151e');d=ImageDraw.Draw(im)
    d.text((24,16),f'{side.upper()} | {sha} | Linux x64 | fresh HOME per case | PTY 120 x 32',font=font,fill='#7dd3fc')
    d.text((24,44),'Replay of recorded CLI output; n + Enter declines each offered installation.',font=font,fill='#a9b4c4')
    for y,line in enumerate(screen.display):d.text((24,85+y*21),line,font=font,fill='#e2e8f0')
    d.text((24,770),f'{t:05.1f}s / {duration:05.1f}s',font=font,fill='#a9b4c4')
    proc.stdin.write(im.tobytes())
    # A representative frame while the directory case's offer is visible, or its help on base.
    text='\n'.join(screen.display)
    if not saved and '=== Directory named t3 on PATH ===' in text and ('Observed: install offer ABSENT' in text or '? Install the t3 command?' in text):
      im.save(root/(side+'.png'));saved=True
  proc.stdin.close();assert proc.wait()==0
print('Rendered both terminal recordings.')
