"""Auth API client for V3."""

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Auth:
    """Client for Authentication resources (/api/v3/auth).

    Handles JWT tokens, API keys, and user authentication.
    """

    def __init__(self, client: "ConcentriqClient"):
        """Initialize with client instance.

        Args:
            client: The ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/v3/auth"

    def whoami(self) -> dict[str, Any]:
        """Get current user information and role rules.

        Returns:
            Dictionary with userId and roleRules

        Raises:
            AuthenticationError: If not authenticated

        Example:
            >>> result = client.v3.auth.whoami()
            >>> print(result["userId"])
            123
            >>> print(result["roleRules"])
            [["read", "imageSets"], ["create", "annotations"]]
        """
        response = self._client._request("GET", f"{self._base_path}/whoami")
        return response.json()

    def get_public_key(self) -> dict[str, Any]:
        """Get JWT token signing public key.

        Returns:
            Dictionary with publicKey (PEM-formatted public key)

        Raises:
            AuthenticationError: If not authenticated

        Example:
            >>> result = client.v3.auth.get_public_key()
            >>> print(result["publicKey"])
            -----BEGIN PUBLIC KEY-----
            ...
        """
        response = self._client._request("GET", f"{self._base_path}/token/public-key")
        return response.json()

    def create_token(self) -> dict[str, Any]:
        """Create a new JWT authentication token.

        Returns:
            Dictionary with token (JWT string)

        Raises:
            AuthenticationError: If not authenticated

        Note:
            Requires authentication via Basic Auth, Cookie, or API Key.
            Token expires after configured duration (typically 24 hours).

        Example:
            >>> result = client.v3.auth.create_token()
            >>> print(result["token"])
            eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
        """
        response = self._client._request("POST", f"{self._base_path}/token")
        return response.json()

    def create_api_key(self) -> dict[str, Any]:
        """Create a new API key for the authenticated user.

        Returns:
            Dictionary with apiKey (string)

        Raises:
            AuthenticationError: If not authenticated

        Warning:
            The API key is only visible at creation time and cannot be retrieved again.
            Store it securely.

        Note:
            Requires authentication via Basic Auth, Cookie, or JWT.
            Cannot create API key using another API key.

        Example:
            >>> result = client.v3.auth.create_api_key()
            >>> print(result["apiKey"])
            cr_1234567890abcdef
        """
        response = self._client._request("POST", f"{self._base_path}/key")
        return response.json()

    def delete_api_key(self) -> None:
        """Delete the API key for the authenticated user.

        Returns:
            None

        Raises:
            AuthenticationError: If not authenticated

        Note:
            This operation cannot be undone. Create a new API key if needed.

        Example:
            >>> client.v3.auth.delete_api_key()
        """
        self._client._request("DELETE", f"{self._base_path}/key")

    def check_api_key_status(self) -> dict[str, Any]:
        """Check if the authenticated user has an active API key.

        Returns:
            Dictionary with active (boolean)

        Raises:
            AuthenticationError: If not authenticated

        Example:
            >>> result = client.v3.auth.check_api_key_status()
            >>> print(result["active"])
            True
        """
        response = self._client._request("GET", f"{self._base_path}/key/status")
        return response.json()
