import subprocess, sys, time
from pathlib import Path
from PIL import Image
session, output = sys.argv[1:]
path=Path(output)
ios='android' not in session

def capture(out):
    raw=out.with_name(out.stem+'-raw.png')
    command=['agent-device','screenshot',str(raw),'--session',session]
    if ios: command+=['--pixel-density','2']
    else: command+=['--normalize-status-bar']
    subprocess.run(command,check=True)
    image=Image.open(raw).convert('RGB')
    # Exclude the iOS system status bar, whose charging indicator animates.
    if ios: image=image.crop((0,48 if "ipad" in session else 120,image.width,image.height))
    image.save(out)
    return image.tobytes()

for attempt in range(6):
    first=path.with_name(path.stem+f'-stable-{attempt}.png')
    a=capture(first)
    time.sleep(.5)
    if a==capture(path):
        print('Two identical app frames at least 500 ms apart:',path.name)
        break
else: raise SystemExit('App did not stabilize')
