from PIL import Image,ImageDraw,ImageFont
import json,pathlib,sys,textwrap,subprocess
root=pathlib.Path(sys.argv[1]);events=json.loads((root/'run-1/events.json').read_text());results=json.loads((root/'run-1/observations.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21);title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',28)
for side,sha in [('base','31d95f850b'),('head','b8e7b8e723')]:
 timeline=[];offset=0;begin=None;active=None
 for t,s in events:
  if s.startswith('BEGIN '):
   active=s.split()[1].lower()
   if active==side:begin=t
  if active==side and begin is not None:
   timeline.append((offset+t-begin,s))
   if s.startswith('END '):offset+=t-begin;begin=None
 def frame(t):
  im=Image.new('RGB',(1440,1000),'#101820');d=ImageDraw.Draw(im)
  d.text((32,24),('BEFORE' if side=='base' else 'AFTER')+' | commit '+sha,fill='#ffffff',font=title)
  d.text((32,76),'Real CLI observation log | Linux x64 | agy 1.5.16',fill='#9fbed2',font=font)
  d.text((32,115),'T3-spawned ACP environment: AGY_CLI_DISABLE_AUTO_UPDATE='+('1' if side=='base' else 'true'),fill='#ffd479',font=font)
  d.text((32,154),'3 interactive PTY runs, 12s each; fresh HOME; HTTPS tunnel logger.',fill='#9fbed2',font=font)
  d.text((32,190),'Timestamped output replay; idle time preserved. No model tool executed (429).',fill='#9fbed2',font=font)
  lines=[]
  for et,s in timeline:
   if et<=t:
    for line in textwrap.wrap(f'{et:5.1f}s '+s,102,subsequent_indent='       '):lines.append(line)
  y=246
  for line in lines[-22:]:
   d.text((32,y),line,fill=('#ffcc82' if 'auto-updater' in line else '#e0e7ed'),font=font);y+=29
  if t>=offset:
   n=sum(any('auto-updater' in h for h in r['contacts']) for r in results if r['side']==side)
   d.rectangle((25,920,1415,983),fill='#223641');d.text((40,936),f'Completed: updater contacted in {n}/3 runs. '+('BUG OBSERVED' if n else 'OPT-OUT HONORED'),font=title,fill='#ffcc82' if n else '#9de3b2')
  return im
 frame(offset+1).save(root/(side+'.png'))
 cmd=['ffmpeg','-y','-f','rawvideo','-vcodec','rawvideo','-pix_fmt','rgb24','-s','1440x1000','-r','2','-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(root/(side+'.mp4'))]
 p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stderr=subprocess.DEVNULL)
 for i in range(int((offset+3)*2)):p.stdin.write(frame(i/2).tobytes())
 p.stdin.close();p.wait()
