import subprocess, pathlib, os, time, sys, hashlib, signal
root=pathlib.Path(__file__).parent; side=sys.argv[1]; checkout=sys.argv[2]; port=sys.argv[3]
done=root/(side+'-done'); transcript=root/(side+'-transcript.txt')
terminal_code="""import subprocess,pathlib,sys,os
with open(os.environ['PROOF_TRANSCRIPT'],'w') as f:
 p=subprocess.Popen([sys.executable,sys.argv[1],*sys.argv[2:]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 for line in p.stdout:
  print(line,end='',flush=True); f.write(line);f.flush()
 p.wait()
pathlib.Path(os.environ['PROOF_DONE']).touch()
input()
"""
env=dict(os.environ,PROOF_DONE=str(done),PROOF_TRANSCRIPT=str(transcript))
terminal=subprocess.Popen(['xterm','-geometry','150x43+0+0','-fa','Monospace','-fs','16','-bg','#10141b','-fg','#e2e8f0','+sb','-e','python3','-c',terminal_code,str(root/'drive.py'),side,checkout,port],env=env)
video=subprocess.Popen(['ffmpeg','-y','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-crf','23','-pix_fmt','yuv420p',str(root/(side+'.mp4'))],stdout=subprocess.DEVNULL,stderr=open(root/(side+'-ffmpeg.log'),'w'))
try:
 for i in range(300):
  if done.exists():break
  if terminal.poll() is not None:raise RuntimeError('terminal exited')
  time.sleep(1)
 else:raise RuntimeError('driver did not complete')
 # Capture the actual terminal once two frames 500 ms apart match.
 for i in range(10):
  subprocess.run(['import','-window','root',str(root/(side+'-a.png'))],check=True)
  time.sleep(.5)
  subprocess.run(['import','-window','root',str(root/(side+'.png'))],check=True)
  if (root/(side+'-a.png')).read_bytes()==(root/(side+'.png')).read_bytes():break
 else:raise RuntimeError('terminal did not settle')
 time.sleep(2)
finally:
 video.send_signal(signal.SIGINT); video.wait(timeout=20)
 terminal.terminate();terminal.wait(timeout=10)
