from PIL import Image,ImageDraw,ImageFont
import json,textwrap,subprocess
from pathlib import Path
root=Path(__file__).parent
run=sorted(root.glob('run-*'))[-1]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side,sha in [('before','d1b4b60d16'),('after','4acb38a34a')]:
 events=json.loads((run/(side+'-events.json')).read_text());lines=[];frames=[]
 for stamp,line in events:
  if line.startswith('Attempt '):lines=[]
  lines+=textwrap.wrap(f'[{stamp:7.3f}s] {line}',width=113,subsequent_indent='    ')
  im=Image.new('RGB',(1600,900),'#111820');d=ImageDraw.Draw(im)
  d.text((35,25),f'{side.upper()}  {sha}  |  Real t3 connect link — Linux x64',font=font,fill='#e4f1ff')
  d.text((35,65),'Timestamped CLI observation recording; waiting time compressed. SIGINT at activation.',font=small,fill='#a8bbc9')
  for j,l in enumerate(lines[-26:]):d.text((35,110+j*28),l,font=font,fill='#f3c67a' if '.tmp' in l else '#d6e4ec')
  frames.append(im)
 frames[-1].save(root/(side+'.png'))
 proc=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1600x900','-r','2','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
 for im in frames:
  for _ in range(2):proc.stdin.write(im.tobytes())
 for _ in range(6):proc.stdin.write(frames[-1].tobytes())
 proc.stdin.close();proc.wait()
 # Representative cancellation + retry frame from attempt 2.
 n=next(i for i,(t,s) in enumerate(events) if s.startswith('Attempt 3'))-1
 frames[n].save(root/(side+'-attempt2.png'))
