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 ...models.item import Item
from ...types import Response


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

    _kwargs: dict[str, Any] = {
        "method": "put",
        "url": "/dpi/shipping/v1/items/{item_id}".format(
            item_id=quote(str(item_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) -> CwsErrorDTO | Item | None:
    if response.status_code == 200:
        response_200 = Item.from_dict(response.json())

        return response_200

    if response.status_code == 403:
        response_403 = CwsErrorDTO.from_dict(response.json())

        return response_403

    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 | Item]:
    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,
    body: Item,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> Response[CwsErrorDTO | Item]:
    """Update item

     Updates the item for the specified item id. <br><br>This operation only works for items attached to
    orders that are in the OPEN state. Called on items of orders in the FINALIZED state leads to an 404
    error (an item with the desired attributes cannot be found). The following fields are not updatable:
    product, serviceLevel, destinationCountry

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        body (Item):  Example: {'product': 'GPT', 'serviceLevel': 'PRIORITY', 'recipient': 'Doris
            Bronson', 'addressLine1': 'Uptown street 10', 'addressLine2': '2nd floor', 'postalCode':
            'SW1A 2AA', 'city': 'London', 'destinationCountry': 'GB', 'custRef': 'BRE-2021-XIT',
            'recipientPhone': '+441234567890', 'recipientEmail': 'doris@somewhere.non.eu',
            'senderTaxId': 'IOSS number', 'importerTaxId': 'IOSS number', 'shipmentAmount': 100,
            'shipmentCurrency': 'EUR', 'shipmentGrossWeight': 1500, 'returnItemWanted': False,
            'shipmentNaturetype': 'SALE_GOODS', 'contents': [{'contentPieceHsCode': 1234567890,
            'contentPieceDescription': 'Hairspray', 'contentPieceValue': '120.50',
            'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE', 'contentPieceAmount': 2}]}.

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

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

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

    return _build_response(client=client, response=response)


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

     Updates the item for the specified item id. <br><br>This operation only works for items attached to
    orders that are in the OPEN state. Called on items of orders in the FINALIZED state leads to an 404
    error (an item with the desired attributes cannot be found). The following fields are not updatable:
    product, serviceLevel, destinationCountry

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        body (Item):  Example: {'product': 'GPT', 'serviceLevel': 'PRIORITY', 'recipient': 'Doris
            Bronson', 'addressLine1': 'Uptown street 10', 'addressLine2': '2nd floor', 'postalCode':
            'SW1A 2AA', 'city': 'London', 'destinationCountry': 'GB', 'custRef': 'BRE-2021-XIT',
            'recipientPhone': '+441234567890', 'recipientEmail': 'doris@somewhere.non.eu',
            'senderTaxId': 'IOSS number', 'importerTaxId': 'IOSS number', 'shipmentAmount': 100,
            'shipmentCurrency': 'EUR', 'shipmentGrossWeight': 1500, 'returnItemWanted': False,
            'shipmentNaturetype': 'SALE_GOODS', 'contents': [{'contentPieceHsCode': 1234567890,
            'contentPieceDescription': 'Hairspray', 'contentPieceValue': '120.50',
            'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE', 'contentPieceAmount': 2}]}.

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

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


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

     Updates the item for the specified item id. <br><br>This operation only works for items attached to
    orders that are in the OPEN state. Called on items of orders in the FINALIZED state leads to an 404
    error (an item with the desired attributes cannot be found). The following fields are not updatable:
    product, serviceLevel, destinationCountry

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        body (Item):  Example: {'product': 'GPT', 'serviceLevel': 'PRIORITY', 'recipient': 'Doris
            Bronson', 'addressLine1': 'Uptown street 10', 'addressLine2': '2nd floor', 'postalCode':
            'SW1A 2AA', 'city': 'London', 'destinationCountry': 'GB', 'custRef': 'BRE-2021-XIT',
            'recipientPhone': '+441234567890', 'recipientEmail': 'doris@somewhere.non.eu',
            'senderTaxId': 'IOSS number', 'importerTaxId': 'IOSS number', 'shipmentAmount': 100,
            'shipmentCurrency': 'EUR', 'shipmentGrossWeight': 1500, 'returnItemWanted': False,
            'shipmentNaturetype': 'SALE_GOODS', 'contents': [{'contentPieceHsCode': 1234567890,
            'contentPieceDescription': 'Hairspray', 'contentPieceValue': '120.50',
            'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE', 'contentPieceAmount': 2}]}.

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

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

    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,
    body: Item,
    authorization: str = "Bearer [place  OAuth access_token here, without brackets]",
) -> CwsErrorDTO | Item | None:
    """Update item

     Updates the item for the specified item id. <br><br>This operation only works for items attached to
    orders that are in the OPEN state. Called on items of orders in the FINALIZED state leads to an 404
    error (an item with the desired attributes cannot be found). The following fields are not updatable:
    product, serviceLevel, destinationCountry

    Args:
        item_id (str):
        authorization (str):  Default: 'Bearer [place  OAuth access_token here, without
            brackets]'.
        body (Item):  Example: {'product': 'GPT', 'serviceLevel': 'PRIORITY', 'recipient': 'Doris
            Bronson', 'addressLine1': 'Uptown street 10', 'addressLine2': '2nd floor', 'postalCode':
            'SW1A 2AA', 'city': 'London', 'destinationCountry': 'GB', 'custRef': 'BRE-2021-XIT',
            'recipientPhone': '+441234567890', 'recipientEmail': 'doris@somewhere.non.eu',
            'senderTaxId': 'IOSS number', 'importerTaxId': 'IOSS number', 'shipmentAmount': 100,
            'shipmentCurrency': 'EUR', 'shipmentGrossWeight': 1500, 'returnItemWanted': False,
            'shipmentNaturetype': 'SALE_GOODS', 'contents': [{'contentPieceHsCode': 1234567890,
            'contentPieceDescription': 'Hairspray', 'contentPieceValue': '120.50',
            'contentPieceNetweight': 1200, 'contentPieceOrigin': 'DE', 'contentPieceAmount': 2}]}.

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

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