import json,ast,sys,pathlib,textwrap,subprocess
from PIL import Image,ImageDraw,ImageFont
folder=pathlib.Path(sys.argv[1]);side=sys.argv[2];speed=8
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
lines=[json.loads(x) for x in (folder/'session.cast').read_text().splitlines()];events=[]
def tasklines(ts):
 result=[]
 for i,t in enumerate(ts):
  p=t.get('prompt','');label=('READY' if p.startswith('Reply with exactly READY') else 'B' if p.startswith('Reply with exactly: NOTED') else 'A2' if 'echo BUILD2-DONE' in p else 'A (control)' if 'echo BUILD-DONE' in p else 'EXTRA WAKE TASK')
  result.append(f"  {label:17} {t.get('status',''):10} {t.get('result') or '(pending)'}")
 return result
for e in lines[1:]:
 tm,_,text=e;text=text.strip().replace('\r','')
 if text.startswith('{'):
  try:r=json.loads(text)
  except: r=ast.literal_eval(text)
  text='CLI reply: '+(r.get('reply') or r.get('status') or '')
  if 'READY' in text:text='CLI: initial delegation completed; child replied READY.'
  else:text='CLI: parent sent follow-up. '+('SENT' if 'SENT' in text else text[:200])
 elif ': [' in text and text.split(': [',1)[0] in ['control-completed','B-completed-before-wake','final-tasks']:
  label,raw=text.split(': ',1);text=label+'\n'+'\n'.join(tasklines(json.loads(raw)))
 elif text.startswith('Results: '):continue
 events.append((tm,text))
# Text shown is a readable projection of the captured CLI transcript; original cast accompanies video.
duration=events[-1][0];fps=4;frames=int(duration/speed*fps)+12
proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x900','-framerate',str(fps),'-i','-','-an','-c:v','libx264','-preset','fast','-crf','21','-pix_fmt','yuv420p',str(folder/'runtime.mp4')],stdin=subprocess.PIPE)
for n in range(frames):
 tm=min(duration,n/fps*speed);visible=[]
 for et,txt in events:
  if et>tm:break
  visible.extend(textwrap.wrap(txt,115,replace_whitespace=False) if '\n' not in txt else [v for line in txt.split('\n') for v in (textwrap.wrap(line,115,replace_whitespace=False) or [''])])
 im=Image.new('RGB',(1600,900),'#10151d');d=ImageDraw.Draw(im)
 d.text((36,26),'Issue 46127 | '+side.upper()+' | real server / Claude Agent',font=font,fill='#fafafa')
 d.text((36,66),f'Captured runtime transcript | replay at 8x | elapsed {int(tm)//60:02}:{int(tm)%60:02}',font=small,fill='#9baec6')
 for j,line in enumerate(visible[-26:]):
  color='#f6c76c' if ('STARTED' in line or 'EXTRA WAKE TASK' in line) else '#b9ead2' if 'FINAL REPORT' in line else '#d7dfeb'
  d.text((36,112+j*28),line,font=font,fill=color)
 proc.stdin.write(im.tobytes())
 if n==frames-1:im.save(folder/'final.png')
proc.stdin.close();assert proc.wait()==0
(folder/'readable-transcript.txt').write_text('\n\n'.join(f'[{tm:.3f}s] {text}' for tm,text in events)+'\n')
