from PIL import Image,ImageDraw,ImageFont
import pathlib,json,textwrap,subprocess,sys
root=pathlib.Path(sys.argv[1]); font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21); small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
for side in ['before','after']:
 events=json.loads((root/(side+'.json')).read_text()); frames=root/(side+'-frames');frames.mkdir(exist_ok=True)
 for i,(t,txt) in enumerate(events):
  img=Image.new('RGB',(1600,1000),'#111827');d=ImageDraw.Draw(img)
  d.text((35,22),side.upper()+' — Real CLI capture | Linux | Tailscale Serve + T3 dev --share',font=font,fill='#f9fafb')
  d.text((35,62),'Recorded command output; tailnet hostname and worktree path redacted.',font=small,fill='#9ca3af')
  # Keep current lifecycle stage and initial context visible.
  context=events[0][1]+'\n\n'+txt
  if 'AFTER DEV STOPS' in txt:
   context=events[0][1]+'\n\n'+next(e[1] for e in events if e[1].startswith('WHILE DEV RUNS'))+'\n\n$ SIGINT to dev process group\n\n'+txt
  lines=[]
  for line in context.splitlines():lines+=textwrap.wrap(line,112,replace_whitespace=False,drop_whitespace=False) or ['']
  for n,line in enumerate(lines[:31]):d.text((35,115+26*n),line,font=font,fill='#d1fae5' if 'OTHER-APP' in line else '#e5e7eb')
  d.text((35,955),'Stage '+str(i+1)+'/'+str(len(events))+' | elapsed '+str(t)+'s',font=small,fill='#9ca3af')
  img.save(frames/(str(i)+'.png'))
  if 'AFTER DEV STOPS' in txt:img.save(root/(side+'.png'))
 manifest=''
 for i in range(len(events)):
  duration = max(1, events[i+1][0]-events[i][0]) if i+1 < len(events) else 6
  manifest+=f"file '{frames/str(i)}.png'\nduration {duration}\n"
 manifest+=f"file '{frames/str(len(events)-1)}.png'\n"
 (root/(side+'-frames.txt')).write_text(manifest)
 subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(root/(side+'-frames.txt')),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],check=True)
