import argparse,base64,hashlib,json,os,pathlib,re,socket,subprocess,time,urllib.request,urllib.parse
p=argparse.ArgumentParser();p.add_argument('checkout');p.add_argument('side');p.add_argument('--output',required=True);a=p.parse_args()
out=pathlib.Path(a.output)/ (a.side+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir(parents=True)
s=socket.socket();s.bind(('127.0.0.1',0));port=s.getsockname()[1];s.close();origin=f'http://127.0.0.1:{port}'
log=open(out/'private-server.log','w+'); env=dict(os.environ,T3CODE_DEV_SEED='0')
proc=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(out/'data'),'--no-browser'],cwd=a.checkout,env=env,stdout=log,stderr=subprocess.STDOUT)
events=[];start=time.monotonic()
def record(label,value):
 events.append({'elapsed':round(time.monotonic()-start,3),'step':label,'response':value})
 print(label, json.dumps(value),flush=True)
def request(path,body,headers=None,form=False):
 data=urllib.parse.urlencode(body).encode() if form else json.dumps(body).encode()
 req=urllib.request.Request(origin+path,data,{'Content-Type':'application/x-www-form-urlencoded' if form else 'application/json',**(headers or {})})
 with urllib.request.urlopen(req,timeout=90) as r:
  raw=r.read().decode();h=dict(r.headers)
  if not raw:return None,h
  if raw.startswith('event:') or raw.startswith('data:'):
   raw=[l[6:] for l in raw.splitlines() if l.startswith('data: ')][-1]
  return json.loads(raw),h
try:
 for i in range(120):
  log.flush();log.seek(0);txt=log.read();m=re.search(r'^Token: (\S+)',txt,re.M)
  if m:break
  if proc.poll() is not None:raise RuntimeError('server exited')
  time.sleep(.5)
 else:raise RuntimeError('server startup timeout')
 sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=a.checkout,text=True).strip()
 record('Environment',{'commit':sha,'surface':'real Node server, loopback HTTP, fresh database','seed':'T3CODE_DEV_SEED=0'})
 redirect='http://localhost:51234/callback'
 reg,_=request('/oauth/mcp/register',{'client_name':'ChatGPT','redirect_uris':[redirect],'grant_types':['authorization_code','refresh_token'],'token_endpoint_auth_method':'none'})
 verifier='mcp-proof-'+'a'*60;challenge=base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
 auth={'response_type':'code','client_id':reg['client_id'],'redirect_uri':redirect,'code_challenge':challenge,'code_challenge_method':'S256','state':'proof','resource':origin+'/mcp'}
 decision,_=request('/oauth/mcp/decision',{'authorization':auth,'decision':{'_tag':'pairing-code','access':'full-access','code':m[1]}})
 code=urllib.parse.parse_qs(urllib.parse.urlparse(decision['redirectTo']).query)['code'][0]
 token,_=request('/oauth/mcp/token',{'grant_type':'authorization_code','code':code,'redirect_uri':redirect,'client_id':reg['client_id'],'code_verifier':verifier,'resource':origin+'/mcp'},form=True)
 record('OAuth public client + pairing approval + PKCE S256',{'client_name':'ChatGPT','access':'full-access','scope':token['scope'],'credentials':'omitted'})
 headers={'Authorization':'Bearer '+token['access_token'],'Accept':'application/json, text/event-stream'};seq=0
 def rpc(method,params=None,notification=False):
  global seq
  seq+=1;b={'jsonrpc':'2.0','method':method}
  if not notification:b['id']=seq
  if params is not None:b['params']=params
  result,h=request('/mcp',b,headers)
  if 'mcp-session-id' in {k.lower():v for k,v in h.items()}:headers['Mcp-Session-Id']={k.lower():v for k,v in h.items()}['mcp-session-id']
  return result
 init=rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'external-proof','version':'1.0'}});record('initialize',init)
 headers['Mcp-Protocol-Version']='2025-06-18';rpc('notifications/initialized',notification=True)
 listed=rpc('tools/list')['result']['tools'];names=[t['name'] for t in listed]
 record('tools/list',{'count':len(names),'issueTools':[n for n in names if 'issue' in n]})
 project=rpc('tools/call',{'name':'t3_project_create','arguments':{'title':'MCP issue proof','workspaceRoot':a.checkout}})
 if project.get('result',{}).get('isError'):record('project failure',project);raise RuntimeError('project failed')
 result=project['result'];structured=result.get('structuredContent')
 if structured is None:structured=json.loads(result['content'][0]['text'])
 projectId=structured['id'];record('t3_project_create',{'isError':result.get('isError',False),'title':structured.get('title'),'workspaceRoot':'<isolated GitHub checkout>'})
 for name,args in [('list_issues',{'projectId':projectId}),('read_issue',{'url':'https://github.com/pingdotgg/t3code/issues/44940','projectId':projectId}),('list_thread_issues',{})]:
  response=rpc('tools/call',{'name':name,'arguments':args});record(name,response)
finally:
 proc.terminate()
 try:proc.wait(timeout=15)
 except subprocess.TimeoutExpired:proc.kill();proc.wait()
 (out/'transcript.json').write_text(json.dumps(events,indent=2))
 print('OUTPUT',out)
