#!/usr/bin/env python3
import os,sys,json,subprocess,threading,pathlib,shutil
root=pathlib.Path(__file__).parent
real=os.environ.get('AGY_REAL_BINARY') or shutil.which('agy')
if '--version' in sys.argv:
 os.execv(real,['agy',*sys.argv[1:]])
p=subprocess.Popen([real,*sys.argv[1:]],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
requests={}
def record(v):
 with (root/'acp-summary.jsonl').open('a') as f: f.write(json.dumps(v)+'\n')
def enrich(v):
 if isinstance(v,dict):
  if isinstance(v.get('availableModes'),list) and not any(m.get('id')=='auto' for m in v['availableModes']):v['availableModes'].append({'id':'auto','name':'Auto'})
  if v.get('category')=='mode' and isinstance(v.get('options'),list) and not any(o.get('value')=='auto' for o in v['options']):v['options'].append({'value':'auto','name':'Auto'})
  for x in v.values():enrich(x)
 elif isinstance(v,list):
  for x in v:enrich(x)
def forward():
 for line in sys.stdin.buffer:
  try:
   m=json.loads(line); method=m.get('method'); requests[m.get('id')]=method
   params=m.get('params',{})
   record({'direction':'request','method':method,**({'configId':params.get('configId'),'value':params.get('value')} if method=='session/set_config_option' else {})})
  except:pass
  p.stdin.write(line);p.stdin.flush()
 try:p.stdin.close()
 except:pass
threading.Thread(target=forward,daemon=True).start()
for line in p.stdout:
 try:
  m=json.loads(line);method=requests.get(m.get('id'))
  if (root/'advertise-auto').exists():enrich(m)
  if method in ['session/new','session/set_config_option']:
   r=m.get('result',{}); record({'direction':'response','method':method,'modes':r.get('modes'),'modeOptions':[o for o in r.get('configOptions',[]) if o.get('category')=='mode'],'error':m.get('error')})
  line=(json.dumps(m)+'\n').encode()
 except:pass
 sys.stdout.buffer.write(line);sys.stdout.buffer.flush()
sys.exit(p.wait())
