import subprocess, time, pathlib, sys, json
cli, cwd, output, label = sys.argv[1:]
out=pathlib.Path(output); out.mkdir(parents=True,exist_ok=True)
log=[]
def run(*args):
    start=time.monotonic()
    result=subprocess.run([cli,*args,'--session','proof40610'],cwd=cwd,text=True,capture_output=True)
    log.append({'seconds':round(time.monotonic()-epoch,3),'command':list(args),'exit':result.returncode})
    if result.returncode: raise RuntimeError(result.stderr)
    return result.stdout

def stable(name):
    run('screenshot',str(out/(name+'-check.png')))
    time.sleep(.5)
    run('screenshot',str(out/(name+'.png')))
    from PIL import Image,ImageChops
    identical=ImageChops.difference(Image.open(out/(name+'-check.png')),Image.open(out/(name+'.png'))).getbbox() is None
    log.append({'stable':name,'identical':identical})

epoch=time.monotonic()
try:
    run('record','start',str(out/(label+'.mp4')))
    stable('agent-has-control')
    time.sleep(2)
    run('find','Take control','click')
    time.sleep(4)
    stable('after-first-take-control')
    run('click','516','1008')
    time.sleep(4)
    stable('after-page-click')
    print(run('snapshot','-i'))
finally:
    run('record','stop')
    (out/'driver-log.json').write_text(json.dumps(log,indent=2))
