#!/usr/bin/env python3
import argparse,os,pathlib,subprocess,urllib.parse
p=argparse.ArgumentParser();p.add_argument('side',choices=['before','after']);p.add_argument('--session',default='n1-32681');a=p.parse_args()
root=pathlib.Path(__file__).resolve().parent
repo='/home/user/wt/pr-32681-before' if a.side=='before' else '/home/user/wt/pr-32681'
port='15099' if a.side=='before' else '15735'
env=dict(os.environ,T3CODE_PORT=port)
r=subprocess.run(['node','apps/server/src/bin.ts','auth','pairing','create','--base-dir',str(root/a.side/'t3-home'),'--base-url','http://fs-75.tail131df4.ts.net:'+port,'--ttl','15m','--label','agent-mobile'],cwd=repo,env=env,text=True,capture_output=True,check=True)
url=next(line.removeprefix('Pair URL: ') for line in r.stdout.splitlines() if line.startswith('Pair URL: '))
link='t3code-dev://connections/new?'+urllib.parse.urlencode({'pairingUrl':url,'autoConnect':'1'})
# Keep the automation working directory at the one that owns this session.
subprocess.run(['agent-device','open','com.t3tools.t3code.dev',link,'--session',a.session],cwd='/home/user/wt/pr-32681',capture_output=True,text=True,check=True)
print('Opened existing pairing route with a fresh '+a.side+' credential; credential not logged.')
