#!/usr/bin/env python3
import subprocess, sys, threading, json, os, time
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,stderr=sys.stderr,bufsize=0)
def send():
 for line in sys.stdin.buffer:
  try: p.stdin.write(line); p.stdin.flush()
  except BrokenPipeError: break
threading.Thread(target=send,daemon=True).start()
for line in p.stdout:
 try:
  frame=json.loads(line)
  if isinstance(frame.get('result'),dict) and 'authMethods' in frame['result']:
   methods=frame['result']['authMethods']
   if not any(m.get('id')=='xai.api_key' for m in methods):
    methods.append({'id':'xai.api_key','name':'API key'})
   line=(json.dumps(frame)+'\n').encode()
  params=frame.get('params',{})
  update=params.get('update',{})
  if update.get('sessionUpdate')=='agent_message_chunk':
   meta=update.get('_meta',{})
   with open(os.environ.get('ACP_PROOF_RAW','/tmp/acp-proof-raw.jsonl'),'a') as f:
    f.write(json.dumps({'time':time.time(),'sessionId':params.get('sessionId'),'update':update})+'\n')
 except (ValueError,TypeError): pass
 sys.stdout.buffer.write(line); sys.stdout.buffer.flush()
os._exit(p.wait())
