#!/usr/bin/env python3
import subprocess,sys,json,threading,os
if "stdio" not in sys.argv:
 os.execvp("grok", ["grok",*sys.argv[1:]])
p=subprocess.Popen(['grok',*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
def send():
 for line in sys.stdin.buffer:
  p.stdin.write(line);p.stdin.flush()
threading.Thread(target=send,daemon=True).start()
for line in p.stdout:
 try:
  msg=json.loads(line)
  if isinstance(msg.get('result'),dict) and 'authMethods' in msg['result']:
   msg['result']['authMethods'].append({'id':'xai.api_key','name':'API key'})
   line=(json.dumps(msg)+'\n').encode()
 except Exception: pass
 sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
os._exit(p.wait())
