"""Setup used for the comparison. Arguments: head checkout, run directory.
Run from the head checkout with proof-driver.ts copied to apps/server/.
Servers are real T3 processes. Use the same completed B thread for both clients;
never regenerate its assistant response between captures.
"""
import pathlib, subprocess, json, urllib.request, sys, os
repo,run=map(pathlib.Path,sys.argv[1:]);run.mkdir(parents=True,exist_ok=True)
workspace=run/'search-demo';workspace.mkdir(exist_ok=True)
(workspace/'app.ts').write_text('export const answer = 42;\n// TODO tidy this up\n')
def cli(home,*args):
 return subprocess.check_output(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=repo,text=True)
def rpc(home,port,method,payload):
 return json.loads(subprocess.check_output(['node','apps/server/proof-driver.ts',str(home),f'http://127.0.0.1:{port}',method,json.dumps(payload)],cwd=repo,text=True))
def start(checkout,home,port,label):
 env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD':'0','T3CODE_ENVIRONMENT_LABEL':label}
 log=open(run/(home.name+'.log'),'w')
 proc=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','0.0.0.0','--port',str(port),'--base-dir',str(home),'--no-browser'],cwd=checkout,env=env,stdout=log,stderr=log)
 print('Server PID:',proc.pid)
 return proc
# Start B using start(repo, run/'source', 19451, 'On B'), wait for its runtime
# file, then execute source(). Keep the returned thread unchanged for both sides.
def source():
 home=run/'source'
 rpc(home,19451,'server.updateSettings',{'patch':{'linkedEnvironmentsEnabled':True,'providerInstances':{'opencode':{'driver':'opencode','enabled':True}}}})
 cli(home,'project','add',str(workspace),'--title','Search demo')
 return json.loads(cli(home,'thread','start',str(workspace),'Use the grep tool to search TODO in app.ts (use relative paths if possible), then use webfetch for https://example.com. Do not change files. Reply with one short sentence.','--title','Search demo','--provider','opencode','--model','anthropic/claude-sonnet-5-5','--wait','--json'))
def primary(home,port,source_thread):
 rpc(home,port,'server.updateSettings',{'patch':{'linkedEnvironmentsEnabled':True,'providerInstances':{'opencode':{'driver':'opencode','enabled':True}}}})
 b=run/'source';token=cli(b,'auth','session','issue','--token-only').strip()
 req=urllib.request.Request('http://127.0.0.1:19451/api/auth/pairing-token',data=json.dumps({'purpose':'peer-link','access':'full-access'}).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'})
 credential=json.load(urllib.request.urlopen(req))['credential']
 linked=rpc(home,port,'peerLinks.link',{'url':'http://127.0.0.1:19451','pairingCode':credential,'access':'full-access'})
 cli(home,'project','add',str(workspace),'--title','Linked search proof')
 message=f"Open [Search demo](t3-thread://v2/{linked['environmentId']}/{source_thread['threadId']}). Reply OK only."
 return json.loads(cli(home,'thread','start',str(workspace),message,'--title','Search comparison','--provider','opencode','--model','anthropic/claude-sonnet-5-5','--wait','--json'))
# For each checkout, start its own A (19452 base, 19453 head), call primary(),
# run its Metro on 8081 (stop the previous Metro by its captured PID), and install
# via `vp run mobile:install android --session SESSION --metro METRO_URL`.
# Pair only with that side's A using the repository pair-client.sh helper.
# Open the parent, expand its prompt, tap Search demo. Run capture.py from the
# linked sheet with both rows collapsed. Close the device session and terminate
# only the captured server/Metro processes after both captures.
