import pathlib,json,sys,subprocess,textwrap
run=pathlib.Path(sys.argv[1]);events=json.loads((run/'events.json').read_text())
header={'version':2,'width':112,'height':38,'title':'Self-update CLI verification — '+run.name.split('-')[0],'env':{'TERM':'xterm-256color'}}
with (run/'recording.cast').open('w') as f:
 f.write(json.dumps(header)+'\n')
 for t,line in events:f.write(json.dumps([t,'o',line.replace('\n','\r\n')+'\r\n'])+'\n')
lines=[];frames=[]
for i,(t,line) in enumerate(events):
 # Keep the recorded RPC response readable without losing its result.
 for l in line.splitlines():
  lines.extend(textwrap.wrap(l,110,replace_whitespace=False,drop_whitespace=False) or [''])
 txt=run/f'frame-{i:03}.txt';txt.write_text('\n'.join(lines[-35:]))
 png=run/f'frame-{i:03}.png'
 subprocess.run(['convert','-size','1500x1000','xc:#10151d','-font','DejaVu-Sans-Mono','-pointsize','21','-fill','#e2e8f0','-gravity','NorthWest','-annotate','+32+32',txt.read_text(),str(png)],check=True)
 duration=max(.5,(events[i+1][0]-t) if i+1<len(events) else 5)
 frames.append((png,duration))
concat=run/'frames.txt';concat.write_text(''.join("file '"+str(p)+"'\nduration "+str(d)+'\n' for p,d in frames)+"file '"+str(frames[-1][0])+"'\n")
subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(concat),'-vf','fps=10','-c:v','libx264','-preset','fast','-pix_fmt','yuv420p','-movflags','+faststart',str(run/'recording.mp4')],check=True)
import shutil
shutil.copyfile(frames[-1][0],run/'result.png')
