import pathlib,json,re,textwrap,subprocess,sys
from PIL import Image,ImageDraw,ImageFont
# Usage: python3 render-captures.py <output-directory>
root=pathlib.Path(sys.argv[1])
r=sorted(root.glob('run-*'))[-1]
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',25)
ansi=re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')
def clean(s):
 s=ansi.sub('',s).replace('\r','')
 s=re.sub(r'https?://[^\s\x1b]+','[URL redacted]',s)
 s=re.sub(r'file:///[^\s)]+','[source path redacted]',s)
 s=re.sub(r'/(?:home|tmp)/[^\s\"\']+','[path redacted]',s)
 return s
for side,sha in [('before','d8f480add0'),('after','2ba29a90d8')]:
 for mode in ['login','startup']:
  name=side+'-'+mode; ev=json.loads((r/(name+'.json')).read_text())
  marker='T3 Connect' if mode=='login' else 'Authentication required.'
  cumulative=''; start=None
  for t,s in ev:
   cumulative+=s
   if marker in clean(cumulative): start=t;break
  if start is None: raise Exception(name+' missing marker')
  end=ev[-1][0]
  def frame(t):
   s=clean(''.join(s for et,s in ev if et<=t))
   # Capture begins at the sign-in prompt / pairing announcement; initialization is omitted.
   if marker in s:
    s=s[s.index(marker):]
   else:s='Waiting for '+('sign-in prompt...' if mode=='login' else 'pairing URL...')
   lines=[]
   for line in s.splitlines(): lines.extend(textwrap.wrap(line,125,replace_whitespace=False,drop_whitespace=False) or [''])
   im=Image.new('RGB',(1600,1060),'#10151c'); d=ImageDraw.Draw(im)
   d.text((30,20),side.upper()+' | '+sha+' | '+('t3 connect login' if mode=='login' else 't3 --port <free>'),font=titlefont,fill='#e6edf3')
   d.text((30,62),'Linux x86_64 | Bash login profile | fresh data | no DISPLAY/WAYLAND_DISPLAY',font=font,fill='#9caabd')
   d.text((30,90),'xdg-open absent; effective PATH ends in a regular file',font=font,fill='#9caabd')
   d.line((30,125,1570,125),fill='#3a4657')
   for i,line in enumerate(lines[-34:]):
    color='#e6edf3'
    if 'ENOTDIR' in line or 'Exit status: 1;' in line:color='#ff8c8c'
    if 'Could not open a browser' in line or 'browser auto-open unavailable' in line:color='#88e0ad'
    d.text((30,145+i*25),line,font=font,fill=color)
   d.text((30,1020),f'PTY output playback | URLs/paths redacted | elapsed {max(0,t-start):.1f}s',font=font,fill='#9caabd')
   return im
  # Last pre-cancellation frame captures the observed behavior, without shutdown noise.
  cutoff=next((t for t,s in ev if '[driver] CLI still' in s or '[driver] Server still' in s),end)
  # Include process exit for the base CLI; include liveness check for startup.
  stilltime=end if mode=='login' and side=='before' else cutoff
  im=frame(stilltime);im.save(root/(name+'.png'))
  # Verify a stable rendered output window 500ms apart before the still.
  if stilltime==cutoff and not (mode=='login' and side=='before'):
   a=frame(cutoff-.7);b=frame(cutoff-.2)
   # Footer changes only the elapsed timestamp; terminal body remains stable.
   assert a.crop((0,0,1600,1010)).tobytes()==b.crop((0,0,1600,1010)).tobytes(),name+' output not stable'
  video=root/(name+'.mp4')
  proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s','1600x1060','-r','5','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(video)],stdin=subprocess.PIPE)
  duration=end-start+2
  for i in range(int(duration*5)+1):proc.stdin.write(frame(min(start+i/5,end)).tobytes())
  proc.stdin.close();assert proc.wait()==0
  transcript=clean(''.join(s for _,s in ev));transcript=transcript[transcript.index(marker):]
  (root/(name+'.txt')).write_text('Linux x86_64; real source CLI; fresh isolated data; Bash login profile.\nxdg-open absent; effective PATH ends in a regular file; DISPLAY/WAYLAND_DISPLAY unset.\nCommit: '+sha+'\n\n'+transcript)
  print(name,'rendered',flush=True)
