#!/usr/bin/python3
import sys,os,subprocess,json,threading,pathlib,time
root=pathlib.Path(__file__).parent
if 'app-server' not in sys.argv:
 os.execv('/usr/local/bin/codex',['codex']+sys.argv[1:])
p=subprocess.Popen(['/usr/local/bin/codex']+sys.argv[1:],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
lock=threading.Lock()
def emit(line):
 with lock:
  sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
def log(x):
 with open(root/'protocol.jsonl','a') as f:f.write(json.dumps(dict(time=time.time(),**x))+'\n')
def output():
 for line in p.stdout:
  try:
   x=json.loads(line)
   if x.get('method') in ['turn/started','turn/completed','thread/goal/updated']:
    params=x.get('params',{}); log({'direction':'in','method':x['method'],'goal':params.get('goal'),'turnStatus':params.get('turn',{}).get('status')})
  except:pass
  emit(line)
threading.Thread(target=output,daemon=True).start()
for line in sys.stdin.buffer:
 try:
  x=json.loads(line)
  if x.get('method') in ['thread/goal/set','thread/goal/get','turn/start']:
   log({'direction':'out','method':x['method'],'status':x.get('params',{}).get('status')})
  if x.get('method')=='thread/goal/set' and x.get('params',{}).get('status')=='active' and (root/'ARM').exists():
   (root/'ARM').unlink();log({'injected':'goal activation failed'})
   emit((json.dumps({'id':x['id'],'error':{'code':-32603,'message':'Injected one-shot goal activation failure'}})+'\n').encode());continue
 except:pass
 p.stdin.write(line);p.stdin.flush()
p.terminate();p.wait()
