import subprocess,os,sys,time,re
from pathlib import Path
scratch=Path(__file__).parent
side,checkout,port,sha=sys.argv[1:]
out=scratch/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir()
pair=subprocess.run(['node','apps/server/src/bin.ts','pair','--base-dir',checkout+'/.t3'],cwd=checkout,capture_output=True,text=True,check=True)
m=re.search(r'token=([A-Z0-9]+)',pair.stdout)
if not m:raise RuntimeError('Pair command returned no pairing link')
env=os.environ.copy();env['PAIRING_TOKEN']=m.group(1)
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',env['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-crf','0','-pix_fmt','yuv420p',str(out/'recording.mp4')])
try:
 terminal=subprocess.Popen(['gnome-terminal','--wait','--geometry=150x49+0+0','--zoom=1.15','--title=Branch refresh evidence','--','node',str(scratch/'driver.mjs'),'http://127.0.0.1:'+port,str(scratch/(side+'-repo-v3')),side,sha,str(out)],env=env)
 code=terminal.wait(timeout=150)
 time.sleep(1)
finally:
 video.send_signal(2);video.wait(timeout=15)
subprocess.run(['ffmpeg','-y','-loglevel','error','-sseof','-4','-i',str(out/'recording.mp4'),'-frames:v','1',str(out/'summary.png')],check=True)
print('Recording directory:',out,'exit:',code)
