#!/usr/bin/env python3
"""Drive an isolated running T3 development server; credentials stay in memory.
Usage: drive.py CHECKOUT PORT PROJECT_ID SELECTION_JSON TITLE
SELECTION_JSON is private runtime configuration and is not part of evidence.
"""
import json,subprocess,sys,urllib.request
from pathlib import Path
checkout,port,project,selection,title=sys.argv[1:]
token=subprocess.check_output(['node','apps/server/src/bin.ts','auth','session','issue','--base-dir','.t3','--subject','mcp-client','--ttl','2h','--label','evidence driver','--token-only'],cwd=checkout,text=True).strip()
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json','Accept':'application/json, text/event-stream'}
def call(method,params,ident=1):
 data=json.dumps({'jsonrpc':'2.0','id':ident,'method':method,'params':params}).encode()
 req=urllib.request.Request(f'http://127.0.0.1:{port}/mcp',data,headers)
 response=urllib.request.urlopen(req)
 if response.headers.get('Mcp-Session-Id'):headers['Mcp-Session-Id']=response.headers['Mcp-Session-Id']
 body=response.read().decode()
 if body.startswith('event:') or body.startswith('data:'):
  body=next(line[6:] for line in body.splitlines() if line.startswith('data: '))
 return json.loads(body)
call('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'evidence-driver','version':'1'}})
headers['MCP-Protocol-Version']='2025-06-18'
result=call('tools/call',{'name':'t3_thread_launch','arguments':{'projectId':project,'title':title,'message':'Reply with READY only. Do not use tools.','modelSelection':json.loads(selection)}})
print(json.dumps(result))
