"""
Authentication resource classes.

Auto-generated from OpenAPI specification.
"""

from __future__ import annotations

from typing import (
    Dict,
    Optional,
)

from ..errors import ApiError, ClientValidationError
from ..models import (
    TokenResponse,
)


class AuthenticationResource:
    """Resource class for authentication operations

    Provides structured Pydantic types for all authentication API operations.
    All methods return validated Pydantic models with comprehensive error handling.

    Available operations:
        - exchange(): Exchange API Key for Access Token
    Example:
        >>> client = CredoAI("https://api.example.com", "your-api-key")
        >>> authentication_resource = client.authentication
        >>> client.authentication.exchange()
    """

    def __init__(self, client):
        """Initialize the AuthenticationResource.

        Args:
            client: The parent client instance providing HTTP functionality.
        """
        self._client = client

    def exchange(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> TokenResponse:
        """Exchange API Key for Access Token.

                Exchange an API key for a JWT access token.

        This endpoint accepts an API key and tenant identifier, validates them
        against the authentication service, and returns a JWT access token that
        can be used for subsequent authenticated requests.

        The returned access token should be included in the Authorization header
        as a Bearer token for all authenticated API calls.

                Returns:
                    TokenResponse: Validated response data.

                Response Codes:
                    200: Successful Response
                    422: Error

                Raises:
                    ApiError: When the API returns an error status code.
                    ClientValidationError: When response validation fails.
                    httpx.TimeoutException: When request times out."""
        url = "/auth/token"

        return self._client._make_request(
            method="POST",
            url=url,
            timeout=timeout,
            headers=headers,
            response_model=TokenResponse,
            is_list_response=False,
        )


class AsyncAuthenticationResource:
    """Async resource class for authentication operations

    Provides async methods with structured Pydantic types for all authentication API operations.
    All methods are async and return validated Pydantic models with comprehensive error handling.

    Available async operations:
        - exchange(): Exchange API Key for Access Token
    Example:
        >>> async_client = AsyncCredoAI("https://api.example.com", "your-api-key")
        >>> authentication_resource = async_client.authentication
        >>> result = await async_client.authentication.exchange()
    """

    def __init__(self, client):
        """Initialize the AsyncAuthenticationResource.

        Args:
            client: The parent async client instance providing HTTP functionality.
        """
        self._client = client

    async def exchange(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> TokenResponse:
        """Exchange API Key for Access Token.

                Exchange an API key for a JWT access token.

        This endpoint accepts an API key and tenant identifier, validates them
        against the authentication service, and returns a JWT access token that
        can be used for subsequent authenticated requests.

        The returned access token should be included in the Authorization header
        as a Bearer token for all authenticated API calls.

                Returns:
                    TokenResponse: Validated response data.

                Response Codes:
                    200: Successful Response
                    422: Error

                Raises:
                    ApiError: When the API returns an error status code.
                    ClientValidationError: When response validation fails.
                    httpx.TimeoutException: When request times out."""
        # Prepare URL with path parameters
        url = "/auth/token"

        # Prepare headers
        request_headers = {"Accept": "application/json"}
        if headers:
            request_headers.update(headers)

        # Make async request
        httpx_client = self._client.get_async_httpx_client()
        response = await httpx_client.request(
            method="POST", url=url, headers=request_headers, timeout=timeout
        )

        # Handle errors
        if response.status_code >= 400:
            raise ApiError(
                status_code=response.status_code,
                message=f"POST {url} failed",
                response=response,
            )

        # Parse and validate response
        if self._client._validate_responses and response.content:
            try:
                response_data = response.json()

                # Handle JSON:API format
                if isinstance(response_data, dict) and "data" in response_data:
                    from ..models import JsonApiResponse

                    jsonapi_response = JsonApiResponse.model_validate(response_data)
                    data = jsonapi_response.data
                    # Check for attributes in both dict and object forms
                    if isinstance(data, dict) and "attributes" in data:
                        # Merge id from data level with attributes
                        merged = {"id": data.get("id"), **data["attributes"]}
                        parsed_data = TokenResponse.model_validate(merged)
                    elif hasattr(data, "attributes"):
                        parsed_data = TokenResponse.model_validate(data.attributes)
                    else:
                        parsed_data = TokenResponse.model_validate(data)
                    return parsed_data
                parsed_data = TokenResponse.model_validate(response_data)
                return parsed_data

            except Exception as e:
                if self._client._validate_responses:
                    raise ClientValidationError(f"Response validation failed: {e}")

        # Return basic response wrapper
        from ..models import ClientResponse

        return ClientResponse.from_httpx_response(
            response, response.json() if response.content else None
        )
