import subprocess,sys,time,json,datetime,re
from pathlib import Path
session,out=sys.argv[1:3]
key=sys.argv[3] if len(sys.argv)>3 else "c"
if key not in ("c","d"): raise ValueError("Use c or d")
root=Path(out); root.mkdir(parents=True,exist_ok=False)
log=[]
def run(*args):
 start=datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds")
 p=subprocess.run(["agent-device",*args,"--session",session],capture_output=True,text=True)
 log.append({"time":start,"action":list(args) if args[0]!="clipboard" else ["clipboard","write","70000 x characters"],"exit":p.returncode})
 (root/"actions.json").write_text(json.dumps(log,indent=2))
 print(start,args[0],p.returncode,flush=True)
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout
run("record","start",str(root/"interaction.mp4"),"--fps","10","--hide-touches")
run("type","status")
run("press",'label=send')
time.sleep(1)
run("clipboard","write","x"*70000)
run("longpress","170","240","--settle")
snapshot=run("snapshot","-i")
match=re.search(r'(@\S+) \[(?:cell|menu-item)\] "Paste"',snapshot)
if not match: raise RuntimeError("System Paste menu item unavailable")
run("press",match.group(1),"--settle")
run("type","queued")
run("press","label=CTRL")
run("type",key)
time.sleep(15)
run("screenshot",str(root/"15-seconds-after-interrupt.png"))
time.sleep(48)
if key=="c":
 run("type","status")
 run("press",'label=send')
time.sleep(2)
run("screenshot",str(root/"final.png"))
run("record","stop")
