import sys, os, json, subprocess, time
from pathlib import Path
from datetime import datetime
from PIL import Image, ImageChops
session, runner, home, state, appdir, destination = sys.argv[1:]
out=Path(destination)/datetime.now().strftime("%Y%m%d-%H%M%S")
out.mkdir(parents=True)
def device(*args):
 p=subprocess.run(["agent-device",*args,"--session",session],text=True,capture_output=True)
 (out/"device.log").open("a").write(p.stdout+p.stderr)
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout
def press(selector):
 device("press",selector,"--settle")
def shot(label):
 device("wait","stable","500","15000")
 for n in range(4):
  first=out/f"{label}-{n}-a.png"; second=out/f"{label}-{n}-b.png"
  device("screenshot",str(first),"--normalize-status-bar")
  time.sleep(.5)
  device("screenshot",str(second),"--normalize-status-bar")
  if ImageChops.difference(Image.open(first).convert("RGB"),Image.open(second).convert("RGB")).getbbox() is None:
   target=out/f"{label}.png";target.write_bytes(second.read_bytes());return
 raise RuntimeError("Screen did not stabilize: "+label)
def turn(file):
 env={**os.environ,"T3_SCENARIO_APP_DIR":appdir}
 p=subprocess.run(["node",runner,"turn",home,state,file],env=env,text=True,capture_output=True)
 (out/"turns.log").open("a").write(p.stdout+p.stderr)
 if p.returncode: raise RuntimeError(p.stderr)
 device("wait","stable","1000","15000")
device("record","start",str(out/"interaction.mp4"),"--hide-touches")
try:
 press('label="Select diff"');press('text="Latest turn"')
 shot("01-latest-selected")
 press('label="Select diff"');shot("02-latest-menu-selected")
 press('text="Latest turn"')
 turn("two.txt");shot("03-latest-after-completion")
 press('label="Select diff"');shot("04-menu-after-completion")
 press('text="Turn"');shot("05-turn-submenu")
 press('text="Turn 3"');shot("06-explicit-newest-selected")
 turn("three.txt");shot("07-explicit-turn-after-completion")
 press('label="Select diff"');shot("08-explicit-menu-after-completion")
finally:
 device("record","stop")
print(out)
