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

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from ..commons.errors.access_denied_error import AccessDeniedError
from ..commons.errors.error import Error
from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
from ..commons.errors.not_found_error import NotFoundError
from ..commons.errors.unauthorized_error import UnauthorizedError
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 .types.blob_storage_export_frequency import BlobStorageExportFrequency
from .types.blob_storage_export_mode import BlobStorageExportMode
from .types.blob_storage_integration_deletion_response import (
    BlobStorageIntegrationDeletionResponse,
)
from .types.blob_storage_integration_file_type import BlobStorageIntegrationFileType
from .types.blob_storage_integration_response import BlobStorageIntegrationResponse
from .types.blob_storage_integration_type import BlobStorageIntegrationType
from .types.blob_storage_integrations_response import BlobStorageIntegrationsResponse

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


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

    def get_blob_storage_integrations(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BlobStorageIntegrationsResponse]:
        """
        Get all blob storage integrations for the organization (requires organization-scoped API key)

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

        Returns
        -------
        HttpResponse[BlobStorageIntegrationsResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/public/integrations/blob-storage",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationsResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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 upsert_blob_storage_integration(
        self,
        *,
        project_id: str,
        type: BlobStorageIntegrationType,
        bucket_name: str,
        region: str,
        export_frequency: BlobStorageExportFrequency,
        enabled: bool,
        force_path_style: bool,
        file_type: BlobStorageIntegrationFileType,
        export_mode: BlobStorageExportMode,
        endpoint: typing.Optional[str] = OMIT,
        access_key_id: typing.Optional[str] = OMIT,
        secret_access_key: typing.Optional[str] = OMIT,
        prefix: typing.Optional[str] = OMIT,
        export_start_date: typing.Optional[dt.datetime] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BlobStorageIntegrationResponse]:
        """
        Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket.

        Parameters
        ----------
        project_id : str
            ID of the project in which to configure the blob storage integration

        type : BlobStorageIntegrationType

        bucket_name : str
            Name of the storage bucket

        region : str
            Storage region

        export_frequency : BlobStorageExportFrequency

        enabled : bool
            Whether the integration is active

        force_path_style : bool
            Use path-style URLs for S3 requests

        file_type : BlobStorageIntegrationFileType

        export_mode : BlobStorageExportMode

        endpoint : typing.Optional[str]
            Custom endpoint URL (required for S3_COMPATIBLE type)

        access_key_id : typing.Optional[str]
            Access key ID for authentication

        secret_access_key : typing.Optional[str]
            Secret access key for authentication (will be encrypted when stored)

        prefix : typing.Optional[str]
            Path prefix for exported files (must end with forward slash if provided)

        export_start_date : typing.Optional[dt.datetime]
            Custom start date for exports (required when exportMode is FROM_CUSTOM_DATE)

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

        Returns
        -------
        HttpResponse[BlobStorageIntegrationResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/public/integrations/blob-storage",
            method="PUT",
            json={
                "projectId": project_id,
                "type": type,
                "bucketName": bucket_name,
                "endpoint": endpoint,
                "region": region,
                "accessKeyId": access_key_id,
                "secretAccessKey": secret_access_key,
                "prefix": prefix,
                "exportFrequency": export_frequency,
                "enabled": enabled,
                "forcePathStyle": force_path_style,
                "fileType": file_type,
                "exportMode": export_mode,
                "exportStartDate": export_start_date,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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 delete_blob_storage_integration(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BlobStorageIntegrationDeletionResponse]:
        """
        Delete a blob storage integration by ID (requires organization-scoped API key)

        Parameters
        ----------
        id : str

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

        Returns
        -------
        HttpResponse[BlobStorageIntegrationDeletionResponse]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/public/integrations/blob-storage/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationDeletionResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationDeletionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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 AsyncRawBlobStorageIntegrationsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_blob_storage_integrations(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BlobStorageIntegrationsResponse]:
        """
        Get all blob storage integrations for the organization (requires organization-scoped API key)

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

        Returns
        -------
        AsyncHttpResponse[BlobStorageIntegrationsResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/public/integrations/blob-storage",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationsResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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 upsert_blob_storage_integration(
        self,
        *,
        project_id: str,
        type: BlobStorageIntegrationType,
        bucket_name: str,
        region: str,
        export_frequency: BlobStorageExportFrequency,
        enabled: bool,
        force_path_style: bool,
        file_type: BlobStorageIntegrationFileType,
        export_mode: BlobStorageExportMode,
        endpoint: typing.Optional[str] = OMIT,
        access_key_id: typing.Optional[str] = OMIT,
        secret_access_key: typing.Optional[str] = OMIT,
        prefix: typing.Optional[str] = OMIT,
        export_start_date: typing.Optional[dt.datetime] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BlobStorageIntegrationResponse]:
        """
        Create or update a blob storage integration for a specific project (requires organization-scoped API key). The configuration is validated by performing a test upload to the bucket.

        Parameters
        ----------
        project_id : str
            ID of the project in which to configure the blob storage integration

        type : BlobStorageIntegrationType

        bucket_name : str
            Name of the storage bucket

        region : str
            Storage region

        export_frequency : BlobStorageExportFrequency

        enabled : bool
            Whether the integration is active

        force_path_style : bool
            Use path-style URLs for S3 requests

        file_type : BlobStorageIntegrationFileType

        export_mode : BlobStorageExportMode

        endpoint : typing.Optional[str]
            Custom endpoint URL (required for S3_COMPATIBLE type)

        access_key_id : typing.Optional[str]
            Access key ID for authentication

        secret_access_key : typing.Optional[str]
            Secret access key for authentication (will be encrypted when stored)

        prefix : typing.Optional[str]
            Path prefix for exported files (must end with forward slash if provided)

        export_start_date : typing.Optional[dt.datetime]
            Custom start date for exports (required when exportMode is FROM_CUSTOM_DATE)

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

        Returns
        -------
        AsyncHttpResponse[BlobStorageIntegrationResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/public/integrations/blob-storage",
            method="PUT",
            json={
                "projectId": project_id,
                "type": type,
                "bucketName": bucket_name,
                "endpoint": endpoint,
                "region": region,
                "accessKeyId": access_key_id,
                "secretAccessKey": secret_access_key,
                "prefix": prefix,
                "exportFrequency": export_frequency,
                "enabled": enabled,
                "forcePathStyle": force_path_style,
                "fileType": file_type,
                "exportMode": export_mode,
                "exportStartDate": export_start_date,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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 delete_blob_storage_integration(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BlobStorageIntegrationDeletionResponse]:
        """
        Delete a blob storage integration by ID (requires organization-scoped API key)

        Parameters
        ----------
        id : str

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

        Returns
        -------
        AsyncHttpResponse[BlobStorageIntegrationDeletionResponse]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/public/integrations/blob-storage/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BlobStorageIntegrationDeletionResponse,
                    parse_obj_as(
                        type_=BlobStorageIntegrationDeletionResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    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,
        )
