"""
System resource classes.

Auto-generated from OpenAPI specification.
"""

from __future__ import annotations

from typing import (
    Any,
    Dict,
    Optional,
)

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


class SystemResource:
    """Resource class for system operations

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

    Available operations:
        - metrics(): Metrics
        - ping(): Ping
    Example:
        >>> client = CredoAI("https://api.example.com", "your-api-key")
        >>> system_resource = client.system
        >>> client.system.metrics()
    """

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

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

    def metrics(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """Metrics.

        Endpoint that serves Prometheus metrics.

        Returns:
            Any: Raw API response data.

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

        return self._client._make_request(
            method="GET",
            url=url,
            timeout=timeout,
            headers=headers,
        )

    def ping(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> PingResponse:
        """Ping.

        Ping endpoint (public, no authentication required).

        Returns:
            PingResponse: Validated response data.

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

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


class AsyncSystemResource:
    """Async resource class for system operations

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

    Available async operations:
        - metrics(): Metrics
        - ping(): Ping
    Example:
        >>> async_client = AsyncCredoAI("https://api.example.com", "your-api-key")
        >>> system_resource = async_client.system
        >>> result = await async_client.system.metrics()
    """

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

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

    async def metrics(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """Metrics.

        Endpoint that serves Prometheus metrics.

        Returns:
            Any: Raw API response data.

        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 = "/metrics"

        # 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="GET", url=url, headers=request_headers, timeout=timeout
        )

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

        # Parse and validate response

        # Return basic response wrapper
        from ..models import ClientResponse

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

    async def ping(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> PingResponse:
        """Ping.

        Ping endpoint (public, no authentication required).

        Returns:
            PingResponse: Validated response data.

        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 = "/ping"

        # 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="GET", url=url, headers=request_headers, timeout=timeout
        )

        # Handle errors
        if response.status_code >= 400:
            raise ApiError(
                status_code=response.status_code,
                message=f"GET {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 = PingResponse.model_validate(merged)
                    elif hasattr(data, "attributes"):
                        parsed_data = PingResponse.model_validate(data.attributes)
                    else:
                        parsed_data = PingResponse.model_validate(data)
                    return parsed_data
                parsed_data = PingResponse.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
        )
