"""Who may call a GalaxiQ product's API: a signed-in user of the platform, or one of our own services.

A user arrives with the platform's JWT (the app sends it on every call); a service (the Node backend, another
product) arrives with the shared service key. Anyone else gets 401. Health and bootstrap stay open, and a product
may name more open paths (a chat widget visitors use, an OAuth callback).

    door = Door(jwt_key=settings.JWT_KEY, service_key=settings.GALAXIQ_SERVICE_KEY)
    app = FastAPI(dependencies=[Depends(door)])          # every route, every router

    caller = door.caller_of(request)    # {"kind": "user", "user_id", "email"} | {"kind": "service"} | None

No postponed annotations here: FastAPI resolves a dependency's parameter types from the callable's globals, and a
Door instance has none, so `request: Request` must be a real annotation, not a string.
"""
import hmac
import logging
from typing import Iterable, Optional

from fastapi import HTTPException, Request

log = logging.getLogger("galaxiq.auth")

SERVICE_KEY_HEADER = "x-galaxiq-service-key"
OPEN_BY_DEFAULT = ("/health", "/bootstrap")
REFUSED = "Sign in required."


def actor_from_token(token: str, jwt_key: str) -> Optional[dict]:
    """{user_id, email} from the platform's HS256 token, or None when it does not verify or names nobody."""
    import jwt

    try:
        payload = jwt.decode(token, jwt_key, algorithms=["HS256"])
    except jwt.PyJWTError as exc:
        log.info("auth: token not verifiable (%s)", type(exc).__name__)
        return None
    user_id = payload.get("userId") or payload.get("id")
    if not user_id:
        return None
    return {"user_id": str(user_id), "email": payload.get("email")}


class Door:
    def __init__(self, jwt_key: str = "", service_key: str = "", open_paths: Iterable[str] = (),
                 key_headers: Iterable[str] = (SERVICE_KEY_HEADER,)):
        self.jwt_key = jwt_key or ""
        self.service_key = service_key or ""
        self.open_paths = frozenset(p.rstrip("/") or "/" for p in (*OPEN_BY_DEFAULT, *open_paths))
        self.key_headers = tuple(key_headers)
        if not self.jwt_key and not self.service_key:
            log.error("auth: neither JWT_KEY nor the service key is set; every call but the open paths is refused")

    def is_open(self, path: str) -> bool:
        return (path.rstrip("/") or "/") in self.open_paths

    def caller_of(self, request: Request) -> Optional[dict]:
        for header in self.key_headers:
            key = request.headers.get(header, "")
            if key and self.service_key and hmac.compare_digest(key, self.service_key):
                return {"kind": "service"}
        if self.jwt_key:
            token = request.headers.get("authorization", "")
            if token.startswith("Bearer "):
                actor = actor_from_token(token[7:], self.jwt_key)
                if actor:
                    return {"kind": "user", **actor}
            token = request.query_params.get("token", "")   # websockets cannot carry a header
            if token:
                actor = actor_from_token(token, self.jwt_key)
                if actor:
                    return {"kind": "user", **actor}
        return None

    def __call__(self, request: Request) -> dict:
        """The FastAPI dependency: the caller, or 401."""
        if self.is_open(request.url.path):
            return {"kind": "open"}
        caller = self.caller_of(request)
        if caller is None:
            raise HTTPException(status_code=401, detail=REFUSED)
        return caller


__all__ = ["Door", "actor_from_token", "SERVICE_KEY_HEADER", "OPEN_BY_DEFAULT", "REFUSED"]
