import datetime
from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.agent_version_variance_response import AgentVersionVarianceResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    suite_id: int | None | Unset = UNSET,
    variance_threshold: float | Unset = 0.1,
    limit: int | Unset = 20,
    since: datetime.datetime | None | Unset = UNSET,
    until: datetime.datetime | None | Unset = UNSET,
) -> dict[str, Any]:

    params: dict[str, Any] = {}

    json_suite_id: int | None | Unset
    if isinstance(suite_id, Unset):
        json_suite_id = UNSET
    else:
        json_suite_id = suite_id
    params["suite_id"] = json_suite_id

    params["variance_threshold"] = variance_threshold

    params["limit"] = limit

    json_since: None | str | Unset
    if isinstance(since, Unset):
        json_since = UNSET
    elif isinstance(since, datetime.datetime):
        json_since = since.isoformat()
    else:
        json_since = since
    params["since"] = json_since

    json_until: None | str | Unset
    if isinstance(until, Unset):
        json_until = UNSET
    elif isinstance(until, datetime.datetime):
        json_until = until.isoformat()
    else:
        json_until = until
    params["until"] = json_until

    params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/v1/admin/analytics/agent-version-variance",
        "params": params,
    }

    return _kwargs


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

        return response_200

    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[AgentVersionVarianceResponse | HTTPValidationError]:
    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,
    suite_id: int | None | Unset = UNSET,
    variance_threshold: float | Unset = 0.1,
    limit: int | Unset = 20,
    since: datetime.datetime | None | Unset = UNSET,
    until: datetime.datetime | None | Unset = UNSET,
) -> Response[AgentVersionVarianceResponse | HTTPValidationError]:
    """Score variance across validators for recent agent versions

     Find agent versions with high score variance across validators.

    Args:
        suite_id (int | None | Unset): Suite ID (defaults to active suite)
        variance_threshold (float | Unset): Spread threshold for flagging Default: 0.1.
        limit (int | Unset): Number of agent versions Default: 20.
        since (datetime.datetime | None | Unset): Only versions after this time
        until (datetime.datetime | None | Unset): Only versions before this time

    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[AgentVersionVarianceResponse | HTTPValidationError]
    """

    kwargs = _get_kwargs(
        suite_id=suite_id,
        variance_threshold=variance_threshold,
        limit=limit,
        since=since,
        until=until,
    )

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

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient | Client,
    suite_id: int | None | Unset = UNSET,
    variance_threshold: float | Unset = 0.1,
    limit: int | Unset = 20,
    since: datetime.datetime | None | Unset = UNSET,
    until: datetime.datetime | None | Unset = UNSET,
) -> AgentVersionVarianceResponse | HTTPValidationError | None:
    """Score variance across validators for recent agent versions

     Find agent versions with high score variance across validators.

    Args:
        suite_id (int | None | Unset): Suite ID (defaults to active suite)
        variance_threshold (float | Unset): Spread threshold for flagging Default: 0.1.
        limit (int | Unset): Number of agent versions Default: 20.
        since (datetime.datetime | None | Unset): Only versions after this time
        until (datetime.datetime | None | Unset): Only versions before this time

    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:
        AgentVersionVarianceResponse | HTTPValidationError
    """

    return sync_detailed(
        client=client,
        suite_id=suite_id,
        variance_threshold=variance_threshold,
        limit=limit,
        since=since,
        until=until,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    suite_id: int | None | Unset = UNSET,
    variance_threshold: float | Unset = 0.1,
    limit: int | Unset = 20,
    since: datetime.datetime | None | Unset = UNSET,
    until: datetime.datetime | None | Unset = UNSET,
) -> Response[AgentVersionVarianceResponse | HTTPValidationError]:
    """Score variance across validators for recent agent versions

     Find agent versions with high score variance across validators.

    Args:
        suite_id (int | None | Unset): Suite ID (defaults to active suite)
        variance_threshold (float | Unset): Spread threshold for flagging Default: 0.1.
        limit (int | Unset): Number of agent versions Default: 20.
        since (datetime.datetime | None | Unset): Only versions after this time
        until (datetime.datetime | None | Unset): Only versions before this time

    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[AgentVersionVarianceResponse | HTTPValidationError]
    """

    kwargs = _get_kwargs(
        suite_id=suite_id,
        variance_threshold=variance_threshold,
        limit=limit,
        since=since,
        until=until,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient | Client,
    suite_id: int | None | Unset = UNSET,
    variance_threshold: float | Unset = 0.1,
    limit: int | Unset = 20,
    since: datetime.datetime | None | Unset = UNSET,
    until: datetime.datetime | None | Unset = UNSET,
) -> AgentVersionVarianceResponse | HTTPValidationError | None:
    """Score variance across validators for recent agent versions

     Find agent versions with high score variance across validators.

    Args:
        suite_id (int | None | Unset): Suite ID (defaults to active suite)
        variance_threshold (float | Unset): Spread threshold for flagging Default: 0.1.
        limit (int | Unset): Number of agent versions Default: 20.
        since (datetime.datetime | None | Unset): Only versions after this time
        until (datetime.datetime | None | Unset): Only versions before this time

    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:
        AgentVersionVarianceResponse | HTTPValidationError
    """

    return (
        await asyncio_detailed(
            client=client,
            suite_id=suite_id,
            variance_threshold=variance_threshold,
            limit=limit,
            since=since,
            until=until,
        )
    ).parsed
