import pathlib,json,re,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent/'run-4'
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
W,H=1440,900
ansi=re.compile(r'\x1b\[[0-9;]*[a-zA-Z]')
def clean(s):return ansi.sub('',s).replace('\r','')
def frame(lines,title,footer):
 im=Image.new('RGB',(W,H),'#10151c');d=ImageDraw.Draw(im)
 d.text((28,20),title,font=font,fill='#70c5ff')
 d.text((28,54),'Debian 12 bookworm | amd64 | Node 24.23.0 | root | LC_ALL=fr_FR.UTF-8',font=small,fill='#b5bdc8')
 for i,l in enumerate(lines[-32:]):d.text((28,91+i*23),l,font=font,fill='#e5e9ef')
 d.text((28,H-33),footer,font=small,fill='#8fa1b5')
 return im
for side,sha in [('base','65002403cf'),('head','d984743b1a')]:
 title=('BEFORE' if side=='base' else 'AFTER')+' — '+sha+' — real CLI output'
 events=[json.loads(x) for x in (root/(side+'.cast')).read_text().splitlines()[1:]]
 proc=subprocess.Popen(['ffmpeg','-y','-f','rawvideo','-pixel_format','rgb24','-video_size',f'{W}x{H}','-framerate','4','-i','-','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
 buf='';last=0
 for t,_,data in events:
  n=max(1,min(8,round((t-last)*4/4)))
  for _ in range(n):proc.stdin.write(frame(textwrap.wrap(clean(buf).split('\n')[-1],112) if not buf else [part for line in clean(buf).splitlines() for part in textwrap.wrap(line,112) or ['']],title,'Terminal capture | 4x playback; idle gaps capped at 2 seconds').tobytes())
  buf+=data;last=t
 lines=[part for line in clean(buf).splitlines() for part in textwrap.wrap(line,112) or ['']]
 for _ in range(16):proc.stdin.write(frame(lines,title,'Terminal capture | 4x playback; idle gaps capped at 2 seconds').tobytes())
 proc.stdin.close();proc.wait()
 log=clean((root/(side+'.log')).read_text())
 selected=[]
 for line in log.splitlines():
  if any(s in line for s in ['Candidat','libasound2:', 'Installed:', 'Installé', '1.2.8-1+b1','Impossible de trouver','BrowserSetupStepError','setup exit=','Installed the browser','Google Chrome for Testing','browser exit=','=== After:', '=== Real CLI:']):
   selected.extend(textwrap.wrap(line,112) or [''])
 frame(selected,title,'Excerpt of captured stdout/stderr; complete transcript and terminal recording supplied.').save(root/(side+'.png'))
