from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.body_submit_agent import BodySubmitAgent
from ...models.code_analysis_error import CodeAnalysisError
from ...models.cooldown_active_error import CooldownActiveError
from ...models.file_too_large_error import FileTooLargeError
from ...models.invalid_agent_name_error import InvalidAgentNameError
from ...models.invalid_file_error import InvalidFileError
from ...models.no_active_suite_error import NoActiveSuiteError
from ...models.rate_limit_exceeded_error import RateLimitExceededError
from ...models.submit_agent_response import SubmitAgentResponse
from ...types import Response


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

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/v1/miner/submit",
    }

    _kwargs["files"] = body.to_multipart()

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> (
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
    | None
):
    if response.status_code == 200:
        response_200 = SubmitAgentResponse.from_dict(response.json())

        return response_200

    if response.status_code == 400:

        def _parse_response_400(data: object) -> InvalidAgentNameError | InvalidFileError:
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_400_type_0 = InvalidAgentNameError.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 = InvalidFileError.from_dict(data)

            return response_400_type_1

        response_400 = _parse_response_400(response.json())

        return response_400

    if response.status_code == 413:
        response_413 = FileTooLargeError.from_dict(response.json())

        return response_413

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

        return response_422

    if response.status_code == 429:

        def _parse_response_429(data: object) -> CooldownActiveError | RateLimitExceededError:
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_429_type_0 = CooldownActiveError.from_dict(data)

                return response_429_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            if not isinstance(data, dict):
                raise TypeError()
            response_429_type_1 = RateLimitExceededError.from_dict(data)

            return response_429_type_1

        response_429 = _parse_response_429(response.json())

        return response_429

    if response.status_code == 503:
        response_503 = NoActiveSuiteError.from_dict(response.json())

        return response_503

    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[
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
]:
    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: BodySubmitAgent,
) -> Response[
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
]:
    """Submit agent

     Submit an agent file for evaluation. Creates new agent if needed.

    Args:
        body (BodySubmitAgent):

    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[CodeAnalysisError | CooldownActiveError | RateLimitExceededError | FileTooLargeError | InvalidAgentNameError | InvalidFileError | NoActiveSuiteError | SubmitAgentResponse]
    """

    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: BodySubmitAgent,
) -> (
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
    | None
):
    """Submit agent

     Submit an agent file for evaluation. Creates new agent if needed.

    Args:
        body (BodySubmitAgent):

    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:
        CodeAnalysisError | CooldownActiveError | RateLimitExceededError | FileTooLargeError | InvalidAgentNameError | InvalidFileError | NoActiveSuiteError | SubmitAgentResponse
    """

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


async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: BodySubmitAgent,
) -> Response[
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
]:
    """Submit agent

     Submit an agent file for evaluation. Creates new agent if needed.

    Args:
        body (BodySubmitAgent):

    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[CodeAnalysisError | CooldownActiveError | RateLimitExceededError | FileTooLargeError | InvalidAgentNameError | InvalidFileError | NoActiveSuiteError | SubmitAgentResponse]
    """

    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: BodySubmitAgent,
) -> (
    CodeAnalysisError
    | CooldownActiveError
    | RateLimitExceededError
    | FileTooLargeError
    | InvalidAgentNameError
    | InvalidFileError
    | NoActiveSuiteError
    | SubmitAgentResponse
    | None
):
    """Submit agent

     Submit an agent file for evaluation. Creates new agent if needed.

    Args:
        body (BodySubmitAgent):

    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:
        CodeAnalysisError | CooldownActiveError | RateLimitExceededError | FileTooLargeError | InvalidAgentNameError | InvalidFileError | NoActiveSuiteError | SubmitAgentResponse
    """

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