import http.server, urllib.request, urllib.error, json, pathlib, os
config=json.loads((pathlib.Path.home()/'.config/opencode/opencode.json').read_text())['provider']['openai']['options']
count=0
class Proxy(http.server.BaseHTTPRequestHandler):
 def log_message(self,*a): pass
 def do_GET(self):
  global count
  if self.path=='/reset':count=0
  self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'requests':count}).encode())
 def do_POST(self):
  global count
  data=self.rfile.read(int(self.headers['Content-Length']));count+=1
  print(json.dumps({'request':count,'path':self.path,'outcome':'forward' if count==1 else 'HTTP 500 upstream overloaded'}),flush=True)
  if count>1:
   self.send_response(500);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(b'{"error":{"message":"upstream overloaded","type":"server_error"}}');return
  req=urllib.request.Request(config['baseURL'].rstrip('/')+self.path.removeprefix('/v1'),data,{'Authorization':'Bearer '+config['apiKey'],'Content-Type':'application/json'})
  try:
   with urllib.request.urlopen(req,timeout=180) as r:
    self.send_response(r.status);self.send_header('Content-Type',r.headers.get('Content-Type','text/event-stream'));self.end_headers()
    while chunk:=r.read(1024):self.wfile.write(chunk);self.wfile.flush()
  except Exception as e:
   self.send_response(502);self.end_headers();self.wfile.write(str(type(e).__name__).encode())
http.server.ThreadingHTTPServer(('127.0.0.1',18935),Proxy).serve_forever()
