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

import typing
from json.decoder import JSONDecodeError

from ... import core
from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.duplicate_file_handling import DuplicateFileHandling
from ...types.file_metadata import FileMetadata
from ...types.http_validation_error import HttpValidationError

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


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

    def upload(
        self,
        source_id: str,
        *,
        file: core.File,
        duplicate_handling: typing.Optional[DuplicateFileHandling] = None,
        name: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[FileMetadata]:
        """
        Upload a file to a data source.

        Parameters
        ----------
        source_id : str

        file : core.File
            See core.File for more documentation

        duplicate_handling : typing.Optional[DuplicateFileHandling]
            How to handle duplicate filenames

        name : typing.Optional[str]
            Optional custom name to override the uploaded file's name

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

        Returns
        -------
        HttpResponse[FileMetadata]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/upload",
            method="POST",
            params={
                "duplicate_handling": duplicate_handling,
                "name": name,
            },
            data={},
            files={
                "file": file,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FileMetadata,
                    construct_type(
                        type_=FileMetadata,  # 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(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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(
        self,
        source_id: str,
        *,
        limit: typing.Optional[int] = None,
        after: typing.Optional[str] = None,
        include_content: typing.Optional[bool] = None,
        check_status_updates: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[FileMetadata]]:
        """
        List paginated files associated with a data source.

        Parameters
        ----------
        source_id : str

        limit : typing.Optional[int]
            Number of files to return

        after : typing.Optional[str]
            Pagination cursor to fetch the next set of results

        include_content : typing.Optional[bool]
            Whether to include full file content

        check_status_updates : typing.Optional[bool]
            Whether to check and update file processing status (from the vector db service). If False, will not fetch and update the status, which may lead to performance gains.

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

        Returns
        -------
        HttpResponse[typing.List[FileMetadata]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/files",
            method="GET",
            params={
                "limit": limit,
                "after": after,
                "include_content": include_content,
                "check_status_updates": check_status_updates,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[FileMetadata],
                    construct_type(
                        type_=typing.List[FileMetadata],  # 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(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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(
        self, source_id: str, file_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Delete a data source.

        Parameters
        ----------
        source_id : str

        file_id : str

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/{jsonable_encoder(file_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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 AsyncRawFilesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def upload(
        self,
        source_id: str,
        *,
        file: core.File,
        duplicate_handling: typing.Optional[DuplicateFileHandling] = None,
        name: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[FileMetadata]:
        """
        Upload a file to a data source.

        Parameters
        ----------
        source_id : str

        file : core.File
            See core.File for more documentation

        duplicate_handling : typing.Optional[DuplicateFileHandling]
            How to handle duplicate filenames

        name : typing.Optional[str]
            Optional custom name to override the uploaded file's name

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

        Returns
        -------
        AsyncHttpResponse[FileMetadata]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/upload",
            method="POST",
            params={
                "duplicate_handling": duplicate_handling,
                "name": name,
            },
            data={},
            files={
                "file": file,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    FileMetadata,
                    construct_type(
                        type_=FileMetadata,  # 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(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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(
        self,
        source_id: str,
        *,
        limit: typing.Optional[int] = None,
        after: typing.Optional[str] = None,
        include_content: typing.Optional[bool] = None,
        check_status_updates: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[FileMetadata]]:
        """
        List paginated files associated with a data source.

        Parameters
        ----------
        source_id : str

        limit : typing.Optional[int]
            Number of files to return

        after : typing.Optional[str]
            Pagination cursor to fetch the next set of results

        include_content : typing.Optional[bool]
            Whether to include full file content

        check_status_updates : typing.Optional[bool]
            Whether to check and update file processing status (from the vector db service). If False, will not fetch and update the status, which may lead to performance gains.

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

        Returns
        -------
        AsyncHttpResponse[typing.List[FileMetadata]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/files",
            method="GET",
            params={
                "limit": limit,
                "after": after,
                "include_content": include_content,
                "check_status_updates": check_status_updates,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[FileMetadata],
                    construct_type(
                        type_=typing.List[FileMetadata],  # 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(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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(
        self, source_id: str, file_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Delete a data source.

        Parameters
        ----------
        source_id : str

        file_id : str

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/sources/{jsonable_encoder(source_id)}/{jsonable_encoder(file_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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)
