# 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.pydantic_utilities import pydantic_v1
from ..core.request_options import RequestOptions
from ..errors.bad_request_error import BadRequestError
from ..errors.content_too_large_error import ContentTooLargeError
from ..errors.internal_server_error import InternalServerError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..errors.unsupported_media_type_error import UnsupportedMediaTypeError
from ..types.asset_not_found_error import AssetNotFoundError
from ..types.data_frame_request_out import DataFrameRequestOut
from ..types.data_frame_unknown_format_error import DataFrameUnknownFormatError
from ..types.file_chunk_request_out import FileChunkRequestOut
from ..types.file_too_large_error import FileTooLargeError
from ..types.parent_folder_error import ParentFolderError
from ..types.save_asset_request_out import SaveAssetRequestOut
from .calendar.client import AsyncCalendarClient, CalendarClient
from .email.client import AsyncEmailClient, EmailClient
from .structured_data_extractor.client import AsyncStructuredDataExtractorClient, StructuredDataExtractorClient
from .tasks.client import AsyncTasksClient, TasksClient
from .types.tools_data_frame_request_columns_item import ToolsDataFrameRequestColumnsItem

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


class ToolsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper
        self.calendar = CalendarClient(client_wrapper=self._client_wrapper)
        self.email = EmailClient(client_wrapper=self._client_wrapper)
        self.structured_data_extractor = StructuredDataExtractorClient(client_wrapper=self._client_wrapper)
        self.tasks = TasksClient(client_wrapper=self._client_wrapper)

    def get_asset_chunks(
        self, *, asset_ids: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> FileChunkRequestOut:
        """
        Get the chunks of a file.

        Parameters
        ----------
        asset_ids : typing.Sequence[str]
            Identifiers of the assets

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

        Returns
        -------
        FileChunkRequestOut
            Successful Response

        Examples
        --------
        from athena.client import Athena

        client = Athena(
            api_key="YOUR_API_KEY",
        )
        client.tools.get_asset_chunks(
            asset_ids=[
                "asset_9249292-d118-42d3-96b4-00eccfe0754f",
                "asset_9249292-d118-42d3-95b4-01eccfe0754f",
            ],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/v0/tools/asset/chunks",
            method="POST",
            json={"asset_ids": asset_ids},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(FileChunkRequestOut, _response.json())  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 404:
            raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def data_frame(
        self,
        *,
        asset_id: str,
        row_limit: typing.Optional[int] = None,
        index_column: typing.Optional[int] = None,
        columns: typing.Optional[
            typing.Union[ToolsDataFrameRequestColumnsItem, typing.Sequence[ToolsDataFrameRequestColumnsItem]]
        ] = None,
        sheet_name: typing.Optional[int] = None,
        separator: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None
    ) -> DataFrameRequestOut:
        """
        Parameters
        ----------
        asset_id : str

        row_limit : typing.Optional[int]

        index_column : typing.Optional[int]

        columns : typing.Optional[typing.Union[ToolsDataFrameRequestColumnsItem, typing.Sequence[ToolsDataFrameRequestColumnsItem]]]
            should be a list of strings or a list of integers

        sheet_name : typing.Optional[int]
            only for excel files

        separator : typing.Optional[str]
            only for csv files

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

        Returns
        -------
        DataFrameRequestOut
            Successful Response

        Examples
        --------
        from athena.client import Athena

        client = Athena(
            api_key="YOUR_API_KEY",
        )
        client.tools.data_frame(
            asset_id="asset_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/v0/tools/file/data-frame",
            method="GET",
            params={
                "asset_id": asset_id,
                "row_limit": row_limit,
                "index_column": index_column,
                "columns": columns,
                "sheet_name": sheet_name,
                "separator": separator,
            },
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(DataFrameRequestOut, _response.json())  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 404:
            raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
        if _response.status_code == 415:
            raise UnsupportedMediaTypeError(
                pydantic_v1.parse_obj_as(DataFrameUnknownFormatError, _response.json())  # type: ignore
            )
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def raw_data(
        self, *, asset_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.Iterator[bytes]:
        """
        Get the raw file data for given asset.

        Parameters
        ----------
        asset_id : str

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

        Yields
        ------
        typing.Iterator[bytes]
            Stream the file in original format.

        Examples
        --------
        from athena.client import Athena

        client = Athena(
            api_key="YOUR_API_KEY",
        )
        client.tools.raw_data(
            asset_id="string",
        )
        """
        with self._client_wrapper.httpx_client.stream(
            "api/v0/tools/file/raw-data", method="GET", params={"asset_id": asset_id}, request_options=request_options
        ) as _response:
            if 200 <= _response.status_code < 300:
                for _chunk in _response.iter_bytes():
                    yield _chunk
                return
            _response.read()
            if _response.status_code == 401:
                raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 404:
                raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
            if _response.status_code == 422:
                raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 500:
                raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            try:
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    def save_asset(
        self,
        *,
        file: core.File,
        parent_folder_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None
    ) -> SaveAssetRequestOut:
        """
        Parameters
        ----------
        file : core.File
            See core.File for more documentation

        parent_folder_id : typing.Optional[str]
            Identifier of the folder into which the asset should be saved

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

        Returns
        -------
        SaveAssetRequestOut
            Successful Response

        Examples
        --------
        from athena.client import Athena

        client = Athena(
            api_key="YOUR_API_KEY",
        )
        client.tools.save_asset()
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/v0/tools/file/save",
            method="POST",
            params={"parent_folder_id": parent_folder_id},
            data={},
            files={"file": file},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SaveAssetRequestOut, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(ParentFolderError, _response.json()))  # type: ignore
        if _response.status_code == 413:
            raise ContentTooLargeError(pydantic_v1.parse_obj_as(FileTooLargeError, _response.json()))  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncToolsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper
        self.calendar = AsyncCalendarClient(client_wrapper=self._client_wrapper)
        self.email = AsyncEmailClient(client_wrapper=self._client_wrapper)
        self.structured_data_extractor = AsyncStructuredDataExtractorClient(client_wrapper=self._client_wrapper)
        self.tasks = AsyncTasksClient(client_wrapper=self._client_wrapper)

    async def get_asset_chunks(
        self, *, asset_ids: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None
    ) -> FileChunkRequestOut:
        """
        Get the chunks of a file.

        Parameters
        ----------
        asset_ids : typing.Sequence[str]
            Identifiers of the assets

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

        Returns
        -------
        FileChunkRequestOut
            Successful Response

        Examples
        --------
        from athena.client import AsyncAthena

        client = AsyncAthena(
            api_key="YOUR_API_KEY",
        )
        await client.tools.get_asset_chunks(
            asset_ids=[
                "asset_9249292-d118-42d3-96b4-00eccfe0754f",
                "asset_9249292-d118-42d3-95b4-01eccfe0754f",
            ],
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/v0/tools/asset/chunks",
            method="POST",
            json={"asset_ids": asset_ids},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(FileChunkRequestOut, _response.json())  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 404:
            raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def data_frame(
        self,
        *,
        asset_id: str,
        row_limit: typing.Optional[int] = None,
        index_column: typing.Optional[int] = None,
        columns: typing.Optional[
            typing.Union[ToolsDataFrameRequestColumnsItem, typing.Sequence[ToolsDataFrameRequestColumnsItem]]
        ] = None,
        sheet_name: typing.Optional[int] = None,
        separator: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None
    ) -> DataFrameRequestOut:
        """
        Parameters
        ----------
        asset_id : str

        row_limit : typing.Optional[int]

        index_column : typing.Optional[int]

        columns : typing.Optional[typing.Union[ToolsDataFrameRequestColumnsItem, typing.Sequence[ToolsDataFrameRequestColumnsItem]]]
            should be a list of strings or a list of integers

        sheet_name : typing.Optional[int]
            only for excel files

        separator : typing.Optional[str]
            only for csv files

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

        Returns
        -------
        DataFrameRequestOut
            Successful Response

        Examples
        --------
        from athena.client import AsyncAthena

        client = AsyncAthena(
            api_key="YOUR_API_KEY",
        )
        await client.tools.data_frame(
            asset_id="asset_id",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/v0/tools/file/data-frame",
            method="GET",
            params={
                "asset_id": asset_id,
                "row_limit": row_limit,
                "index_column": index_column,
                "columns": columns,
                "sheet_name": sheet_name,
                "separator": separator,
            },
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(DataFrameRequestOut, _response.json())  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 404:
            raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
        if _response.status_code == 415:
            raise UnsupportedMediaTypeError(
                pydantic_v1.parse_obj_as(DataFrameUnknownFormatError, _response.json())  # type: ignore
            )
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        if _response.status_code == 500:
            raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def raw_data(
        self, *, asset_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.AsyncIterator[bytes]:
        """
        Get the raw file data for given asset.

        Parameters
        ----------
        asset_id : str

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

        Yields
        ------
        typing.AsyncIterator[bytes]
            Stream the file in original format.

        Examples
        --------
        from athena.client import AsyncAthena

        client = AsyncAthena(
            api_key="YOUR_API_KEY",
        )
        await client.tools.raw_data(
            asset_id="string",
        )
        """
        async with self._client_wrapper.httpx_client.stream(
            "api/v0/tools/file/raw-data", method="GET", params={"asset_id": asset_id}, request_options=request_options
        ) as _response:
            if 200 <= _response.status_code < 300:
                async for _chunk in _response.aiter_bytes():
                    yield _chunk
                return
            await _response.aread()
            if _response.status_code == 401:
                raise UnauthorizedError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 404:
                raise NotFoundError(pydantic_v1.parse_obj_as(AssetNotFoundError, _response.json()))  # type: ignore
            if _response.status_code == 422:
                raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            if _response.status_code == 500:
                raise InternalServerError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
            try:
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    async def save_asset(
        self,
        *,
        file: core.File,
        parent_folder_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None
    ) -> SaveAssetRequestOut:
        """
        Parameters
        ----------
        file : core.File
            See core.File for more documentation

        parent_folder_id : typing.Optional[str]
            Identifier of the folder into which the asset should be saved

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

        Returns
        -------
        SaveAssetRequestOut
            Successful Response

        Examples
        --------
        from athena.client import AsyncAthena

        client = AsyncAthena(
            api_key="YOUR_API_KEY",
        )
        await client.tools.save_asset()
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/v0/tools/file/save",
            method="POST",
            params={"parent_folder_id": parent_folder_id},
            data={},
            files={"file": file},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SaveAssetRequestOut, _response.json())  # type: ignore
        if _response.status_code == 400:
            raise BadRequestError(pydantic_v1.parse_obj_as(ParentFolderError, _response.json()))  # type: ignore
        if _response.status_code == 413:
            raise ContentTooLargeError(pydantic_v1.parse_obj_as(FileTooLargeError, _response.json()))  # type: ignore
        if _response.status_code == 422:
            raise UnprocessableEntityError(pydantic_v1.parse_obj_as(typing.Any, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
