# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.error import Error
from .types.macro import Macro
from .types.macro_list import MacroList


class RawMacrosClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list_macros(
        self,
        *,
        per_page: typing.Optional[int] = None,
        starting_after: typing.Optional[str] = None,
        updated_since: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[MacroList]:
        """
        You can fetch a list of all macros (saved replies) in your workspace for use in automating responses.

        The macros are returned in descending order by updated_at.

        **Pagination**

        This endpoint uses cursor-based pagination via the `starting_after` parameter. The cursor is a Base64-encoded JSON array containing `[updated_at, id]` of the last item from the previous page.

        **Placeholder Transformation**

        The API transforms Intercom placeholders to a more standard XML-like format:
        - From: `{{user.name | fallback: 'there'}}`
        - To: `<attribute key="user.name" default="there"/>`

        Parameters
        ----------
        per_page : typing.Optional[int]
            The number of results per page

        starting_after : typing.Optional[str]
            Base64-encoded cursor containing [updated_at, id] for pagination

        updated_since : typing.Optional[int]
            Unix timestamp to filter macros updated after this time

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[MacroList]
            Successful response
        """
        _response = self._client_wrapper.httpx_client.request(
            "macros",
            method="GET",
            params={
                "per_page": per_page,
                "starting_after": starting_after,
                "updated_since": updated_since,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MacroList,
                    construct_type(
                        type_=MacroList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_macro(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Optional[Macro]]:
        """
        You can fetch a single macro (saved reply) by its ID. The macro will only be returned if it is visible to the authenticated user based on its visibility settings.

        **Visibility Rules**

        A macro is returned based on its `visible_to` setting:
        - `everyone`: Always visible to all team members
        - `specific_teams`: Only visible if the authenticated user belongs to one of the teams specified in `visible_to_team_ids`

        If a macro exists but is not visible to the authenticated user, a 404 error is returned.

        **Placeholder Transformation**

        The API transforms Intercom placeholders to a more standard XML-like format in the `body` field:
        - From: `{{user.name | fallback: 'there'}}`
        - To: `<attribute key="user.name" default="there"/>`

        Default values in placeholders are HTML-escaped for security.

        Parameters
        ----------
        id : str
            The unique identifier of the macro

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Optional[Macro]]
            Macro found
        """
        _response = self._client_wrapper.httpx_client.request(
            f"macros/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[Macro],
                    construct_type(
                        type_=typing.Optional[Macro],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawMacrosClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_macros(
        self,
        *,
        per_page: typing.Optional[int] = None,
        starting_after: typing.Optional[str] = None,
        updated_since: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[MacroList]:
        """
        You can fetch a list of all macros (saved replies) in your workspace for use in automating responses.

        The macros are returned in descending order by updated_at.

        **Pagination**

        This endpoint uses cursor-based pagination via the `starting_after` parameter. The cursor is a Base64-encoded JSON array containing `[updated_at, id]` of the last item from the previous page.

        **Placeholder Transformation**

        The API transforms Intercom placeholders to a more standard XML-like format:
        - From: `{{user.name | fallback: 'there'}}`
        - To: `<attribute key="user.name" default="there"/>`

        Parameters
        ----------
        per_page : typing.Optional[int]
            The number of results per page

        starting_after : typing.Optional[str]
            Base64-encoded cursor containing [updated_at, id] for pagination

        updated_since : typing.Optional[int]
            Unix timestamp to filter macros updated after this time

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[MacroList]
            Successful response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "macros",
            method="GET",
            params={
                "per_page": per_page,
                "starting_after": starting_after,
                "updated_since": updated_since,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MacroList,
                    construct_type(
                        type_=MacroList,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_macro(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Optional[Macro]]:
        """
        You can fetch a single macro (saved reply) by its ID. The macro will only be returned if it is visible to the authenticated user based on its visibility settings.

        **Visibility Rules**

        A macro is returned based on its `visible_to` setting:
        - `everyone`: Always visible to all team members
        - `specific_teams`: Only visible if the authenticated user belongs to one of the teams specified in `visible_to_team_ids`

        If a macro exists but is not visible to the authenticated user, a 404 error is returned.

        **Placeholder Transformation**

        The API transforms Intercom placeholders to a more standard XML-like format in the `body` field:
        - From: `{{user.name | fallback: 'there'}}`
        - To: `<attribute key="user.name" default="there"/>`

        Default values in placeholders are HTML-escaped for security.

        Parameters
        ----------
        id : str
            The unique identifier of the macro

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Optional[Macro]]
            Macro found
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"macros/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[Macro],
                    construct_type(
                        type_=typing.Optional[Macro],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        construct_type(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
