"""Capture the real PR reference, follow it, and expose Safari's destination.
Run after pairing and opening the synthetic PR. Pass output directory, side, session.
The PR is expanded, then scrolled at its right edge to avoid the video player's gestures.
"""
import hashlib, json, pathlib, subprocess, sys, time
root, side, session = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3]
root.mkdir(parents=True, exist_ok=True)
def device(*args):
    value = subprocess.check_output(['agent-device',*args,'--session',session,'--json'],text=True)
    result=json.loads(value)
    if not result.get('success'): raise RuntimeError(result)
    return result['data']
def stable(label):
    previous=None
    for i in range(4):
        path=root/f'{side}-{label}-{i}.png'
        device('screenshot',str(path))
        digest=hashlib.sha256(path.read_bytes()).digest()
        if digest==previous:
            final=root/f'{side}-{label}.png'; final.write_bytes(path.read_bytes()); return str(final)
        previous=digest
        time.sleep(.5)
    raise RuntimeError('Screenshots did not stabilize')
# Both commits use the same 402 x 874 iPhone and light appearance.
nodes=device('snapshot','-i')['nodes']
expand=[n for n in nodes if n.get('label')=='Expand description']
if expand: device('press','@'+expand[0]['ref'])
device('swipe','390','700','390','350')
device('swipe','390','350','390','410')
app=stable('app')
nodes=device('snapshot','-i')['nodes']
reference=[n for n in nodes if n.get('label')=='docs'][-1]
device('record','start',str(root/f'{side}-follow-reference.mp4'),'--fps','10','--hide-touches')
try:
    device('press','@'+reference['ref'])
    # Foreground the Safari tab opened by the real link; no URL is supplied here.
    device('open','com.apple.mobilesafari','--foreground')
    # Safari's compact address bar is absent from its accessibility snapshot.
    device('press','201','818','--settle')
    nodes=device('snapshot','-i')['nodes']
    destination=[n.get('value') for n in nodes if n.get('label')=='Address']
    image=stable('destination')
    (root/f'{side}-observed.json').write_text(json.dumps({'destination':destination,'app':app,'capture':image},indent=2))
finally:
    device('record','stop')
