"""Render captured stdout timing to video; this does not simulate the application."""
import json,pathlib,re,subprocess,sys,textwrap,math
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(sys.argv[1])
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
big=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
for side in ['before','after']:
 dirs=sorted(root.glob(side+'-*'))
 folder=next(d for d in dirs if d.is_dir() and (d/'recording.cast').exists())
 dest=root/(side+'-public');dest.mkdir(exist_ok=True)
 def scrub(s):
  s=re.sub(r'bt-wf-[a-z0-9]+','[environment label redacted]',s)
  s=re.sub(r'/home/[^\s"\']+','[local path redacted]',s)
  s=re.sub(r'/tmp/factory-[^\s"\']+','[local path redacted]',s)
  return s
 for filename in ['recording.cast','server-output.txt','parent.json','child.json']:
  (dest/filename).write_text(scrub((folder/filename).read_text()))
 data=[json.loads(s) for s in (dest/'recording.cast').read_text().splitlines()]
 events=data[1:];duration=events[-1][0]; fps=4; speed=2
 rows=[];cursor=0;endframe=None
 proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1000','-r',str(fps),'-i','-','-an','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(dest/(side+'.mp4'))],stdin=subprocess.PIPE)
 for frame in range(math.ceil((duration/speed+3)*fps)):
  now=min(duration,frame/fps*speed)
  while cursor<len(events) and events[cursor][0]<=now:
   for line in events[cursor][2].splitlines():
    rows.extend(textwrap.wrap(line,148,replace_whitespace=False,drop_whitespace=False) or [''])
   cursor+=1
  im=Image.new('RGB',(1600,1000),'#10151d');draw=ImageDraw.Draw(im)
  draw.text((24,18),side.upper()+' | Real server stdout recording | 2x playback',font=big,fill='#f0f4f8')
  draw.text((24,53),f'OpenCode + T3 Connect staging | {now:.1f}s elapsed | terminal output, not a phone capture',font=font,fill='#b2c3d5')
  for n,line in enumerate(rows[-40:]):
   color='#f8cf74' if "statePhase:" in line else '#d2e2ef'
   draw.text((24,95+n*22),line,font=font,fill=color)
  proc.stdin.write(im.tobytes());endframe=im
 proc.stdin.close();assert proc.wait()==0
 # Static view retains the actual publish and its response in context.
 text=(dest/'server-output.txt').read_text();blocks=re.findall(r'\[.*?\] INFO .*?(?=\n\[|\nParent CLI|\nChild CLI|\nCapture ended|\Z)',text,re.S)
 selected=[]
 for block in blocks:
  if ('publishing agent activity for thread' in block or 'agent activity publish completed' in block):
   selected.append(block)
 lines=[]
 for b in selected:
  # Long ids remain in text evidence; omit them from the compact visual.
  for l in b.splitlines():
   if any(k in l for k in ['environmentId:', 'threadId:', 'projectId:']):continue
   lines.append(l)
 # Summarize using direct log excerpts only, splitting paired publishes into columns.
 im=Image.new('RGB',(1600,1000),'#10151d');draw=ImageDraw.Draw(im)
 draw.text((24,18),side.upper()+' | Remote delegated child: actual server log excerpts',font=big,fill='#f0f4f8')
 draw.text((24,56),('939b0f9e5e' if side=='before' else '0b6713358d')+' | Linux CLI/server | OpenCode | T3 Connect staging',font=font,fill='#b2c3d5')
 y=100
 for l in lines:
  if y>950:break
  draw.text((24,y),l,font=font,fill='#f8cf74' if 'statePhase:' in l else '#d2e2ef');y+=21
 im.save(dest/(side+'.png'))
 print(side,'duration',duration,'public',dest)
