import json,sys,subprocess,pathlib,urllib.request,time,datetime,statistics
root=pathlib.Path(sys.argv[1]); side=sys.argv[2]; n=int(sys.argv[3]) if len(sys.argv)>3 else 36
out=pathlib.Path(__file__).parent/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));out.mkdir()
home=root/'.t3'
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=root,text=True,capture_output=True)
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout.strip()
fixture=out/'vscode-fixture';fixture.mkdir()
for args in [['init','-q','--initial-branch=main'],['-c','user.name=Evidence','-c','user.email=evidence@example.invalid','commit','--allow-empty','-qm','fixture'],['remote','add','origin','https://github.com/microsoft/vscode.git']]:subprocess.run(['git','-C',str(fixture),*args],check=True,capture_output=True)
cli('project','add',str(fixture),'--title','vscode-fixture')
thread=json.loads(cli('thread','start',str(fixture),'Start','--provider','devReplay','--model','showcase','--title','Issue link measurement','--json'))['threadId']
# Project id is read only from this isolated server's database, never inserted.
import sqlite3
with sqlite3.connect('file:'+str(home/'userdata/statev2.sqlite')+'?mode=ro',uri=True) as db:
 tables=[x[0] for x in db.execute("select name from sqlite_master where type='table'")]
 for tab in tables:
  if 'project' in tab.lower():
   cols=[x[1] for x in db.execute('pragma table_info('+tab+')')]
   if 'workspace_root' in cols:
    row=db.execute('select * from '+tab+' where workspace_root=?',(str(fixture),)).fetchone()
    if row: project=dict(zip(cols,row)).get('project_id') or dict(zip(cols,row)).get('id');break
origin=json.loads((home/'userdata/server-runtime.json').read_text())['origin'];token=None
for _ in range(200):
 if (home/'replay-session-private.json').exists():
  private=json.loads((home/'replay-session-private.json').read_text())
  if private['params']['cwd']==str(fixture):break
 time.sleep(.1)
else:raise RuntimeError('Replay session did not start')

servers=private['params']['mcpServers']
for server in servers:
 if server.get('name')=='t3-code':
  for e in server.get('env',[]):
   if e['name']=='T3_ACP_MCP_AUTHORIZATION':token=e['value'].removeprefix('Bearer ')
  for h in server.get('headers',[]):
   if h['name'].lower()=='authorization':token=h['value'].removeprefix('Bearer ')
headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream','Authorization':'Bearer '+token}
def rpc(method,params,id=1):
 data={'jsonrpc':'2.0','method':method,'params':params}
 if id is not None:data['id']=id
 req=urllib.request.Request(origin+'/mcp',data=json.dumps(data).encode(),headers=headers)
 with urllib.request.urlopen(req,timeout=90) as r:
  if r.headers.get('mcp-session-id'):headers['mcp-session-id']=r.headers['mcp-session-id']
  body=r.read().decode()
 if not body:return None
 if body.startswith('event:') or body.startswith('data:'):return json.loads([l[6:] for l in body.splitlines() if l.startswith('data: ')][-1])
 return json.loads(body)
rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'issue-link-evidence','version':'1'}})
headers['mcp-protocol-version']='2025-06-18';rpc('notifications/initialized',{},None)
rows=[]
measurementStart=time.time_ns()
for i in range(n):
 start=time.perf_counter();r=rpc('tools/call',{'name':'link_issue','arguments':{'threadId':thread,'projectId':project,'key':'56644'}},i+2);ms=(time.perf_counter()-start)*1000
 row={'run':i+1,'wallMs':round(ms,3),'response':r};rows.append(row)
 (out/'calls.json').write_text(json.dumps(rows,indent=2)); print(side,i+1,round(ms,2),json.dumps(r),flush=True)
 if r.get('error') or r.get('result',{}).get('isError'):break
# Export only relevant trace fields; no credentials, paths, hostnames or unrelated spans.
for _ in range(200):
 trace=home/'userdata/logs/server.trace.ndjson'
 spans=[json.loads(l) for f in [trace.with_name(trace.name+'.1'),trace] if f.exists() for l in f.read_text().splitlines()]
 if len([s for s in spans if s.get('name')=='mcp.tool.link_issue' and int(s['startTimeUnixNano'])>=measurementStart])>=len(rows):break
 time.sleep(.05)
links=[s for s in spans if s.get('name')=='mcp.tool.link_issue' and int(s['startTimeUnixNano'])>=measurementStart]; traces={s['traceId'] for s in links}
selected=[{k:s[k] for k in ['name','traceId','spanId','parentSpanId','durationMs','attributes','exit'] if k in s} for s in spans if s.get('traceId') in traces and (s.get('name')=='mcp.tool.link_issue' or 'github' in s.get('name','').lower())]
(out/'spans.json').write_text(json.dumps(selected,indent=2))
with sqlite3.connect('file:'+str(home/'userdata/statev2.sqlite')+'?mode=ro',uri=True) as db:
 for tab, in db.execute("select name from sqlite_master where type='table'"):
  cols=[x[1] for x in db.execute('pragma table_info('+tab+')')]
  if 'thread_id' in cols and 'payload_json' in cols and 'projection_threads' in tab:
   row=db.execute('select payload_json from '+tab+' where thread_id=?',(thread,)).fetchone()
   if row:
    shell=json.loads(row[0]);(out/'stored-link.json').write_text(json.dumps(shell.get('issues'),indent=2))
print('OUTPUT',out)
