from PIL import Image,ImageDraw,ImageFont
import pathlib,json,textwrap,subprocess,time,hashlib
R=pathlib.Path(__file__).resolve().parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16)
for side,sha in [('before','35cc7724c5'),('after','24de5760cc')]:
 d=sorted(p for p in R.glob(side+'-*') if (p/'session.cast').exists())[-1]
 transcript=(d/'transcript.txt').read_text()
 # Display exact stdout, omitting only stack frames and empty lines for readable stills.
 lines=[]
 for l in transcript.splitlines():
  if l.startswith('    at ') or not l.strip():continue
  lines.extend(textwrap.wrap(l,110,replace_whitespace=False,drop_whitespace=False) or [''])
 title=f'{side.upper()} | {sha} | real CLI output (stack frames / QR omitted; tokens redacted)'
 def still():
  im=Image.new('RGB',(1140,100+22*len(lines)), '#10151c');dr=ImageDraw.Draw(im);dr.text((24,20),title,font=font,fill='#7dd3fc')
  for i,l in enumerate(lines):dr.text((24,70+i*22),l,font=font,fill='#e2e8f0')
  return im
 im=still();im.save(R/(side+'.png'));time.sleep(.5);assert im.tobytes()==still().tobytes()
 # Replay the timestamped captured stdout in a fixed terminal viewport.
 entries=[json.loads(l) for l in (d/'session.cast').read_text().splitlines()[1:]]
 duration=entries[-1][0]+3; fps=4;proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1140x960','-framerate',str(fps),'-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(R/(side+'.mp4'))],stdin=subprocess.PIPE)
 for n in range(int(duration*fps)):
  t=n/fps; ls=[]
  for e in entries:
   if e[0]<=t:
    for l in e[2].replace('\r','').splitlines():ls.extend(textwrap.wrap(l,110,replace_whitespace=False,drop_whitespace=False) or [''])
  frame=Image.new('RGB',(1140,960),'#10151c');dr=ImageDraw.Draw(frame);dr.text((24,18),f'{side.upper()} | {sha} | captured CLI stdout replay | {t:.1f}s',font=font,fill='#7dd3fc')
  for i,l in enumerate(ls[-39:]):dr.text((24,70+22*i),l,font=font,fill='#e2e8f0')
  proc.stdin.write(frame.tobytes())
 proc.stdin.close();assert proc.wait()==0
 (R/(side+'.txt')).write_text(transcript)
 (R/(side+'.cast')).write_text((d/'session.cast').read_text())
 print(side,d)
