import http.server, urllib.request, threading, pathlib, time, json, os
root=pathlib.Path(__file__).parent
class Proxy(http.server.BaseHTTPRequestHandler):
 def log_message(self,*args): pass
 def do_GET(self): self.forward()
 def do_POST(self): self.forward()
 def forward(self):
  body=self.rfile.read(int(self.headers.get('Content-Length','0')))
  held=(root/'hold').exists() and 'streamGenerateContent' in self.path
  print(json.dumps({'at':time.time(),'path':self.path.split('?')[0],'held':held}),flush=True)
  if held:
   self.send_response(200); self.send_header('Content-Type','text/event-stream'); self.end_headers()
   try:
    while True: self.wfile.write(b'\n'); self.wfile.flush(); time.sleep(5)
   except Exception: print(json.dumps({'at':time.time(),'closed':True}),flush=True)
   return
  headers={k:v for k,v in self.headers.items() if k.lower() not in ['host','connection','accept-encoding']}
  try:
   req=urllib.request.Request(os.environ['UPSTREAM_BASE_URL'].rstrip('/')+self.path,data=body if self.command=='POST' else None,headers=headers,method=self.command)
   with urllib.request.urlopen(req,timeout=180) as r:
    self.send_response(r.status)
    for k,v in r.headers.items():
     if k.lower() not in ['transfer-encoding','connection','content-length','content-encoding']: self.send_header(k,v)
    self.end_headers()
    while b:=r.read1(65536): self.wfile.write(b); self.wfile.flush()
  except Exception as e:
   print(type(e).__name__,str(e),flush=True)
   try: self.send_error(502)
   except Exception: pass
http.server.ThreadingHTTPServer(('127.0.0.1',19876),Proxy).serve_forever()
