from PIL import Image,ImageDraw,ImageFont
import pathlib,json,re,textwrap,subprocess
root=pathlib.Path(__file__).parent
run=sorted(p for p in root.iterdir() if p.is_dir())[-1]
def clean(s):
 return re.sub(r'<HOME>/wt/factory-issue-43575-evidence-2(?:-base)?','<WORKTREE>',s)
for p in run.glob('*.log'):p.write_text(clean(p.read_text()))
events=[[t,clean(s)] for t,s in json.loads((run/'events.json').read_text())]
(run/'events.json').write_text(json.dumps(events))
(run/'transcript.txt').write_text('\n'.join(s for t,s in events))
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side,sha in [('before','712f51f0a6'),('after','17dec469f8')]:
 begin=next(t for t,s in events if '=== '+side.upper() in s)
 end=next(t for t,s in events if f'[{side}] captured supervisors stopped' in s)
 seq=[(t-begin,s) for t,s in events if begin<=t<=end]
 def frame(t):
  im=Image.new('RGB',(1600,1000),'#10151e');d=ImageDraw.Draw(im)
  d.text((30,20),f'{side.upper()} | {sha} | Real dev:server command capture',font=font,fill='#ffffff')
  d.text((30,55),'Linux | Node v26.13.1 | T3CODE_DEV_SEED=0 | Fresh isolated SQLite state',font=small,fill='#a9b6cb')
  lines=[]
  for when,s in seq:
   if when<=t:
    if 'InterruptError' in s or 'WARN' in s:continue
    for line in s.splitlines():lines.extend(textwrap.wrap(line,125,replace_whitespace=False) or [''])
  for i,line in enumerate(lines[-30:]):
   color='#e8eaf0'
   if 'already' in line or 'Waiting for file' in line:color='#ffca85'
   if 'Listening on' in line:color='#8ee4b1'
   d.text((30,105+i*28),line,font=font,fill=color)
  d.text((30,963),f'Elapsed {t:05.1f}s | Paths redacted as <WORKTREE>; output otherwise unchanged',font=small,fill='#a9b6cb')
  return im
 p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1000','-r','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdin=subprocess.PIPE)
 for n in range(int((end-begin+3)*2)):p.stdin.write(frame(n/2).tobytes())
 p.stdin.close();p.wait()
 shot=next(t for t,s in seq if f'[{side}] after reload:' in s)
 frame(shot).save(root/(side+'.png'))
print(run)
