# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.payment_required_error import PaymentRequiredError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.error import Error
from ..types.phone_enum import PhoneEnum
from ..types.phone_feature_enum import PhoneFeatureEnum
from ..types.phone_number_details import PhoneNumberDetails
from ..types.purchased_number import PurchasedNumber
from .types.phone_details_schema_level import PhoneDetailsSchemaLevel
from .types.phone_numbers_get_response import PhoneNumbersGetResponse
from .types.retrieve_phone_number_details_options import RetrievePhoneNumberDetailsOptions
from .types.search_phone_number_by_digits import SearchPhoneNumberByDigits
from .types.search_phone_number_by_location import SearchPhoneNumberByLocation
from .types.search_phone_number_options import SearchPhoneNumberOptions

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


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

    def search(
        self,
        *,
        type: typing.Sequence[PhoneEnum],
        features: typing.Optional[typing.Sequence[PhoneFeatureEnum]] = OMIT,
        location: typing.Optional[SearchPhoneNumberByLocation] = OMIT,
        number: typing.Optional[SearchPhoneNumberByDigits] = OMIT,
        options: typing.Optional[SearchPhoneNumberOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[PhoneNumberDetails]]:
        """
        Search for available phone numbers that match your exact criteria.

        Parameters
        ----------
        type : typing.Sequence[PhoneEnum]
            Types of phone numbers to return in your search.

        features : typing.Optional[typing.Sequence[PhoneFeatureEnum]]

        location : typing.Optional[SearchPhoneNumberByLocation]
            Filter your search by geographic location to find numbers in specific regions. <br>

            Toll-free numbers ignore city and state filters.

        number : typing.Optional[SearchPhoneNumberByDigits]
            Filter your search by digit pattern.

        options : typing.Optional[SearchPhoneNumberOptions]
            Extra search settings to control how many results you get.

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

        Returns
        -------
        HttpResponse[typing.List[PhoneNumberDetails]]
            Returns a **list** of available phone numbers that match the search criteria. <br>

            Use our [buy endpoint](./buy) to purchase any amount of phone numbers that you like.
        """
        _response = self._client_wrapper.httpx_client.request(
            "phone-numbers/search",
            method="POST",
            json={
                "features": features,
                "location": convert_and_respect_annotation_metadata(
                    object_=location, annotation=SearchPhoneNumberByLocation, direction="write"
                ),
                "number": convert_and_respect_annotation_metadata(
                    object_=number, annotation=SearchPhoneNumberByDigits, direction="write"
                ),
                "options": convert_and_respect_annotation_metadata(
                    object_=options, annotation=SearchPhoneNumberOptions, direction="write"
                ),
                "type": type,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[PhoneNumberDetails],
                    parse_obj_as(
                        type_=typing.List[PhoneNumberDetails],  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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 buy(
        self, *, numbers: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.List[PurchasedNumber]]:
        """
        Purchase one or more phone numbers found through the [search endpoint](./search). <br>

        Billing uses your account credits and the numbers are ready for immediate use.

        Parameters
        ----------
        numbers : typing.Sequence[str]
            List of phone numbers you want to purchase, each in international E.164 format. <br>

            All specified numbers must be currently available and will be validated for availability before processing the purchase. <br>

            If any number in the request is unavailable or invalid, no purchases will be made and the request will be voided.

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

        Returns
        -------
        HttpResponse[typing.List[PurchasedNumber]]
            Successfully purchased the number(s).
        """
        _response = self._client_wrapper.httpx_client.request(
            "phone-numbers/buy",
            method="POST",
            json={
                "numbers": numbers,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[PurchasedNumber],
                    parse_obj_as(
                        type_=typing.List[PurchasedNumber],  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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(
        self,
        *,
        phone: str,
        level: PhoneDetailsSchemaLevel,
        options: typing.Optional[RetrievePhoneNumberDetailsOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PhoneNumbersGetResponse]:
        """
        Retrieve information about any phone number.

        Parameters
        ----------
        phone : str
            Phone number you want to analyze in E.164 format.

        level : PhoneDetailsSchemaLevel
            Choose how much detail you want in your results:
            - `basic`: Receive essential info like carrier, location, and format.
            - `advanced`: Receive a deeper analysis including fraud risk, detailed location, and enhanced contact info.

        options : typing.Optional[RetrievePhoneNumberDetailsOptions]
            Customize your lookup with additional options.

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

        Returns
        -------
        HttpResponse[PhoneNumbersGetResponse]
            Returns detailed information for the requested phone number based on the selected lookup.
        """
        _response = self._client_wrapper.httpx_client.request(
            "phone-numbers/details",
            method="POST",
            json={
                "phone": phone,
                "level": level,
                "options": convert_and_respect_annotation_metadata(
                    object_=options, annotation=RetrievePhoneNumberDetailsOptions, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PhoneNumbersGetResponse,
                    parse_obj_as(
                        type_=PhoneNumbersGetResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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)


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

    async def search(
        self,
        *,
        type: typing.Sequence[PhoneEnum],
        features: typing.Optional[typing.Sequence[PhoneFeatureEnum]] = OMIT,
        location: typing.Optional[SearchPhoneNumberByLocation] = OMIT,
        number: typing.Optional[SearchPhoneNumberByDigits] = OMIT,
        options: typing.Optional[SearchPhoneNumberOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[PhoneNumberDetails]]:
        """
        Search for available phone numbers that match your exact criteria.

        Parameters
        ----------
        type : typing.Sequence[PhoneEnum]
            Types of phone numbers to return in your search.

        features : typing.Optional[typing.Sequence[PhoneFeatureEnum]]

        location : typing.Optional[SearchPhoneNumberByLocation]
            Filter your search by geographic location to find numbers in specific regions. <br>

            Toll-free numbers ignore city and state filters.

        number : typing.Optional[SearchPhoneNumberByDigits]
            Filter your search by digit pattern.

        options : typing.Optional[SearchPhoneNumberOptions]
            Extra search settings to control how many results you get.

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

        Returns
        -------
        AsyncHttpResponse[typing.List[PhoneNumberDetails]]
            Returns a **list** of available phone numbers that match the search criteria. <br>

            Use our [buy endpoint](./buy) to purchase any amount of phone numbers that you like.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "phone-numbers/search",
            method="POST",
            json={
                "features": features,
                "location": convert_and_respect_annotation_metadata(
                    object_=location, annotation=SearchPhoneNumberByLocation, direction="write"
                ),
                "number": convert_and_respect_annotation_metadata(
                    object_=number, annotation=SearchPhoneNumberByDigits, direction="write"
                ),
                "options": convert_and_respect_annotation_metadata(
                    object_=options, annotation=SearchPhoneNumberOptions, direction="write"
                ),
                "type": type,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[PhoneNumberDetails],
                    parse_obj_as(
                        type_=typing.List[PhoneNumberDetails],  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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 buy(
        self, *, numbers: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.List[PurchasedNumber]]:
        """
        Purchase one or more phone numbers found through the [search endpoint](./search). <br>

        Billing uses your account credits and the numbers are ready for immediate use.

        Parameters
        ----------
        numbers : typing.Sequence[str]
            List of phone numbers you want to purchase, each in international E.164 format. <br>

            All specified numbers must be currently available and will be validated for availability before processing the purchase. <br>

            If any number in the request is unavailable or invalid, no purchases will be made and the request will be voided.

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

        Returns
        -------
        AsyncHttpResponse[typing.List[PurchasedNumber]]
            Successfully purchased the number(s).
        """
        _response = await self._client_wrapper.httpx_client.request(
            "phone-numbers/buy",
            method="POST",
            json={
                "numbers": numbers,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[PurchasedNumber],
                    parse_obj_as(
                        type_=typing.List[PurchasedNumber],  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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(
        self,
        *,
        phone: str,
        level: PhoneDetailsSchemaLevel,
        options: typing.Optional[RetrievePhoneNumberDetailsOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PhoneNumbersGetResponse]:
        """
        Retrieve information about any phone number.

        Parameters
        ----------
        phone : str
            Phone number you want to analyze in E.164 format.

        level : PhoneDetailsSchemaLevel
            Choose how much detail you want in your results:
            - `basic`: Receive essential info like carrier, location, and format.
            - `advanced`: Receive a deeper analysis including fraud risk, detailed location, and enhanced contact info.

        options : typing.Optional[RetrievePhoneNumberDetailsOptions]
            Customize your lookup with additional options.

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

        Returns
        -------
        AsyncHttpResponse[PhoneNumbersGetResponse]
            Returns detailed information for the requested phone number based on the selected lookup.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "phone-numbers/details",
            method="POST",
            json={
                "phone": phone,
                "level": level,
                "options": convert_and_respect_annotation_metadata(
                    object_=options, annotation=RetrievePhoneNumberDetailsOptions, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PhoneNumbersGetResponse,
                    parse_obj_as(
                        type_=PhoneNumbersGetResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            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)
