"""Drive one side against its real server through the transparent history-delay proxy.
Usage: python mobile-capture-driver.py SIDE METRO_URL PRIVATE_SEED_JSON SESSION OUTPUT_DIR [PROXY_ORIGIN]
The private seed file is produced locally by mobile-workflow-proof-driver.ts; do not upload it.
"""
import json, subprocess, sys, time, urllib.parse, urllib.request
side, metro, seed_file, session, out = sys.argv[1:6]
seed = json.load(open(seed_file))
def device(*args, optional=False):
    result = subprocess.run(['agent-device', *args, '--session', session], capture_output=True, text=True)
    if result.returncode and not optional:
        raise RuntimeError(result.stderr)
    return result.stdout

def pair_and_open():
    device('open','com.t3tools.t3code.dev', 't3code-dev://expo-development-client/?'+urllib.parse.urlencode({'url':metro,'disableOnboarding':'1','disableFab':'1','disableAutoLaunch':'1'}))
    device('alert','accept',optional=True)
    device('wait','text','No threads yet','120000')
    # Bundling and initial pairing happen before the recorded reproduction.
    device('open','com.t3tools.t3code.dev','t3code-dev://connections/new?'+urllib.parse.urlencode({'pairingUrl':seed['pairingUrl'],'autoConnect':'1'}))
    device('alert','accept',optional=True)
    device('open','com.t3tools.t3code.dev',f"t3code-dev://workflows/{seed['environmentId']}/{seed['runId']}")
    device('wait','text','Ship the release?','60000')

def capture_transition(proxy_origin):
    device('press','role=button label="Ship"','--settle')
    device('record','start',f'{out}/mobile-{side}-proof.mp4','--scope','app','--hide-touches')
    device('fill','label="Reason for Ship the release?"','needs QA sign-off','--settle')
    for suffix in ['a','b']:
        time.sleep(.5)
        device('screenshot',f'{out}/mobile-{side}-before-{suffix}.png')
    urllib.request.urlopen(proxy_origin+'/release').read()
    device('wait','text','approval','15000')
    for suffix in ['a','b']:
        time.sleep(.5)
        device('screenshot',f'{out}/mobile-{side}-after-{suffix}.png')
    device('record','stop')

if __name__ == '__main__':
    if len(sys.argv) > 6:
        capture_transition(sys.argv[6])
    else:
        pair_and_open()
        print('Ready: run again with PROXY_ORIGIN to record the transition.')
