from PIL import Image,ImageDraw,ImageFont
import pathlib,json,textwrap,subprocess
p=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',15)
def clean(s,side):
 import re
 return re.sub(r'<workspace>/run-'+side+r'-\d+/data','<data>',s).replace('<workspace>/'+side+'/apps/server/dist/bin.mjs','<built-cli>')
def draw(lines,path,size=(1600,1600)):
 im=Image.new('RGB',size,'#10161f'); d=ImageDraw.Draw(im)
 y=22
 for line in lines:
  for part in textwrap.wrap(line.expandtabs(2),width=(size[0]-48)//11,replace_whitespace=False) or ['']:
   color='#76d9c5' if part.startswith(('$','STEP','BEFORE','AFTER')) else '#e2e8f0'
   d.text((24,y),part,font=font,fill=color); y+=23
 im.save(path)
for side,sha in [('base','226113fee0'),('head','bbb9088344')]:
 es=json.loads((p/(side+'.json')).read_text())
 title=('BEFORE' if side=='base' else 'AFTER')+' | '+sha
 header=[title,'macOS 26.6.2 / arm64 | built Node CLI | fresh isolated data','Captured output; private paths normalized to <data>, <home>, <built-cli>.','']
 lines=header.copy()
 for i in [4,5,7,8,9,10,11,12]:
  e=es[i]; lines+=['STEP '+e['step']]+clean(e['output'],side).strip().splitlines()+['']
 draw(lines,p/(side+'.png'))
 transcript='\n'.join(header)+'\n'
 cast=[json.dumps({'version':2,'width':140,'height':40,'title':title+' real CLI reproduction'})]; t=0
 for n,e in enumerate(es):
  text='\r\nSTEP '+e['step']+'\r\n$ '+clean(e['command'],side)+'\r\n'+clean(e['output'],side).replace('\n','\r\n')+'[exit '+str(e['exit'])+']\r\n'
  cast.append(json.dumps([t,'o',text])); t+=max(e['seconds'],0.01)
  transcript+='\nSTEP '+e['step']+'\n$ '+clean(e['command'],side)+'\n'+clean(e['output'],side)+'[exit '+str(e['exit'])+']\n'
  frame=header+['Paced replay of recorded command output','', 'STEP '+e['step'],'$ '+clean(e['command'],side),'']+clean(e['output'],side).strip().splitlines()+['','Exit: '+str(e['exit'])]
  draw(frame,p/(side+'-'+str(n)+'.png'),(1600,1000))
 (p/(side+'.cast')).write_text('\n'.join(cast)+'\n')
 (p/(side+'.txt')).write_text(transcript)
 (p/(side+'-frames.txt')).write_text(''.join("file '"+side+'-'+str(i)+".png'\nduration 4\n" for i in range(len(es)))+"file '"+side+'-'+str(len(es)-1)+".png'\n")
 subprocess.run(['ffmpeg','-y','-loglevel','error','-f','concat','-safe','0','-i',str(p/(side+'-frames.txt')),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p',str(p/(side+'.mp4'))],check=True)
