#!/usr/bin/env python3
import sys,json,threading,http.server,os
lock=threading.Lock()
def send(o):
 with lock: print(json.dumps(o),flush=True)
for line in sys.stdin:
 try: q=json.loads(line)
 except: continue
 if 'id' not in q: continue
 method=q.get('method'); ident=q['id']

 if method=='initialize':
  send({'jsonrpc':'2.0','id':ident,'result':{'protocolVersion':1,'agentInfo':{'name':'antigravity-acp','version':'1.1.1'},'agentCapabilities':{'loadSession':True,'sessionCapabilities':{'resume':{}},'auth':{'logout':{}}},'authMethods':[{'id':'oauth-business','name':'Gemini Enterprise'},{'id':'oauth-personal','name':'Google account'}]}})
 elif method in ('authenticate','auth/login'):
  # A synthetic saved credential selects immediate successful authentication.
  marker=os.path.join(os.environ.get('GEMINI_HOME','.'),'evidence-saved')
  if os.path.exists(marker): send({'jsonrpc':'2.0','id':ident,'result':{}}); continue
  class Handler(http.server.BaseHTTPRequestHandler):
   def log_message(self,*a): pass
   def do_GET(self):
    self.send_response(200); self.end_headers(); self.wfile.write(b'All set (synthetic authentication fixture)')
    os.makedirs(os.path.dirname(marker),exist_ok=True)
    open(marker,'w').write('synthetic')
    send({'jsonrpc':'2.0','id':ident,'result':{}})
  server=http.server.HTTPServer(('127.0.0.1',0),Handler)
  threading.Thread(target=server.serve_forever,daemon=True).start()
  open(os.path.join(os.environ.get('GEMINI_HOME','.'),'evidence-callback'),'w').write('http://127.0.0.1:'+str(server.server_port)+'/?state=evidence&code=synthetic')
  url='https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=evidence&redirect_uri=http%3A%2F%2F127.0.0.1%3A'+str(server.server_port)+'%2F'
  print('Open the following link to authenticate the ACP server: '+url,flush=True)
 elif method=='session/new': pass
 else: send({'jsonrpc':'2.0','id':ident,'result':{}})
