from pathlib import Path
import json,re,datetime,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
root=Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
bold=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',27)
for side,runname,sha in [('base','base-20261127T002211','7068f984530af138a9e755cc7058e20919ba2a81'),('head','head-20261127T002326','43257eb61a20571f96a6819a6d46f3574169c2ed')]:
 run=root/runname; out=root/('public-'+side);out.mkdir(exist_ok=True)
 events=[]; selected=[]
 def add(ts,text): events.append((ts,text))
 f=next((run/'data/userdata/logs/provider').glob('*delegated*'))
 for line in f.read_text().splitlines():
  ts=line[1:25];d=json.loads(line.split('NTIVE: ',1)[1]);p=d.get('event',{}).get('payload',{});t=p.get('type'); st=p.get('subtype')
  if t=='query.open': add(ts,'child query.open (claude-haiku-5-5)')
  elif t=='query.close':add(ts,'T3 -> child query.close')
  elif t=='system' and st=='init':add(ts,'Claude system init (turn starts)')
  elif t=='system' and st=='task_started':add(ts,'Bash background task_started')
  elif t=='system' and st=='status' and p.get('status')=='requesting':add(ts,'Claude status requesting')
  elif t=='system' and st=='task_notification':add(ts,'task_notification: completed (exit 0)')
  elif t=='assistant':
   content=p.get('message',{}).get('content',[])
   for c in content:
    if c['type']=='tool_use':
     if c['name']=='Bash':add(ts,'Bash: sleep 15; echo WAKE-TOKEN [background]');selected.append({'timestamp':ts,'type':'tool_use','name':'Bash','input':c.get('input')})
     elif 'background_wait' in c['name']:add(ts,'t3_background_wait registered');selected.append({'timestamp':ts,'type':'tool_use','name':'t3_background_wait','input':c.get('input')})
    elif c['type']=='text':
     text=c.get('text','');selected.append({'timestamp':ts,'type':'assistant','text':text})
     if text.strip()=='WAKE-TOKEN': add(ts,'child assistant: WAKE-TOKEN')
     elif text.startswith('one\n'):add(ts,f'child assistant: one ... one thousand ({len(text.splitlines())} lines)')
  elif t=='result':
   result=p.get('result','');add(ts,'result '+str(st)+(': WAKE-TOKEN' if result.strip()=='WAKE-TOKEN' else ': number list' if result.startswith('one\n') else ': '+result[:80])); selected.append({'timestamp':ts,'type':'result','subtype':st,'result':result,'is_error':p.get('is_error')})
 # Record release from real trace with only safe fields.
 for line in (run/'data/userdata/logs/server.trace.ndjson').read_text().splitlines():
  d=json.loads(line);a=d.get('attributes',{})
  if d.get('name')=='orchestrationV2.dispatch.once' and 'delegated-task-release' in a.get('orchestration_v2.command_id',''):
   ts=datetime.datetime.fromtimestamp(int(d['startTimeUnixNano'])/1e9,datetime.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00','Z')
   ordinal=re.search(r'ordinal:(\d+)',a['orchestration_v2.command_id']).group(1);add(ts,'T3 delegated-task-release (run '+ordinal+')')
 events.sort(); start=datetime.datetime.fromisoformat(events[0][0].replace('Z','+00:00'))
 def elapsed(ts):return (datetime.datetime.fromisoformat(ts.replace('Z','+00:00'))-start).total_seconds()
 parent=json.loads(sorted(run.glob('parent*.json'))[-1].read_text())
 msgs=[re.sub(r'thread:delegated-task:[\w%:-]+','<synthetic child thread>',m['text']) for m in parent['messages'] if m['role']=='assistant']
 transcript={'side':side,'commit':sha,'environment':'Linux x86_64; Claude Code 2.1.332; claude-haiku-5-5; real server and CLI; fresh database and one-commit synthetic repository','source':'Timestamped real provider protocol and server trace, allowlisted fields only; no mock/replay provider.','events':[{'timestamp':ts,'elapsedSeconds':elapsed(ts),'event':text} for ts,text in events],'providerMessages':selected,'parentAssistantMessages':msgs}
 (out/'runtime-transcript.json').write_text(json.dumps(transcript,indent=2)+'\n')
 lines=[f'{elapsed(ts):6.3f}s  {text}' for ts,text in events]
 (out/'runtime-transcript.txt').write_text(transcript['environment']+'\n'+sha+'\n\n'+'\n'.join(lines)+'\n\nPARENT ASSISTANT MESSAGES\n\n'+'\n\n'.join(msgs)+'\n')
 # A faithful timed visualization of recorded events, not a browser capture.
 # The real timestamps determine all frame durations.
 def render(n):
  im=Image.new('RGB',(1600,1100),'#10151d');dr=ImageDraw.Draw(im)
  dr.text((42,30),('BEFORE — BASE' if side=='base' else 'AFTER — FIX')+' | Real Claude runtime',font=bold,fill='#ffffff')
  dr.text((42,80),sha,font=font,fill='#98a8bd')
  dr.text((42,118),'Linux | Claude Code 2.1.332 | claude-haiku-5-5 | fresh isolated state',font=font,fill='#98a8bd')
  dr.text((42,156),'Recorded provider/server events, elapsed time from child query.open',font=font,fill='#98a8bd')
  y=210
  for row in lines[:n]:
   color='#8de9b1' if 'WAKE-TOKEN' in row and ('assistant:' in row or 'result success' in row) else '#ffac9c' if 'query.close' in row else '#e1e7f0'
   dr.text((42,y),row,font=font,fill=color);y+=32
  if n==len(lines):
   foot='Wake turn cut off; no WAKE-TOKEN assistant result.' if side=='base' else 'Wake turn returned WAKE-TOKEN before query.close; parent received it.'
   dr.text((42,1020),foot,font=font,fill='#ffac9c' if side=='base' else '#8de9b1')
  return im
 concat=[]
 for n in range(1,len(lines)+1):
  imagepath=out/f'frame-{n:03d}.png';render(n).save(imagepath)
  duration=max(.04,(elapsed(events[n][0])-elapsed(events[n-1][0]))) if n<len(events) else 5
  concat.extend([f"file '{imagepath}'",f'duration {duration:.6f}'])
 concat.append(f"file '{imagepath}'")
 (out/'frames.txt').write_text('\n'.join(concat)+'\n');render(len(lines)).save(out/'timeline.png')
 subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-y','-f','concat','-safe','0','-i',str(out/'frames.txt'),'-vf','fps=20','-c:v','libx264','-preset','fast','-pix_fmt','yuv420p','-movflags','+faststart',str(out/'event-recording.mp4')],check=True)
 print(side,len(lines),'events',elapsed(events[-1][0]),'seconds',flush=True)
