#!/usr/bin/env python3
import os, sys, subprocess, threading, json, shutil
root=os.path.dirname(os.path.abspath(__file__))
version=open(root+'/reported-version').read().strip()
side=open(root+'/side').read().strip()
p=subprocess.Popen([os.environ.get('PROOF_AGY') or shutil.which('agy'),*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr)
def incoming():
 for line in sys.stdin.buffer:
  try:
   msg=json.loads(line)
   if msg.get('method')=='initialize':
    with open(root+'/'+side+'-initialize.jsonl','a') as f: f.write(json.dumps({'reportedVersion':version,'request':msg})+'\n')
  except Exception: pass
  p.stdin.write(line); p.stdin.flush()
 try: p.stdin.close()
 except Exception: pass
threading.Thread(target=incoming,daemon=True).start()
for line in p.stdout:
 try:
  msg=json.loads(line)
  if 'agentInfo' in msg.get('result',{}):
   original=msg['result']['agentInfo'].get('version')
   if version!='actual': msg['result']['agentInfo']['version']=version
   with open(root+'/'+side+'-replies.jsonl','a') as f: f.write(json.dumps({'originalVersion':original,'reply':msg})+'\n')
   line=(json.dumps(msg)+'\n').encode()
 except Exception: pass
 sys.stdout.buffer.write(line); sys.stdout.buffer.flush()
sys.exit(p.wait())
