"""Drive the same real iOS linked-history failure and retry on either commit.
Args: state.json remote-home app-checkout output-directory session
The seed script writes state.json; all data is synthetic. Requires agent-device and Pillow.
"""
import json, os, pathlib, re, signal, subprocess, sys
from PIL import Image, ImageChops
state_path, remote_home, checkout, out_path, session = sys.argv[1:]
state = json.loads(pathlib.Path(state_path).read_text())
out = pathlib.Path(out_path)
out.mkdir(parents=True, exist_ok=False)

def call(*args):
    p = subprocess.run(['agent-device', *map(str,args), '--session', session], text=True, capture_output=True)
    if p.returncode:
        raise RuntimeError(p.stderr)
    return p.stdout

def stable(label):
    previous = out / (label+'-sample1.png')
    call('screenshot', previous)
    for n in range(2,5):
        current = out / (label+f'-sample{n}.png')
        call('screenshot', current)
        if ImageChops.difference(Image.open(previous).convert('RGB'), Image.open(current).convert('RGB')).getbbox() is None:
            Image.open(current).save(out / (label+'.png'))
            print(label+': consecutive captures have identical pixels', flush=True)
            return
        previous = current
    raise RuntimeError('Screen did not settle: '+label)

def top(): call('swipe',200,400,200,600,'--count',3,'--pause-ms',600)
def bottom(): call('swipe',200,650,200,350,'--count',3,'--pause-ms',600)

from urllib.parse import urlencode
call('open','com.t3tools.t3code.dev','t3code-dev://connections/new?'+urlencode({'pairingUrl':state['pairingUrl'],'autoConnect':'1'}))
call('wait','text','History reader',60000)
call('open','com.t3tools.t3code.dev',state['readerUrl'])
message=f'Agent: Read [Linked history](t3-thread://v2/{state["bId"]}/{state["history"]})'
call('press','role=button label='+json.dumps(message),'--settle')
call('press','role=link label="Linked history"','--settle')
call('wait','text','fixture turn complete',60000)
top()
call('wait','role=button label="Load earlier"',60000)
print('Opened linked history with Load earlier',flush=True)
call('record','start',out/'interaction.mp4','--fps',10,'--hide-touches')
runtime=json.loads((pathlib.Path(remote_home)/'userdata/server-runtime.json').read_text())
pid=runtime['pid']
port=runtime['origin'].rsplit(':',1)[1]
listeners=subprocess.check_output(['ss','-H','-ltnp',f'sport = :{port}'],text=True)
assert f'pid={pid},' in listeners
assert pathlib.Path(os.readlink(f'/proc/{pid}/cwd')).resolve()==pathlib.Path(checkout).resolve()
os.kill(pid,signal.SIGTERM)
print('Stopped only environment B; environment A remains online',flush=True)
bottom()
call('wait','text','is not answering',60000)
stable('connection-warning')
top()
call('press','role=button label="Load earlier"','--settle')
call('wait','role=button label="Load earlier" enabled=true',60000)
stable('failed-earlier-page')
print('Captured failed earlier-page request',flush=True)
bottom()
call('wait','text','is not answering',60000)
stable('retained-connection-warning')
top()
call('press','role=button label="Load earlier"')
call('wait','role=button label="Load earlier" enabled=true',60000)
call('record','stop')
print('Recorded retry and completion',flush=True)
