"""FastMCP token verifier backed by local JWT validation."""

from __future__ import annotations

from typing import Any

from mcp.server.auth.provider import AccessToken, TokenVerifier

from ..errors import AuthenticationError
from ..logging import get_logger
from .validator import JWTValidator

logger = get_logger(__name__)


class HostedJWTTokenVerifier(TokenVerifier):
    """Verify MCP bearer tokens and expose user identity to FastMCP auth context."""

    def __init__(self, validator: JWTValidator):
        self.validator = validator

    async def verify_token(self, token: str) -> AccessToken | None:
        try:
            claims = await self.validator.validate(token)
        except AuthenticationError:
            return None
        except Exception as exc:  # pragma: no cover - defensive
            logger.error("jwt_token_verifier_failure error=%s", exc)
            return None

        raw_scopes: Any = claims.raw_claims.get("scope") or claims.raw_claims.get("scopes")
        if isinstance(raw_scopes, str):
            scopes = [scope for scope in raw_scopes.split() if scope]
        elif isinstance(raw_scopes, list):
            scopes = [str(scope) for scope in raw_scopes if scope]
        else:
            scopes = []

        return AccessToken(
            token=token,
            client_id=claims.user_id,
            scopes=scopes,
            expires_at=int(claims.expires_at.timestamp()) if claims.expires_at else None,
        )
