# Forward real model requests, send the first stream bytes, then sever HTTP 200.
import http.server,urllib.request,pathlib,tomllib,socket,json
cfg=tomllib.loads((pathlib.Path.home()/'.codex/config.toml').read_text())
upstream=cfg['openai_base_url'].rstrip('/')
class Proxy(http.server.BaseHTTPRequestHandler):
 def log_message(self,*args): pass
 def do_POST(self):
  body=self.rfile.read(int(self.headers.get('Content-Length',0)))
  headers={k:v for k,v in self.headers.items() if k.lower() not in ['host','content-length','connection','accept-encoding']}
  req=urllib.request.Request(upstream+self.path.removeprefix('/v1'),data=body,headers=headers)
  try:
   with urllib.request.urlopen(req,timeout=90) as response:
    chunk=response.read1(256)
    self.send_response(response.status)
    self.send_header('Content-Type',response.headers.get('Content-Type','text/event-stream'))
    self.send_header('Content-Length','99999999')
    self.end_headers();self.wfile.write(chunk);self.wfile.flush()
    print(json.dumps({'status':response.status,'bytesForwarded':len(chunk),'action':'cut'}),flush=True)
    self.connection.shutdown(socket.SHUT_RDWR);self.connection.close()
  except Exception as e:
   print(type(e).__name__,flush=True)
   self.send_error(502)
http.server.ThreadingHTTPServer(('127.0.0.1',18781),Proxy).serve_forever()
