"""Authentication module for Crustdata MCP Server."""

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


class CrustdataTokenVerifier(TokenVerifier):
    """Token verifier that validates bearer tokens against a configured token.

    This verifier performs simple string comparison to authenticate MCP clients.
    Clients must provide the same token that the server uses for Crustdata API access.
    """

    def __init__(self, valid_token: str) -> None:
        """Initialize the token verifier.

        Args:
            valid_token: The token that clients must provide to authenticate.
        """
        self.valid_token = valid_token

    async def verify_token(self, token: str) -> AccessToken | None:
        """Verify a bearer token.

        Args:
            token: The bearer token from the Authorization header.

        Returns:
            AccessToken if valid, None if invalid.
        """
        if token == self.valid_token:
            return AccessToken(
                token=token,
                client_id="mcp-client",
                scopes=["read", "write"],
                expires_at=None,
            )
        return None


class PassthroughTokenVerifier(TokenVerifier):
    """Token verifier that accepts any valid-format bearer token.

    Used for HTTP transport where each client provides their own
    Crustdata API token. The token is passed through to tools
    which use it to authenticate with the Crustdata API.

    This enables multi-tenant support: different clients can use
    different Crustdata accounts without server-level configuration.
    """

    # Minimum token length for basic validation
    MIN_TOKEN_LENGTH = 10

    async def verify_token(self, token: str) -> AccessToken | None:
        """Accept any non-empty, valid-format token.

        The token is stored in the AccessToken object and can be
        retrieved by tools via get_access_token() to make API calls.

        Args:
            token: The bearer token from the Authorization header.

        Returns:
            AccessToken with the original token stored, or None if invalid format.
        """
        # Reject empty or whitespace-only tokens
        if not token or not token.strip():
            return None

        # Basic format validation - Crustdata tokens are reasonably long
        if len(token) < self.MIN_TOKEN_LENGTH:
            return None

        return AccessToken(
            token=token,  # Store the actual token for later retrieval
            client_id="crustdata-api-client",
            scopes=["read", "write"],
            expires_at=None,
        )
