# 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.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..errors.too_many_requests_error import TooManyRequestsError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.browser_session_item_view import BrowserSessionItemView
from ..types.browser_session_list_response import BrowserSessionListResponse
from ..types.browser_session_status import BrowserSessionStatus
from ..types.browser_session_update_action import BrowserSessionUpdateAction
from ..types.browser_session_view import BrowserSessionView
from ..types.custom_proxy import CustomProxy
from ..types.proxy_country_code import ProxyCountryCode
from ..types.too_many_concurrent_active_sessions_error import TooManyConcurrentActiveSessionsError

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


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

    def list_browser_sessions(
        self,
        *,
        page_size: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        filter_by: typing.Optional[BrowserSessionStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BrowserSessionListResponse]:
        """
        Get paginated list of browser sessions with optional status filtering.

        Parameters
        ----------
        page_size : typing.Optional[int]

        page_number : typing.Optional[int]

        filter_by : typing.Optional[BrowserSessionStatus]

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

        Returns
        -------
        HttpResponse[BrowserSessionListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "browsers",
            method="GET",
            params={
                "pageSize": page_size,
                "pageNumber": page_number,
                "filterBy": filter_by,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionListResponse,
                    construct_type(
                        type_=BrowserSessionListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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)

    def create_browser_session(
        self,
        *,
        profile_id: typing.Optional[str] = OMIT,
        proxy_country_code: typing.Optional[ProxyCountryCode] = OMIT,
        timeout: typing.Optional[int] = OMIT,
        browser_screen_width: typing.Optional[int] = OMIT,
        browser_screen_height: typing.Optional[int] = OMIT,
        allow_resizing: typing.Optional[bool] = OMIT,
        custom_proxy: typing.Optional[CustomProxy] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BrowserSessionItemView]:
        """
        Create a new browser session.

        **Pricing:** Browser sessions are charged per hour with tiered pricing:
        - Pay As You Go users: $0.06/hour
        - Business/Scaleup subscribers: $0.03/hour (50% discount)

        The full rate is charged upfront when the session starts.
        When you stop the session, any unused time is automatically refunded proportionally.

        Billing is rounded up to the minute (minimum 1 minute).
        For example, if you stop a session after 30 minutes, you'll be refunded half the charged amount.

        **Session Limits:**
        - All users: Up to 4 hours per session

        Parameters
        ----------
        profile_id : typing.Optional[str]
            The ID of the profile to use for the session

        proxy_country_code : typing.Optional[ProxyCountryCode]
            Country code for proxy location.

        timeout : typing.Optional[int]
            The timeout for the session in minutes. All users can use up to 240 minutes (4 hours). Pay As You Go users are charged $0.06/hour, subscribers get 50% off.

        browser_screen_width : typing.Optional[int]
            Custom screen width in pixels for the browser.

        browser_screen_height : typing.Optional[int]
            Custom screen height in pixels for the browser.

        allow_resizing : typing.Optional[bool]
            Whether to allow the browser to be resized during the session (not recommended since it reduces stealthiness).

        custom_proxy : typing.Optional[CustomProxy]
            Custom proxy settings to use for the session. If not provided, our proxies will be used. Custom proxies are only available for Business and Scaleup subscribers.

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

        Returns
        -------
        HttpResponse[BrowserSessionItemView]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "browsers",
            method="POST",
            json={
                "profileId": profile_id,
                "proxyCountryCode": proxy_country_code,
                "timeout": timeout,
                "browserScreenWidth": browser_screen_width,
                "browserScreenHeight": browser_screen_height,
                "allowResizing": allow_resizing,
                "customProxy": convert_and_respect_annotation_metadata(
                    object_=custom_proxy, annotation=typing.Optional[CustomProxy], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionItemView,
                    construct_type(
                        type_=BrowserSessionItemView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        TooManyConcurrentActiveSessionsError,
                        construct_type(
                            type_=TooManyConcurrentActiveSessionsError,  # 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_browser_session(
        self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BrowserSessionView]:
        """
        Get detailed browser session information including status and URLs.

        Parameters
        ----------
        session_id : str

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

        Returns
        -------
        HttpResponse[BrowserSessionView]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"browsers/{jsonable_encoder(session_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionView,
                    construct_type(
                        type_=BrowserSessionView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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)

    def update_browser_session(
        self,
        session_id: str,
        *,
        action: BrowserSessionUpdateAction,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BrowserSessionView]:
        """
        Stop a browser session.

        **Refund:** When you stop a session, unused time is automatically refunded.
        If the session ran for less than 1 hour, you'll receive a proportional refund.
        Billing is ceil to the nearest minute (minimum 1 minute).

        Parameters
        ----------
        session_id : str

        action : BrowserSessionUpdateAction
            The action to perform on the session

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

        Returns
        -------
        HttpResponse[BrowserSessionView]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"browsers/{jsonable_encoder(session_id)}",
            method="PATCH",
            json={
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionView,
                    construct_type(
                        type_=BrowserSessionView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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 AsyncRawBrowsersClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_browser_sessions(
        self,
        *,
        page_size: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        filter_by: typing.Optional[BrowserSessionStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BrowserSessionListResponse]:
        """
        Get paginated list of browser sessions with optional status filtering.

        Parameters
        ----------
        page_size : typing.Optional[int]

        page_number : typing.Optional[int]

        filter_by : typing.Optional[BrowserSessionStatus]

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

        Returns
        -------
        AsyncHttpResponse[BrowserSessionListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "browsers",
            method="GET",
            params={
                "pageSize": page_size,
                "pageNumber": page_number,
                "filterBy": filter_by,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionListResponse,
                    construct_type(
                        type_=BrowserSessionListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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)

    async def create_browser_session(
        self,
        *,
        profile_id: typing.Optional[str] = OMIT,
        proxy_country_code: typing.Optional[ProxyCountryCode] = OMIT,
        timeout: typing.Optional[int] = OMIT,
        browser_screen_width: typing.Optional[int] = OMIT,
        browser_screen_height: typing.Optional[int] = OMIT,
        allow_resizing: typing.Optional[bool] = OMIT,
        custom_proxy: typing.Optional[CustomProxy] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BrowserSessionItemView]:
        """
        Create a new browser session.

        **Pricing:** Browser sessions are charged per hour with tiered pricing:
        - Pay As You Go users: $0.06/hour
        - Business/Scaleup subscribers: $0.03/hour (50% discount)

        The full rate is charged upfront when the session starts.
        When you stop the session, any unused time is automatically refunded proportionally.

        Billing is rounded up to the minute (minimum 1 minute).
        For example, if you stop a session after 30 minutes, you'll be refunded half the charged amount.

        **Session Limits:**
        - All users: Up to 4 hours per session

        Parameters
        ----------
        profile_id : typing.Optional[str]
            The ID of the profile to use for the session

        proxy_country_code : typing.Optional[ProxyCountryCode]
            Country code for proxy location.

        timeout : typing.Optional[int]
            The timeout for the session in minutes. All users can use up to 240 minutes (4 hours). Pay As You Go users are charged $0.06/hour, subscribers get 50% off.

        browser_screen_width : typing.Optional[int]
            Custom screen width in pixels for the browser.

        browser_screen_height : typing.Optional[int]
            Custom screen height in pixels for the browser.

        allow_resizing : typing.Optional[bool]
            Whether to allow the browser to be resized during the session (not recommended since it reduces stealthiness).

        custom_proxy : typing.Optional[CustomProxy]
            Custom proxy settings to use for the session. If not provided, our proxies will be used. Custom proxies are only available for Business and Scaleup subscribers.

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

        Returns
        -------
        AsyncHttpResponse[BrowserSessionItemView]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "browsers",
            method="POST",
            json={
                "profileId": profile_id,
                "proxyCountryCode": proxy_country_code,
                "timeout": timeout,
                "browserScreenWidth": browser_screen_width,
                "browserScreenHeight": browser_screen_height,
                "allowResizing": allow_resizing,
                "customProxy": convert_and_respect_annotation_metadata(
                    object_=custom_proxy, annotation=typing.Optional[CustomProxy], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionItemView,
                    construct_type(
                        type_=BrowserSessionItemView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        TooManyConcurrentActiveSessionsError,
                        construct_type(
                            type_=TooManyConcurrentActiveSessionsError,  # 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_browser_session(
        self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BrowserSessionView]:
        """
        Get detailed browser session information including status and URLs.

        Parameters
        ----------
        session_id : str

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

        Returns
        -------
        AsyncHttpResponse[BrowserSessionView]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"browsers/{jsonable_encoder(session_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionView,
                    construct_type(
                        type_=BrowserSessionView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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)

    async def update_browser_session(
        self,
        session_id: str,
        *,
        action: BrowserSessionUpdateAction,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BrowserSessionView]:
        """
        Stop a browser session.

        **Refund:** When you stop a session, unused time is automatically refunded.
        If the session ran for less than 1 hour, you'll receive a proportional refund.
        Billing is ceil to the nearest minute (minimum 1 minute).

        Parameters
        ----------
        session_id : str

        action : BrowserSessionUpdateAction
            The action to perform on the session

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

        Returns
        -------
        AsyncHttpResponse[BrowserSessionView]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"browsers/{jsonable_encoder(session_id)}",
            method="PATCH",
            json={
                "action": action,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BrowserSessionView,
                    construct_type(
                        type_=BrowserSessionView,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        construct_type(
                            type_=typing.Optional[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)
