import subprocess, pathlib, sys, time, re
session, out = sys.argv[1:]
out = pathlib.Path(out); out.mkdir(parents=True, exist_ok=True)
def call(*args):
 r=subprocess.run(["agent-device",*args,"--session",session],capture_output=True,text=True)
 with (out/"driver.log").open("a") as f: f.write(" ".join(args)+"\n"+r.stdout+r.stderr)
 if r.returncode: raise RuntimeError(r.stderr)
 return r.stdout
def press(label): return call("press",'label="'+label+'"',"--settle")
def still(name):
 a=out/(name+"-settling.png"); b=out/(name+".png")
 call("screenshot",str(a))
 for _ in range(5):
  time.sleep(.5);call("screenshot",str(b))
  result=subprocess.run(["compare","-metric","AE",str(a),str(b),"null:"],capture_output=True,text=True)
  if result.returncode==0: return
  a.write_bytes(b.read_bytes())
 raise RuntimeError("Screenshot not stable: "+name)
call("record","start",str(out/"flow.mp4"),"--fps","10")
try:
 snapshot=call("snapshot","-i")
 if '"Open files"' not in snapshot:
  if '"main.c"' in snapshot: press("Back")
  else:
   ref=re.search(r'(@e[0-9]+).*"Encoding preview,',snapshot).group(1)
   call("press",ref,"--settle")
 for file in ["main.c","utf8.txt","gb18030.txt","binary.txt"]:
  press("Open files");press(file);still(file.replace(".","-"));press("Back")
 still("thread-after-files")
finally: call("record","stop")
