import subprocess,sys,time,json
from pathlib import Path
from PIL import Image,ImageChops
session,label=sys.argv[1:3]
out=Path(__file__).parent / "captures" / label
out.mkdir(parents=True,exist_ok=False)
last=None
for i in range(6):
 p=out/f"frame-{i}.png"
 subprocess.run(["agent-device","screenshot",str(p),"--normalize-status-bar","--session",session],check=True,stdout=subprocess.DEVNULL)
 im=Image.open(p).convert("RGB")
 if "ios" in session: im=im.crop((0,50,im.width,im.height))
 im.save(p)
 if last is not None and ImageChops.difference(last,im).getbbox() is None:
  final=out.parent/f"{label}.png";im.save(final)
  print(json.dumps({"label":label,"path":str(final),"identicalFrames":[i-1,i],"gapAtLeastMs":500}));break
 last=im
 time.sleep(.5)
else: raise SystemExit("Screenshots did not stabilize")
