"""Minimal HTTP server that redirects all requests to HTTPS (port 443).

Run on port 80 alongside the HTTPS Streamlit frontend so that users who
type a bare IP address into their browser are automatically forwarded.
"""

import http.server
import sys


class RedirectHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        host = self.headers.get("Host", "").split(":")[0] or self.server.server_address[0]
        target = f"https://{host}{self.path}"
        self.send_response(301)
        self.send_header("Location", target)
        self.end_headers()

    # Handle every method the same way
    do_POST = do_GET
    do_PUT = do_GET
    do_DELETE = do_GET
    do_HEAD = do_GET

    def log_message(self, format, *args):
        # Keep logging minimal
        sys.stderr.write(f"[http-redirect] {self.address_string()} -> https  {args[0] if args else ''}\n")


def main():
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 80
    server = http.server.HTTPServer(("0.0.0.0", port), RedirectHandler)
    print(f"HTTP->HTTPS redirect server listening on 0.0.0.0:{port}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    server.server_close()


if __name__ == "__main__":
    main()
