import pathlib,json,re,textwrap,subprocess,sys
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',15)
def frame(lines,title):
 im=Image.new('RGB',(1440,960),'#10151c'); d=ImageDraw.Draw(im)
 d.text((24,16),title,fill='#c4d5ee',font=font)
 d.line((24,46,1416,46),fill='#425064')
 for i,l in enumerate(lines[-39:]):
  color='#fca5a5' if any(s in l for s in ['Error:','FAIL','failed','File exists']) else '#d4dce8'
  d.text((24,62+i*22),l,fill=color,font=font)
 return im
for folder in sorted(root.glob(sys.argv[1]+'-*')):
 if not folder.is_dir():continue
 summaries=json.loads((folder/'summary.json').read_text())
 chosen=next((s['run'] for s in summaries if s['collision']),1)
 events=json.loads((folder/f'run-{chosen}.json').read_text())
 title=f'{sys.argv[1].upper()} | cold run {chosen} | Linux x86_64 | Electron 44.10.1 | command output replay (2x)'
 end=events[-1][0]+4
 p=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1440x960','-r','4','-i','-','-an','-c:v','libx264','-preset','fast','-crf','20','-pix_fmt','yuv420p',str(root/(sys.argv[1]+'.mp4'))],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
 lines=[]; pending=''; idx=0
 for k in range(int(end*2)+1):
  t=k*.5
  while idx<len(events) and events[idx][0]<=t:
   pending+=events[idx][1].replace('\r',''); idx+=1
   parts=pending.split('\n'); pending=parts.pop()
   for l in parts:lines.extend(textwrap.wrap(l,133,replace_whitespace=False,drop_whitespace=False) or [''])
  im=frame(lines+([pending] if pending else []),title)
  p.stdin.write(im.tobytes())
 p.stdin.close();p.wait()
 # The final terminal viewport includes the actual failure/success and exit status.
 frame(lines,title.replace('command output replay (2x)','final command output')).save(root/(sys.argv[1]+'.png'))
 # Preserve the earlier collision viewport as well.
 if sys.argv[1]=='base':
  all_lines=[]
  for _,s in events:
   for l in s.splitlines():all_lines.extend(textwrap.wrap(l,133,replace_whitespace=False,drop_whitespace=False) or [''])
  ix=next((i for i,l in enumerate(all_lines) if 'File exists (os error 17)' in l),None)
  if ix is not None:frame(all_lines[max(0,ix-12):ix+8],title.replace('command output replay (2x)','extraction collision output')).save(root/'base-collision.png')
