from http import HTTPStatus
from typing import Any
from urllib.parse import quote
from uuid import UUID

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.eval_run_not_found_error import EvalRunNotFoundError
from ...models.http_validation_error import HTTPValidationError
from ...models.invalid_problem_id_error import InvalidProblemIdError
from ...models.not_run_owner_error import NotRunOwnerError
from ...models.progress_update_request import ProgressUpdateRequest
from ...models.progress_update_response import ProgressUpdateResponse
from ...types import Response


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

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/v1/validator/evaluation-runs/{eval_run_id}/progress".format(
            eval_run_id=quote(str(eval_run_id), safe=""),
        ),
    }

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

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

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> (
    EvalRunNotFoundError
    | HTTPValidationError
    | InvalidProblemIdError
    | NotRunOwnerError
    | ProgressUpdateResponse
    | None
):
    if response.status_code == 200:
        response_200 = ProgressUpdateResponse.from_dict(response.json())

        return response_200

    if response.status_code == 400:
        response_400 = InvalidProblemIdError.from_dict(response.json())

        return response_400

    if response.status_code == 404:
        response_404 = EvalRunNotFoundError.from_dict(response.json())

        return response_404

    if response.status_code == 409:
        response_409 = NotRunOwnerError.from_dict(response.json())

        return response_409

    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[
    EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse
]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    eval_run_id: UUID,
    *,
    client: AuthenticatedClient | Client,
    body: ProgressUpdateRequest,
) -> Response[
    EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse
]:
    """Update progress

     Report per-problem progress during evaluation. Accepts updates even after run completion so late-
    arriving scores and log keys are not lost.

    Args:
        eval_run_id (UUID): Evaluation run ID
        body (ProgressUpdateRequest): Request to update per-problem progress.

    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[EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse]
    """

    kwargs = _get_kwargs(
        eval_run_id=eval_run_id,
        body=body,
    )

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

    return _build_response(client=client, response=response)


def sync(
    eval_run_id: UUID,
    *,
    client: AuthenticatedClient | Client,
    body: ProgressUpdateRequest,
) -> (
    EvalRunNotFoundError
    | HTTPValidationError
    | InvalidProblemIdError
    | NotRunOwnerError
    | ProgressUpdateResponse
    | None
):
    """Update progress

     Report per-problem progress during evaluation. Accepts updates even after run completion so late-
    arriving scores and log keys are not lost.

    Args:
        eval_run_id (UUID): Evaluation run ID
        body (ProgressUpdateRequest): Request to update per-problem progress.

    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:
        EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse
    """

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


async def asyncio_detailed(
    eval_run_id: UUID,
    *,
    client: AuthenticatedClient | Client,
    body: ProgressUpdateRequest,
) -> Response[
    EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse
]:
    """Update progress

     Report per-problem progress during evaluation. Accepts updates even after run completion so late-
    arriving scores and log keys are not lost.

    Args:
        eval_run_id (UUID): Evaluation run ID
        body (ProgressUpdateRequest): Request to update per-problem progress.

    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[EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse]
    """

    kwargs = _get_kwargs(
        eval_run_id=eval_run_id,
        body=body,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    eval_run_id: UUID,
    *,
    client: AuthenticatedClient | Client,
    body: ProgressUpdateRequest,
) -> (
    EvalRunNotFoundError
    | HTTPValidationError
    | InvalidProblemIdError
    | NotRunOwnerError
    | ProgressUpdateResponse
    | None
):
    """Update progress

     Report per-problem progress during evaluation. Accepts updates even after run completion so late-
    arriving scores and log keys are not lost.

    Args:
        eval_run_id (UUID): Evaluation run ID
        body (ProgressUpdateRequest): Request to update per-problem progress.

    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:
        EvalRunNotFoundError | HTTPValidationError | InvalidProblemIdError | NotRunOwnerError | ProgressUpdateResponse
    """

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