# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.composio_sync_response import ComposioSyncResponse
from ..types.composio_sync_status_response import ComposioSyncStatusResponse
from ..types.list_auth_configs_response import ListAuthConfigsResponse
from ..types.update_tool_status_response import UpdateToolStatusResponse

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


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

    def trigger_connector_sync(
        self,
        *,
        force_full_sync: typing.Optional[bool] = None,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ComposioSyncResponse]:
        """
        Trigger connector tool catalog sync.

        Syncs available tools into the local database.
        By default, uses incremental sync which only updates changed tools.
        Use force_full_sync=true to update all tools regardless of changes.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Args:
            force_full_sync: If true, skip incremental checks and update all tools

        Returns:
            Response with job_id and sync statistics

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        force_full_sync : typing.Optional[bool]
            Force full sync, ignoring incremental checks and interval

        api_key : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[ComposioSyncResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/admin/composio/sync",
            method="POST",
            params={
                "force_full_sync": force_full_sync,
            },
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ComposioSyncResponse,
                    parse_obj_as(
                        type_=ComposioSyncResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    def get_sync_status(
        self, *, api_key: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ComposioSyncStatusResponse]:
        """
        Get connector sync status and statistics.

        Returns information about the last sync, next scheduled sync,
        and tool counts.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Returns:
            Response with sync status information

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        api_key : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[ComposioSyncStatusResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/admin/composio/sync/status",
            method="GET",
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ComposioSyncStatusResponse,
                    parse_obj_as(
                        type_=ComposioSyncStatusResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    def list_auth_configs(
        self, *, api_key: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ListAuthConfigsResponse]:
        """
        List all connector auth configs in the project.

        This endpoint helps debug auth config issues and verify which configs
        are available for use. Useful for troubleshooting custom branding issues.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Returns:
            List of all auth configs with their IDs, toolkits, and types

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        api_key : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[ListAuthConfigsResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/admin/composio/auth-configs",
            method="GET",
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListAuthConfigsResponse,
                    parse_obj_as(
                        type_=ListAuthConfigsResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    def update_tool_status(
        self,
        tool_key: str,
        *,
        is_enabled: bool,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[UpdateToolStatusResponse]:
        """
        Enable or disable a connector tool.

        Controls whether a tool appears in the /v1/personal-connectors/available endpoint.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Args:
            tool_key: The tool key (e.g., "slack", "github", "notion")
            request: Request body with is_enabled boolean

        Returns:
            Updated tool status

        Raises:
            AuthenticationException: If admin API key is missing or invalid
            ResourceNotFoundException: If tool not found

        Parameters
        ----------
        tool_key : str

        is_enabled : bool

        api_key : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[UpdateToolStatusResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/admin/composio/tools/{jsonable_encoder(tool_key)}/status",
            method="PATCH",
            json={
                "is_enabled": is_enabled,
            },
            headers={
                "content-type": "application/json",
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpdateToolStatusResponse,
                    parse_obj_as(
                        type_=UpdateToolStatusResponse,  # 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.Any,
                        parse_obj_as(
                            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 AsyncRawAdminConnectorsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def trigger_connector_sync(
        self,
        *,
        force_full_sync: typing.Optional[bool] = None,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ComposioSyncResponse]:
        """
        Trigger connector tool catalog sync.

        Syncs available tools into the local database.
        By default, uses incremental sync which only updates changed tools.
        Use force_full_sync=true to update all tools regardless of changes.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Args:
            force_full_sync: If true, skip incremental checks and update all tools

        Returns:
            Response with job_id and sync statistics

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        force_full_sync : typing.Optional[bool]
            Force full sync, ignoring incremental checks and interval

        api_key : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[ComposioSyncResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/admin/composio/sync",
            method="POST",
            params={
                "force_full_sync": force_full_sync,
            },
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ComposioSyncResponse,
                    parse_obj_as(
                        type_=ComposioSyncResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    async def get_sync_status(
        self, *, api_key: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ComposioSyncStatusResponse]:
        """
        Get connector sync status and statistics.

        Returns information about the last sync, next scheduled sync,
        and tool counts.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Returns:
            Response with sync status information

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        api_key : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[ComposioSyncStatusResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/admin/composio/sync/status",
            method="GET",
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ComposioSyncStatusResponse,
                    parse_obj_as(
                        type_=ComposioSyncStatusResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    async def list_auth_configs(
        self, *, api_key: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ListAuthConfigsResponse]:
        """
        List all connector auth configs in the project.

        This endpoint helps debug auth config issues and verify which configs
        are available for use. Useful for troubleshooting custom branding issues.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Returns:
            List of all auth configs with their IDs, toolkits, and types

        Raises:
            AuthenticationException: If admin API key is missing or invalid

        Parameters
        ----------
        api_key : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[ListAuthConfigsResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/admin/composio/auth-configs",
            method="GET",
            headers={
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListAuthConfigsResponse,
                    parse_obj_as(
                        type_=ListAuthConfigsResponse,  # 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.Any,
                        parse_obj_as(
                            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)

    async def update_tool_status(
        self,
        tool_key: str,
        *,
        is_enabled: bool,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[UpdateToolStatusResponse]:
        """
        Enable or disable a connector tool.

        Controls whether a tool appears in the /v1/personal-connectors/available endpoint.

        Requires:
        - Header: api-key: {ADMIN_API_KEY}

        Args:
            tool_key: The tool key (e.g., "slack", "github", "notion")
            request: Request body with is_enabled boolean

        Returns:
            Updated tool status

        Raises:
            AuthenticationException: If admin API key is missing or invalid
            ResourceNotFoundException: If tool not found

        Parameters
        ----------
        tool_key : str

        is_enabled : bool

        api_key : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[UpdateToolStatusResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/admin/composio/tools/{jsonable_encoder(tool_key)}/status",
            method="PATCH",
            json={
                "is_enabled": is_enabled,
            },
            headers={
                "content-type": "application/json",
                "api-key": str(api_key) if api_key is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpdateToolStatusResponse,
                    parse_obj_as(
                        type_=UpdateToolStatusResponse,  # 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.Any,
                        parse_obj_as(
                            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)
