import subprocess, sys, time
from pathlib import Path
from PIL import Image, ImageChops
session, side, out = sys.argv[1:]
out=Path(out)
def ad(*args):
    result=subprocess.run(['agent-device',*args,'--session',session],text=True,capture_output=True,check=True)
    return result.stdout

def still(label):
    # Compare two captures taken at least 500ms apart before accepting the still.
    a=out/f'{side}-{label}-check.png'
    b=out/f'{side}-{label}.png'
    for attempt in range(20):
        ad('screenshot',str(a))
        time.sleep(.5)
        ad('screenshot',str(b))
        if ImageChops.difference(Image.open(a).convert('RGB'), Image.open(b).convert('RGB')).getbbox() is None: return
    raise RuntimeError('Screen did not stabilize: '+label)

ad('record','start',str(out/f'{side}-replacement.mp4'),'--fps','10','--hide-touches')
ad('longpress','150','297','800')
ad('press','role=button label="Diff options"','--settle')
ad('press','label="Move draft to this line"','--settle')
still('first-editor')
ad('press','role=button label="Cancel"','--settle')
tree=ad('snapshot','-i')
has_hint='Select a current line' in tree
ad('longpress','150','342' if has_hint else '293','800')
ad('press','role=button label="Diff options"','--settle')
still('second-menu')
ad('press','label="Move draft to this line"' if has_hint else 'label="Add review comment"','--settle')
still('second-editor')
print(ad('snapshot','-i'),flush=True)
ad('record','stop')
