from PIL import Image,ImageDraw,ImageFont
import json,sys,pathlib,textwrap,subprocess,math
root=pathlib.Path(sys.argv[1]); events=json.loads((root/'events.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
def draw(text,height=1080):
 im=Image.new('RGB',(1920,height),'#10151d');d=ImageDraw.Draw(im)
 d.text((44,24),'T3 Code | Recorded server runtime output (rendered stdout)',font=small,fill='#97aabe')
 d.line((44,66,1876,66),fill='#354355',width=2)
 lines=[]
 for line in text.splitlines():lines+=textwrap.wrap(line,129,replace_whitespace=False,drop_whitespace=False) or ['']
 lines=lines[-((height-110)//29):]
 for i,line in enumerate(lines):
  color='#e3e8ef'
  if 'not trusted' in line or 'SELF_SIGNED_CERT' in line:color='#ff8b8b'
  elif 'OK' in line:color='#94e5b1'
  d.text((44,91+i*29),line,font=font,fill=color)
 return im
# Preserve the complete first case, where the regression is visible, as a static companion.
text=(root/'transcript.txt').read_text().split('CASE: none')[0]
draw(text).save(root/'runtime.png')
# Render the driver's append-only stdout event recording at real time (2 fps).
end=events[-1]['seconds']+4
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1920x1080','-r','2','-i','-','-c:v','libx264','-preset','veryfast','-crf','23','-pix_fmt','yuv420p','-movflags','+faststart',str(root/'runtime.mp4')],stdin=subprocess.PIPE)
for n in range(math.ceil(end*2)):
 t=n/2
 text='\n'.join(e['text'] for e in events if e['seconds']<=t)
 p.stdin.write(draw(text).tobytes())
p.stdin.close();assert p.wait()==0
print(root/'runtime.png');print(root/'runtime.mp4')
