from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
import json,subprocess,sys,time
root=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side in ['before','after']:
 run=max((x for x in root.glob(side+'-*') if (x/'events.json').exists()),key=lambda x:x.stat().st_mtime)
 events=json.loads((run/'events.json').read_text());start=events[0][0];duration=events[-1][0]-start+3
 def frame(lines):
  img=Image.new('RGB',(1920,1080),'#101820');d=ImageDraw.Draw(img)
  for i,line in enumerate(lines):
   color='#e6edf3'
   if line.startswith(('Day ','RESULT:')):color='#ffc857'
   if 'authenticated=False' in line:color='#ff7b72'
   if 'authenticated=True' in line:color='#7ee787'
   d.text((24,18+i*23),line,font=font,fill=color)
  return img
 final=frame([x[1] for x in events]);final.save(root/(side+'.png'))
 process=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1920x1080','-framerate','10','-i','pipe:0','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
 for n in range(int(duration*10)+1):
  lines=[line for t,line in events if t-start<=n/10]
  process.stdin.write(frame(lines).tobytes())
 process.stdin.close();process.wait()
 (root/(side+'.txt')).write_text((run/'transcript.txt').read_text())
 print(side,run.name,len(events),duration)
