#!/usr/bin/env python3
"""Capture the real T3 MCP HTTP response; no schema helpers or test harness."""
import argparse, datetime, json, pathlib, subprocess, urllib.request
p=argparse.ArgumentParser()
p.add_argument('--checkout', required=True)
p.add_argument('--port', required=True, type=int)
p.add_argument('--side', required=True)
a=p.parse_args()
root=pathlib.Path(__file__).resolve().parent
out=root/(a.side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
out.mkdir()
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=a.checkout,text=True).strip()
token=subprocess.check_output(['node','apps/server/src/bin.ts','auth','session','issue','--base-dir',str(pathlib.Path(a.checkout)/'.t3'),'--subject','mcp-client','--token-only'],cwd=a.checkout,text=True).strip()
headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream','Authorization':'Bearer '+token}
transcript=[]
def rpc(method, params, id=None):
    body={'jsonrpc':'2.0','method':method,'params':params}
    if id is not None: body['id']=id
    req=urllib.request.Request(f'http://127.0.0.1:{a.port}/mcp',data=json.dumps(body).encode(),headers=headers)
    with urllib.request.urlopen(req, timeout=60) as r:
        data=r.read().decode()
        if r.headers.get('mcp-session-id'): headers['mcp-session-id']=r.headers['mcp-session-id']
        transcript.append({'request':body,'httpStatus':r.status,'response':data})
        if not data: return None
        if data.lstrip().startswith('{'): return json.loads(data)
        messages=[json.loads(line[6:]) for line in data.splitlines() if line.startswith('data: ')]
        return next((v for v in messages if v.get('id')==id),None)
init=rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'schema-evidence','version':'1.0'}},1)
headers['mcp-protocol-version']=init['result']['protocolVersion']
rpc('notifications/initialized',{})
response=rpc('tools/list',{},2)
tools=response['result']['tools']
violations=[]
def walk(v,path):
    if isinstance(v,dict):
        if 'enum' in v:
            for x in v['enum']:
                if not isinstance(x,str): violations.append({'path':path+'.enum','value':x})
        for k,x in v.items(): walk(x,path+'.'+k)
    elif isinstance(v,list):
        for i,x in enumerate(v): walk(x,path+f'[{i}]')
for tool in tools: walk(tool['inputSchema'],tool['name']+'.inputSchema')
theme=next(t for t in tools if t['name']=='t3_theme_set')
summary={'commit':sha,'surface':'Real T3 Code server / MCP HTTP','state':'Fresh isolated database; no imported user data','request':'initialize, notifications/initialized, tools/list','httpStatus':transcript[-1]['httpStatus'],'advertisedToolCount':len(tools),'themeVersion':theme['inputSchema']['properties']['theme']['properties']['version'],'nonStringEnums':violations}
(out/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
(out/'tools-list.json').write_text(json.dumps(response,indent=2)+'\n')
(out/'http-transcript.json').write_text(json.dumps(transcript,indent=2)+'\n')
print(str(out))
print(json.dumps(summary,indent=2))
