"""Real upstream HTTPS download proxy with a file-controlled Silero latency gate.
Usage: download-proxy.py <port> <certificate> <key> <release-file>
Trust certificate with NODE_EXTRA_CA_CERTS and enable Node's HTTPS_PROXY support.
All weights come from the real upstream; the app still verifies their hashes.
"""
import http.server,select,socket,socketserver,ssl,sys,time,urllib.request
from pathlib import Path
port,cert,key,release=sys.argv[1:]
ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(cert,key)
ctx.set_alpn_protocols(['http/1.1'])
upstream=urllib.request.build_opener(urllib.request.ProxyHandler({}))
class Proxy(socketserver.StreamRequestHandler):
 def handle(self):
  try:
   first=self.rfile.readline().decode().strip()
   if not first: return
   method,authority,_=first.split()
   while self.rfile.readline() not in (b'\r\n',b'\n',b''): pass
   host,p=authority.rsplit(':',1)
   if method!='CONNECT': return
   self.wfile.write(b'HTTP/1.1 200 Connection established\r\n\r\n');self.wfile.flush()
   if host!='huggingface.co':
    with socket.create_connection((host,int(p))) as remote:
     while True:
      ready,_,_=select.select([self.connection,remote],[],[],120)
      if not ready: return
      for source in ready:
       data=source.recv(65536)
       if not data:return
       (remote if source is self.connection else self.connection).sendall(data)
    return
   with ctx.wrap_socket(self.connection,server_side=True) as conn:
    f=conn.makefile('rb')
    request=f.readline().decode().strip()
    if not request:return
    method,path,_=request.split()
    headers={}
    while True:
     line=f.readline()
     if line in (b'\r\n',b'\n',b''): break
     k,v=line.decode().split(':',1);headers[k]=v.strip()
    if 'silero-vad' in path:
     print('SILERO_WAITING',flush=True)
     while not Path(release).exists(): time.sleep(0.1)
     print('SILERO_RELEASED',flush=True)
    req=urllib.request.Request('https://'+host+path,headers={k:v for k,v in headers.items() if k.lower() in ('range','user-agent')})
    with upstream.open(req,timeout=120) as response:
     conn.sendall(f'HTTP/1.1 {response.status} OK\r\n'.encode())
     for k,v in response.headers.items():
      if k.lower() not in ('connection','transfer-encoding','content-encoding'):
       conn.sendall(f'{k}: {v}\r\n'.encode())
     conn.sendall(b'Connection: close\r\n\r\n')
     while chunk:=response.read(65536): conn.sendall(chunk)
  except (BrokenPipeError,ConnectionResetError,ssl.SSLError): pass
  except Exception as e: print(type(e).__name__,str(e),flush=True)
class Server(socketserver.ThreadingTCPServer):
 allow_reuse_address=True
 daemon_threads=True
with Server(('127.0.0.1',int(port)),Proxy) as server:server.serve_forever()
