from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_version_not_found_error import AgentVersionNotFoundError
from ...models.artifact_download_request import ArtifactDownloadRequest
from ...models.artifact_download_response import ArtifactDownloadResponse
from ...models.artifact_not_found_error import ArtifactNotFoundError
from ...models.artifact_not_released_error import ArtifactNotReleasedError
from ...models.eval_run_not_found_error import EvalRunNotFoundError
from ...models.http_validation_error import HTTPValidationError
from ...models.invalid_artifact_type_error import InvalidArtifactTypeError
from ...models.missing_parameter_error import MissingParameterError
from ...models.suite_not_found_error import SuiteNotFoundError
from ...types import Response


def _get_kwargs(
    *,
    body: ArtifactDownloadRequest,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/v1/public/artifacts/download-url",
    }

    _kwargs["json"] = body.to_dict()

    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> (
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
    | None
):
    if response.status_code == 200:
        response_200 = ArtifactDownloadResponse.from_dict(response.json())

        return response_200

    if response.status_code == 400:

        def _parse_response_400(data: object) -> InvalidArtifactTypeError | MissingParameterError:
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_400_type_0 = MissingParameterError.from_dict(data)

                return response_400_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            if not isinstance(data, dict):
                raise TypeError()
            response_400_type_1 = InvalidArtifactTypeError.from_dict(data)

            return response_400_type_1

        response_400 = _parse_response_400(response.json())

        return response_400

    if response.status_code == 404:

        def _parse_response_404(
            data: object,
        ) -> (
            AgentVersionNotFoundError
            | ArtifactNotFoundError
            | ArtifactNotReleasedError
            | EvalRunNotFoundError
            | SuiteNotFoundError
        ):
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_404_type_0 = AgentVersionNotFoundError.from_dict(data)

                return response_404_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_404_type_1 = SuiteNotFoundError.from_dict(data)

                return response_404_type_1
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_404_type_2 = ArtifactNotReleasedError.from_dict(data)

                return response_404_type_2
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_404_type_3 = ArtifactNotFoundError.from_dict(data)

                return response_404_type_3
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            if not isinstance(data, dict):
                raise TypeError()
            response_404_type_4 = EvalRunNotFoundError.from_dict(data)

            return response_404_type_4

        response_404 = _parse_response_404(response.json())

        return response_404

    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: ArtifactDownloadRequest,
) -> Response[
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
]:
    """Get artifact download URL

     Get a presigned URL to download released artifacts.

    Args:
        body (ArtifactDownloadRequest): Request for artifact download URL.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[AgentVersionNotFoundError | ArtifactNotFoundError | ArtifactNotReleasedError | EvalRunNotFoundError | SuiteNotFoundError | ArtifactDownloadResponse | HTTPValidationError | InvalidArtifactTypeError | MissingParameterError]
    """

    kwargs = _get_kwargs(
        body=body,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient | Client,
    body: ArtifactDownloadRequest,
) -> (
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
    | None
):
    """Get artifact download URL

     Get a presigned URL to download released artifacts.

    Args:
        body (ArtifactDownloadRequest): Request for artifact download URL.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        AgentVersionNotFoundError | ArtifactNotFoundError | ArtifactNotReleasedError | EvalRunNotFoundError | SuiteNotFoundError | ArtifactDownloadResponse | HTTPValidationError | InvalidArtifactTypeError | MissingParameterError
    """

    return sync_detailed(
        client=client,
        body=body,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: ArtifactDownloadRequest,
) -> Response[
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
]:
    """Get artifact download URL

     Get a presigned URL to download released artifacts.

    Args:
        body (ArtifactDownloadRequest): Request for artifact download URL.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[AgentVersionNotFoundError | ArtifactNotFoundError | ArtifactNotReleasedError | EvalRunNotFoundError | SuiteNotFoundError | ArtifactDownloadResponse | HTTPValidationError | InvalidArtifactTypeError | MissingParameterError]
    """

    kwargs = _get_kwargs(
        body=body,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient | Client,
    body: ArtifactDownloadRequest,
) -> (
    AgentVersionNotFoundError
    | ArtifactNotFoundError
    | ArtifactNotReleasedError
    | EvalRunNotFoundError
    | SuiteNotFoundError
    | ArtifactDownloadResponse
    | HTTPValidationError
    | InvalidArtifactTypeError
    | MissingParameterError
    | None
):
    """Get artifact download URL

     Get a presigned URL to download released artifacts.

    Args:
        body (ArtifactDownloadRequest): Request for artifact download URL.

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        AgentVersionNotFoundError | ArtifactNotFoundError | ArtifactNotReleasedError | EvalRunNotFoundError | SuiteNotFoundError | ArtifactDownloadResponse | HTTPValidationError | InvalidArtifactTypeError | MissingParameterError
    """

    return (
        await asyncio_detailed(
            client=client,
            body=body,
        )
    ).parsed
