#!/usr/bin/env python3
"""Render captured CLI stdout as a terminal transcript and command/output replay.
Usage: python3 render.py RUN_DIRECTORY
This is a transcript visualization, not a desktop screen recording.
"""
import pathlib, sys, json, textwrap, subprocess, time, hashlib
from PIL import Image, ImageDraw, ImageFont
p=pathlib.Path(sys.argv[1]); events=json.loads((p/'events.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
def render(rows):
 im=Image.new('RGB',(1600,900),'#10141c'); d=ImageDraw.Draw(im)
 d.text((32,22),'Captured real CLI output • command/output replay',font=font,fill='#a3b7d7')
 y=76
 for line in rows:
  color='#88d8c0' if line.startswith('$') else '#e4e9f2'
  if line.startswith('exit 1') or line.startswith('No T3'): color='#ffb4a9'
  for s in textwrap.wrap(line,130,replace_whitespace=False,drop_whitespace=False) or ['']:
   d.text((32,y),s,font=font,fill=color); y+=27
 return im
final=render(events[-1]); final.save(p/'capture.png'); time.sleep(.5)
assert hashlib.sha256(final.tobytes()).digest()==hashlib.sha256(render(events[-1]).tobytes()).digest()
proc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x900','-framerate','4','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(p/'replay.mp4')],stdin=subprocess.PIPE)
# Hold each actual command and its corresponding result, then hold the final result.
for rows in events:
 if rows and (rows[-1].startswith('$') or rows[-1].startswith('exit ') or rows==events[-1]):
  frame=render(rows).tobytes()
  for _ in range(6 if rows!=events[-1] else 16): proc.stdin.write(frame)
proc.stdin.close(); assert proc.wait()==0
