import pathlib,json,textwrap,subprocess,sys
root=pathlib.Path(sys.argv[1])
for side in ['before','after']:
 d=root/side;events=json.loads((d/'recording.json').read_text());frames=d/'frames';frames.mkdir(exist_ok=True)
 cast=[json.dumps({'version':2,'width':116,'height':48,'title':side+' CLI output (credentials redacted)'})]
 lines=['RECORDED CLI OUTPUT | credentials and server label redacted','Linux x64 | Node 26 | fresh synthetic state | fake tailscale CLI','']
 concat=[]
 for i,(t,s) in enumerate(events):
  cast.append(json.dumps([t,'o',s.replace('\n','\r\n')+'\r\n']))
  for line in s.splitlines():lines.extend(textwrap.wrap(line,112,replace_whitespace=False) or [''])
  txt=frames/f'{i:03}.txt';txt.write_text('\n'.join(lines))
  png=frames/f'{i:03}.png'
  subprocess.run(['convert','-size','1440x1000','xc:#101820','-font','DejaVu-Sans-Mono','-pointsize','19','-fill','#e6edf3','-gravity','NorthWest','-annotate','+26+26',txt.read_text(),str(png)],check=True)
  duration=max(.12,events[i+1][0]-t) if i+1<len(events) else 4
  concat.extend(["file '"+str(png)+"'",'duration '+str(duration)])
 concat.append("file '"+str(png)+"'")
 (d/'recording.cast').write_text('\n'.join(cast)+'\n');(d/'frames.txt').write_text('\n'.join(concat))
 subprocess.run(['ffmpeg','-v','error','-y','-f','concat','-safe','0','-i',str(d/'frames.txt'),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(root/(side+'.mp4'))],check=True)
 subprocess.run(['cp',str(png),str(root/(side+'.png'))],check=True)
