"""
Health resource classes.

Auto-generated from OpenAPI specification.
Generated: 2026-01-28T01:42:33.414545+00:00
Source: 0.1.0
"""

from __future__ import annotations

from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union

from pydantic import BaseModel, TypeAdapter

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


class HealthResource:
    """Resource class for health operations

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

    Available operations:
        - check_liveness(): Liveness Probe
        - check_readiness(): Readiness Probe
    Example:
        >>> client = CredoAI("https://api.example.com", "your-api-key")
        >>> health_resource = client.health
        >>> client.health.check_liveness()
    """

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

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

    def check_liveness(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> HealthResponse:
        """Liveness Probe.

                Kubernetes-style liveness probe endpoint.

        This endpoint indicates whether the application is alive and running.
        It's used by Kubernetes and other orchestration platforms to determine
        if the container should be restarted.

        A successful response (200 OK) indicates the application is alive.
        If this endpoint fails or returns an error, the orchestration platform
        may restart the container.

        Returns:
            HealthResponse: A response object with message=True indicating
            the application is alive.

        Example:
            ```python
            GET /livez

            # Response:
            {
                "message": true
            }
            ```

        Note:
            - This endpoint should always return quickly (< 1 second)
            - It should not perform expensive operations or external calls
            - Used for liveness probes in Kubernetes deployments
            - Does not require authentication

                Returns:
                    HealthResponse: 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 = "/livez"

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

    def check_readiness(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> HealthResponse:
        """Readiness Probe.

                Kubernetes-style readiness probe endpoint.

        This endpoint indicates whether the application is ready to serve traffic.
        It's used by Kubernetes and load balancers to determine if the instance
        should receive incoming requests.

        A successful response indicates the application is ready to handle requests.
        If this endpoint fails, the instance will be removed from the load balancer
        pool until it becomes ready again.

        This endpoint performs the following readiness checks:
        - Verifies that the CREDOAI_SERVER_BASE_URL service is ready by calling its /readyz endpoint

        Returns:
            HealthResponse: A response object with message=True indicating
            the application is ready to serve traffic.

        Raises:
            HTTPException: 503 Service Unavailable if any dependency check fails.

        Example:
            ```python
            GET /readyz

            # Response:
            {
                "message": true
            }
            ```

        Note:
            - This endpoint verifies that all dependencies are available
            - Includes checks for external API availability (CREDOAI_SERVER_BASE_URL)
            - Used for readiness probes in Kubernetes deployments
            - Should return quickly but may be slightly slower than /livez
            - Does not require authentication

                Returns:
                    HealthResponse: 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 = "/readyz"

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


class AsyncHealthResource:
    """Async resource class for health operations

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

    Available async operations:
        - check_liveness(): Liveness Probe
        - check_readiness(): Readiness Probe
    Example:
        >>> async_client = AsyncCredoAI("https://api.example.com", "your-api-key")
        >>> health_resource = async_client.health
        >>> result = await async_client.health.check_liveness()
    """

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

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

    async def check_liveness(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> HealthResponse:
        """Liveness Probe.

                Kubernetes-style liveness probe endpoint.

        This endpoint indicates whether the application is alive and running.
        It's used by Kubernetes and other orchestration platforms to determine
        if the container should be restarted.

        A successful response (200 OK) indicates the application is alive.
        If this endpoint fails or returns an error, the orchestration platform
        may restart the container.

        Returns:
            HealthResponse: A response object with message=True indicating
            the application is alive.

        Example:
            ```python
            GET /livez

            # Response:
            {
                "message": true
            }
            ```

        Note:
            - This endpoint should always return quickly (< 1 second)
            - It should not perform expensive operations or external calls
            - Used for liveness probes in Kubernetes deployments
            - Does not require authentication

                Returns:
                    HealthResponse: 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 = "/livez"

        # 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 = HealthResponse.model_validate(merged)
                    elif hasattr(data, "attributes"):
                        parsed_data = HealthResponse.model_validate(data.attributes)
                    else:
                        parsed_data = HealthResponse.model_validate(data)
                    return parsed_data
                parsed_data = HealthResponse.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
        )

    async def check_readiness(
        self,
        *,
        timeout: Optional[float] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> HealthResponse:
        """Readiness Probe.

                Kubernetes-style readiness probe endpoint.

        This endpoint indicates whether the application is ready to serve traffic.
        It's used by Kubernetes and load balancers to determine if the instance
        should receive incoming requests.

        A successful response indicates the application is ready to handle requests.
        If this endpoint fails, the instance will be removed from the load balancer
        pool until it becomes ready again.

        This endpoint performs the following readiness checks:
        - Verifies that the CREDOAI_SERVER_BASE_URL service is ready by calling its /readyz endpoint

        Returns:
            HealthResponse: A response object with message=True indicating
            the application is ready to serve traffic.

        Raises:
            HTTPException: 503 Service Unavailable if any dependency check fails.

        Example:
            ```python
            GET /readyz

            # Response:
            {
                "message": true
            }
            ```

        Note:
            - This endpoint verifies that all dependencies are available
            - Includes checks for external API availability (CREDOAI_SERVER_BASE_URL)
            - Used for readiness probes in Kubernetes deployments
            - Should return quickly but may be slightly slower than /livez
            - Does not require authentication

                Returns:
                    HealthResponse: 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 = "/readyz"

        # 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 = HealthResponse.model_validate(merged)
                    elif hasattr(data, "attributes"):
                        parsed_data = HealthResponse.model_validate(data.attributes)
                    else:
                        parsed_data = HealthResponse.model_validate(data)
                    return parsed_data
                parsed_data = HealthResponse.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
        )
