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

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.all_configs import AllConfigs
from ...models.http_validation_error import HTTPValidationError
from ...models.non_developer_config import NonDeveloperConfig
from ...types import Response


def _get_kwargs(
    config_ext_id: str,
) -> dict[str, Any]:
    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/api/configs/{config_ext_id}".format(
            config_ext_id=quote(str(config_ext_id), safe=""),
        ),
    }

    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> AllConfigs | NonDeveloperConfig | HTTPValidationError | None:
    if response.status_code == 200:

        def _parse_response_200(data: object) -> AllConfigs | NonDeveloperConfig:
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                response_200_type_0 = AllConfigs.from_dict(data)

                return response_200_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            if not isinstance(data, dict):
                raise TypeError()
            response_200_type_1 = NonDeveloperConfig.from_dict(data)

            return response_200_type_1

        response_200 = _parse_response_200(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[AllConfigs | NonDeveloperConfig | 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(
    config_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
) -> Response[AllConfigs | NonDeveloperConfig | HTTPValidationError]:
    """Get Configs

     Read configurations from database to be displayed in the UI

    Args:
        config_ext_id (str): Config name: 'cfg-XXXXXXXX' or 'default' for system default

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

    kwargs = _get_kwargs(
        config_ext_id=config_ext_id,
    )

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

    return _build_response(client=client, response=response)


def sync(
    config_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
) -> AllConfigs | NonDeveloperConfig | HTTPValidationError | None:
    """Get Configs

     Read configurations from database to be displayed in the UI

    Args:
        config_ext_id (str): Config name: 'cfg-XXXXXXXX' or 'default' for system default

    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:
        AllConfigs | NonDeveloperConfig | HTTPValidationError
    """

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


async def asyncio_detailed(
    config_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
) -> Response[AllConfigs | NonDeveloperConfig | HTTPValidationError]:
    """Get Configs

     Read configurations from database to be displayed in the UI

    Args:
        config_ext_id (str): Config name: 'cfg-XXXXXXXX' or 'default' for system default

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

    kwargs = _get_kwargs(
        config_ext_id=config_ext_id,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    config_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
) -> AllConfigs | NonDeveloperConfig | HTTPValidationError | None:
    """Get Configs

     Read configurations from database to be displayed in the UI

    Args:
        config_ext_id (str): Config name: 'cfg-XXXXXXXX' or 'default' for system default

    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:
        AllConfigs | NonDeveloperConfig | HTTPValidationError
    """

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