#!/usr/bin/env python3
import sys,subprocess,threading,time,json,os,shutil
REAL_CODEX=os.environ.get("REAL_CODEX_BINARY") or shutil.which("codex")
if "app-server" not in sys.argv:
 os.execv(REAL_CODEX,["codex"]+sys.argv[1:])
p=subprocess.Popen([REAL_CODEX]+sys.argv[1:],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr)
start_ids=set(); lock=threading.Lock(); pending=[]; gate=False; released=False
log=open(os.environ.get("PROOF_PROTOCOL_LOG",os.path.join(os.path.dirname(__file__),"protocol.ndjson")),"a",buffering=1)
t0=time.monotonic()
def record(direction,msg):
 with lock:
  log.write(json.dumps({"seconds":round(time.monotonic()-t0,3),"direction":direction,"message":msg})+"\n")
def send(line):
 sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
def release():
 global released
 time.sleep(8)
 with lock:
  for line in pending: send(line)
  pending.clear();released=True
 log.write(json.dumps({"seconds":round(time.monotonic()-t0,3),"event":"ordered-stream-released"})+"\n")
def incoming():
 for line in sys.stdin.buffer:
  try:
   m=json.loads(line)
   if m.get("method")=="turn/start":start_ids.add(m.get("id"))
   record("t3-to-codex",m)
  except Exception:pass
  try:p.stdin.write(line);p.stdin.flush()
  except BrokenPipeError:break
threading.Thread(target=incoming,daemon=True).start()
for line in p.stdout:
 try:m=json.loads(line);record("codex-to-proxy",m)
 except Exception:m={}
 with lock:
  if not gate and (m.get("method")=="turn/started" or (m.get("id") in start_ids and "result" in m)):
   gate=True;threading.Thread(target=release,daemon=True).start()
  if gate and not released:pending.append(line)
  else:send(line)
p.wait()
