import json, subprocess, urllib.request, sys, pathlib, datetime

checkout, home, port, side, target = sys.argv[1:]
token = subprocess.check_output(['node','apps/server/src/issue-proof-session.ts',home],cwd=checkout,text=True).strip()
origin = 'http://127.0.0.1:'+port
headers = {'Authorization':'Bearer '+token,'Content-Type':'application/json','Accept':'application/json, text/event-stream'}
counter=0
def rpc(method, params):
    global counter
    counter+=1
    req=urllib.request.Request(origin+'/mcp',data=json.dumps({'jsonrpc':'2.0','id':counter,'method':method,'params':params}).encode(),headers=headers)
    with urllib.request.urlopen(req,timeout=90) as res:
        if res.headers.get('mcp-session-id'): headers['mcp-session-id']=res.headers['mcp-session-id']
        body=res.read().decode()
    try: return json.loads(body)
    except json.JSONDecodeError:
        return [json.loads(line[6:]) for line in body.splitlines() if line.startswith('data: ')][-1]
rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'model-option-proof','version':'1'}})
def call(name,args): return rpc('tools/call',{'name':name,'arguments':args})['result']
def data(result):
    if 'structuredContent' in result: return result['structuredContent']
    return json.loads(result['content'][0]['text'])
outdir=pathlib.Path(target).parent / (side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S'))
outdir.mkdir()
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
target_data=json.loads(subprocess.check_output(['node','apps/server/src/bin.ts','thread','start',str(pathlib.Path(home).parent/'project'),'Reply with just the word OK','--title','Target Codex thread','--provider','codex','--model','gpt-6-astra','--wait','--json','--base-dir',home],cwd=checkout,text=True))
thread=target_data['threadId']
transcript=[]
def emit(label,value):
    text=label+'\n'+json.dumps(value,indent=2)
    transcript.append(text)
    print(text,flush=True)
emit('Real T3 Code server / HTTP MCP / '+side.upper(),{'commit':sha,'database':'fresh isolated database; no copied state','provider':'Codex','model':'gpt-6-astra','seedPrompt':'Reply with just the word OK','seedResult':target_data})
caps=data(call('orchestrator_capabilities',{'search':'gpt-6-astra'}))
providers=caps.get('providers',[])
emit('orchestrator_capabilities (Codex provider only)',[p for p in providers if p.get('providerInstanceId')=='codex'])
def read(): return call('t3_thread_configure',{'threadId':thread})
initial=read()
emit('Initial t3_thread_configure read',initial)
cases=[('Unknown option ID',[{'id':'effort','value':'high'}],True),('Valid control: ultra',[{'id':'reasoningEffort','value':'ultra'}],False),('Duplicate option IDs',[{'id':'reasoningEffort','value':'high'},{'id':'reasoningEffort','value':'low'}],True),('Invalid select value',[{'id':'reasoningEffort','value':'bogus'}],True)]
results=[]
for label,options,invalid in cases:
    before=read()
    args={'threadId':thread,'modelSelection':{'instanceId':'codex','model':'gpt-6-astra','options':options}}
    response=call('t3_thread_configure',args)
    after=read()
    unchanged=data(before)==data(after)
    passed=(response.get('isError') is True and data(response).get('code')=='invalid_request' and unchanged) if invalid else (response.get('isError') is not True and data(after)['modelSelection'].get('options')==options)
    results.append({'case':label,'expectedInvalid':invalid,'isError':response.get('isError',False),'unchanged':unchanged,'passesExpectedBehavior':passed,'request':args,'response':response,'readBack':after})
    emit(label,results[-1])
legacy_caps=data(call('orchestrator_capabilities',{'search':'claude-opus-5-5'}))
emit('Legacy normalization: advertised Claude model (no Claude turn run)',[p for p in legacy_caps.get('providers',[]) if p.get('providerInstanceId')=='claudeAgent'])
legacy_args={'threadId':thread,'modelSelection':{'instanceId':'claudeAgent','model':'claude-opus-5-5','options':[{'id':'effort','value':'ultracode'}]}}
legacy_response=call('t3_thread_configure',legacy_args)
legacy_after=read()
legacy_result={'case':'Legacy Ultracode normalization','request':legacy_args,'response':legacy_response,'readBack':legacy_after,'passesExpectedBehavior':data(legacy_after).get('modelSelection',{}).get('options')==[{'id':'effort','value':'xhigh'},{'id':'ultracode','value':True}]}
emit('Legacy Ultracode normalization (configuration only)',legacy_result)
emit('Verdict',{'allExpectedBehavior':all(r['passesExpectedBehavior'] for r in results),'cases':[{k:r[k] for k in ['case','isError','unchanged','passesExpectedBehavior']} for r in results]})
(outdir/'transcript.txt').write_text('\n\n'.join(transcript)+'\n')
(outdir/'results.json').write_text(json.dumps({'side':side,'sha':sha,'results':results,'legacy':legacy_result},indent=2))
print('SAVED',outdir,flush=True)
