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

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.cws_error_dto import CwsErrorDTO
from ...models.get_item_label_accept import GetItemLabelAccept
from ...types import Response


def _get_kwargs(
    item_id: str,
    *,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    accept: GetItemLabelAccept,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    headers["Authorization"] = authorization

    headers["accept"] = str(accept)

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/dpi/shipping/v1/items/{item_id}/label".format(
            item_id=quote(str(item_id), safe=""),
        ),
    }

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> CwsErrorDTO | str | None:
    if response.status_code == 200:
        response_200 = cast(str, response.json())
        return response_200

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

        return response_404

    if response.status_code == 500:
        response_500 = CwsErrorDTO.from_dict(response.json())

        return response_500

    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[CwsErrorDTO | str]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    item_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    accept: GetItemLabelAccept,
) -> Response[CwsErrorDTO | str]:
    """Get Item Label

     For a given item a label is generated or retrieved from the cache and send to the requestor as a
    bytestream response.

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        accept (GetItemLabelAccept):

    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[CwsErrorDTO | str]
    """

    kwargs = _get_kwargs(
        item_id=item_id,
        authorization=authorization,
        accept=accept,
    )

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

    return _build_response(client=client, response=response)


def sync(
    item_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    accept: GetItemLabelAccept,
) -> CwsErrorDTO | str | None:
    """Get Item Label

     For a given item a label is generated or retrieved from the cache and send to the requestor as a
    bytestream response.

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        accept (GetItemLabelAccept):

    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:
        CwsErrorDTO | str
    """

    return sync_detailed(
        item_id=item_id,
        client=client,
        authorization=authorization,
        accept=accept,
    ).parsed


async def asyncio_detailed(
    item_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    accept: GetItemLabelAccept,
) -> Response[CwsErrorDTO | str]:
    """Get Item Label

     For a given item a label is generated or retrieved from the cache and send to the requestor as a
    bytestream response.

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        accept (GetItemLabelAccept):

    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[CwsErrorDTO | str]
    """

    kwargs = _get_kwargs(
        item_id=item_id,
        authorization=authorization,
        accept=accept,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    item_id: str,
    *,
    client: AuthenticatedClient | Client,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
    accept: GetItemLabelAccept,
) -> CwsErrorDTO | str | None:
    """Get Item Label

     For a given item a label is generated or retrieved from the cache and send to the requestor as a
    bytestream response.

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        accept (GetItemLabelAccept):

    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:
        CwsErrorDTO | str
    """

    return (
        await asyncio_detailed(
            item_id=item_id,
            client=client,
            authorization=authorization,
            accept=accept,
        )
    ).parsed
