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.cws_error_dto import CwsErrorDTO
from ...types import UNSET, Response, Unset


def _get_kwargs(
    barcode: str,
    *,
    language: str | Unset = "en",
    with_event_type: bool | Unset = False,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    headers["Authorization"] = authorization

    params: dict[str, Any] = {}

    params["language"] = language

    params["withEventType"] = with_event_type

    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": "/dpi/tracking/v3/trackings/{barcode}".format(
            barcode=quote(str(barcode), safe=""),
        ),
        "params": params,
    }

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> CwsErrorDTO | None:
    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]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    barcode: str,
    *,
    client: AuthenticatedClient | Client,
    language: str | Unset = "en",
    with_event_type: bool | Unset = False,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> Response[CwsErrorDTO]:
    """Get Trackings V3

     Get all tracking information for the item (identified by the given barcode). More detailed breakdown
    of track events compared to v1 but possibly more inconsisteny, duplicity and wrong tracking order

    Args:
        barcode (str):
        language (str | Unset):  Default: 'en'.
        with_event_type (bool | Unset):  Default: False.
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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]
    """

    kwargs = _get_kwargs(
        barcode=barcode,
        language=language,
        with_event_type=with_event_type,
        authorization=authorization,
    )

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

    return _build_response(client=client, response=response)


def sync(
    barcode: str,
    *,
    client: AuthenticatedClient | Client,
    language: str | Unset = "en",
    with_event_type: bool | Unset = False,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> CwsErrorDTO | None:
    """Get Trackings V3

     Get all tracking information for the item (identified by the given barcode). More detailed breakdown
    of track events compared to v1 but possibly more inconsisteny, duplicity and wrong tracking order

    Args:
        barcode (str):
        language (str | Unset):  Default: 'en'.
        with_event_type (bool | Unset):  Default: False.
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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
    """

    return sync_detailed(
        barcode=barcode,
        client=client,
        language=language,
        with_event_type=with_event_type,
        authorization=authorization,
    ).parsed


async def asyncio_detailed(
    barcode: str,
    *,
    client: AuthenticatedClient | Client,
    language: str | Unset = "en",
    with_event_type: bool | Unset = False,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> Response[CwsErrorDTO]:
    """Get Trackings V3

     Get all tracking information for the item (identified by the given barcode). More detailed breakdown
    of track events compared to v1 but possibly more inconsisteny, duplicity and wrong tracking order

    Args:
        barcode (str):
        language (str | Unset):  Default: 'en'.
        with_event_type (bool | Unset):  Default: False.
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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]
    """

    kwargs = _get_kwargs(
        barcode=barcode,
        language=language,
        with_event_type=with_event_type,
        authorization=authorization,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    barcode: str,
    *,
    client: AuthenticatedClient | Client,
    language: str | Unset = "en",
    with_event_type: bool | Unset = False,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> CwsErrorDTO | None:
    """Get Trackings V3

     Get all tracking information for the item (identified by the given barcode). More detailed breakdown
    of track events compared to v1 but possibly more inconsisteny, duplicity and wrong tracking order

    Args:
        barcode (str):
        language (str | Unset):  Default: 'en'.
        with_event_type (bool | Unset):  Default: False.
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.

    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
    """

    return (
        await asyncio_detailed(
            barcode=barcode,
            client=client,
            language=language,
            with_event_type=with_event_type,
            authorization=authorization,
        )
    ).parsed
