import jwt
from fastapi import Cookie
from fastapi import Request

from amsdal_ml.mcp_server.mcp_oauth.services.types import JWT_ALGORITHM
from amsdal_ml.ml_config import ml_config


def require_oauth_enabled() -> None:
    from amsdal_ml.mcp_server.mcp_oauth.services.errors import OAuthDisabledError

    if not ml_config.oauth_enabled:
        raise OAuthDisabledError()


def get_current_user_sub(
    _request: Request,
    amsdal_auth: str | None = Cookie(None),
) -> str | None:
    from amsdal.contrib.auth.settings import auth_settings

    if not amsdal_auth:
        return None
    try:
        signing_key = auth_settings.AUTH_JWT_KEY

        payload = jwt.decode(
            amsdal_auth,
            signing_key,
            algorithms=[JWT_ALGORITHM],
        )

        return payload.get('email') or payload.get('sub')
    except Exception:
        return None
