#!/usr/bin/env python3
import subprocess,sys,os,json,threading
child=subprocess.Popen([os.environ['PROOF_OPENCODE_REAL'],*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr.buffer)
pending=set()
lock=threading.Lock()
def forward(src,dst,direction):
 for line in src:
  try:
   v=json.loads(line)
   with lock:
    if 'elicitation' in v.get('method','') and 'id' in v:
     pending.add(v.get('id'))
     with open(os.environ['PROOF_ACP_LOG'],'a') as f: f.write(json.dumps({'direction':direction,'message':v})+'\n')
    elif v.get('id') in pending and ('result' in v or 'error' in v):
     with open(os.environ['PROOF_ACP_LOG'],'a') as f: f.write(json.dumps({'direction':direction,'message':v})+'\n')
  except (ValueError,TypeError): pass
  dst.write(line); dst.flush()
threading.Thread(target=forward,args=(sys.stdin.buffer,child.stdin,'client-to-agent'),daemon=True).start()
forward(child.stdout,sys.stdout.buffer,'agent-to-client')
sys.exit(child.wait())
