#!/usr/bin/env python3
"""Simple local web server for ~/projects.

Serves /home/cybernoc/projects so you can browse:
  /idea/...
  /output/web/...
  /<project>/output/web/...

Optional Basic Auth (enabled when both env vars are set):
  BASIC_AUTH_USER=...
  BASIC_AUTH_PASS=...
"""
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from functools import partial
import base64
import hmac
import os

ROOT = os.path.expanduser("~/projects")
PORT = int(os.environ.get("PORT", "8000"))
HOST = os.environ.get("HOST", "0.0.0.0")
BASIC_AUTH_USER = os.environ.get("BASIC_AUTH_USER", "")
BASIC_AUTH_PASS = os.environ.get("BASIC_AUTH_PASS", "")
AUTH_ENABLED = bool(BASIC_AUTH_USER and BASIC_AUTH_PASS)


def make_handler(directory: str):
    class AuthHandler(SimpleHTTPRequestHandler):
        def _authorized(self) -> bool:
            if not AUTH_ENABLED:
                return True
            header = self.headers.get("Authorization", "")
            if not header.startswith("Basic "):
                return False
            token = header.split(" ", 1)[1].strip()
            try:
                decoded = base64.b64decode(token).decode("utf-8")
            except Exception:
                return False
            user, _, password = decoded.partition(":")
            return hmac.compare_digest(user, BASIC_AUTH_USER) and hmac.compare_digest(
                password, BASIC_AUTH_PASS
            )

        def _send_auth_required(self):
            self.send_response(401)
            self.send_header("WWW-Authenticate", 'Basic realm="projects", charset="UTF-8"')
            self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.end_headers()
            self.wfile.write(b"Authentication required")

        def parse_request(self):
            ok = super().parse_request()
            if not ok:
                return False
            if not self._authorized():
                self._send_auth_required()
                self.close_connection = True
                return False
            return True

        def log_message(self, format, *args):  # noqa: A002
            # Avoid logging credentials; keep default format.
            super().log_message(format, *args)

    return partial(AuthHandler, directory=directory)


if __name__ == "__main__":
    os.chdir(ROOT)
    handler = make_handler(ROOT)
    server = ThreadingHTTPServer((HOST, PORT), handler)
    auth_status = "enabled" if AUTH_ENABLED else "disabled"
    print(f"Serving {ROOT} at http://{HOST}:{PORT} (basic auth: {auth_status})")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
