#!/usr/bin/env python3
"""Independent authenticated ACP check on a newly prepared home, with no hardcoded model IDs.
Usage: verify-provider.py ROOT SIDE
"""
import json,pathlib,subprocess,sys
root=pathlib.Path(sys.argv[1]).resolve();side=sys.argv[2]
p=subprocess.Popen([str(root/side/'bin/copilot'),'--acp'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True)
def call(i,method,params):
 p.stdin.write(json.dumps(dict(jsonrpc='2.0',id=i,method=method,params=params))+'\n');p.stdin.flush()
 while True:
  line=p.stdout.readline()
  if not line:raise RuntimeError('Copilot closed the connection')
  reply=json.loads(line)
  if reply.get('id')==i:
   if 'error' in reply:raise RuntimeError('ACP request failed: '+method)
   return reply['result']
try:
 call(1,'initialize',dict(protocolVersion=1,clientCapabilities={},clientInfo=dict(name='proof-rebuild',version='1')))
 s=call(2,'session/new',dict(cwd=str(root),mcpServers=[]))
 sid=s['sessionId'];a=next(c for c in s['configOptions'] if c['id']=='model')['currentValue']
 call(3,'session/set_config_option',dict(sessionId=sid,configId='model',value=a))
 call(4,'session/set_config_option',dict(sessionId=sid,configId='reasoning_effort',value='high'))
 response=call(5,'session/prompt',dict(sessionId=sid,prompt=[dict(type='text',text='Reply with the single word OK.')]))
 aliases=json.loads((root/'private-aliases.json').read_text())
 usage=[json.loads(line)['data']['usage'] for line in (root/side/'copilot-home/session-state'/sid/'events.jsonl').read_text().splitlines() if json.loads(line).get('type')=='session.usage_record'][-1]
 print(json.dumps(dict(authenticated=True,freshHome=True,model=aliases[usage['model']],reasoningEffort=usage.get('reasoningEffort'),stopReason=response.get('stopReason'))))
finally:
 p.stdin.close();p.wait()
