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

import json
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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..errors.unsupported_media_type_error import UnsupportedMediaTypeError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..types.chunking_strategy import ChunkingStrategy
from ..types.corpus_key import CorpusKey
from ..types.document import Document
from ..types.error import Error
from ..types.not_found_error_body import NotFoundErrorBody
from ..types.table_extraction_config import TableExtractionConfig

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


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

    def file(
        self,
        corpus_key: CorpusKey,
        *,
        file: core.File,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        chunking_strategy: typing.Optional[ChunkingStrategy] = OMIT,
        table_extraction_config: typing.Optional[TableExtractionConfig] = OMIT,
        filename: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Document]:
        """
        Upload a file, such as a PDF or Word document, to the specified corpus for automatic text extraction and metadata parsing.

        This endpoint expects a `multipart/form-data` request with the following fields:

        - **metadata**: An optional JSON object containing additional metadata to associate with the document.
          Example: `metadata={"key": "value"}`
        - **chunking_strategy**: An optional JSON object that sets the chunking method for text extraction.
          - By default, the platform uses sentence-based chunking (one chunk per sentence).
          - Example for explicit sentence chunking: `chunking_strategy={"type":"sentence_chunking_strategy"}`
          - Example for max chars chunking: `chunking_strategy={"type":"max_chars_chunking_strategy","max_chars_per_chunk":512}`
        - **table_extraction_config**: An optional JSON object to control table extraction from supported file types (e.g., PDF).
          Example: `table_extraction_config={"extract_tables": true}`
        - **file**: The file to upload. Attach your file as the value for this field.
        - **filename**: The desired name for the uploaded file. Specify as part of the file field in your request.

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus of which to upload the file.

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

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Arbitrary object that will be attached as document metadata to the extracted document.

        chunking_strategy : typing.Optional[ChunkingStrategy]

        table_extraction_config : typing.Optional[TableExtractionConfig]

        filename : typing.Optional[str]
            Optional multipart section to override the filename.

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

        Returns
        -------
        HttpResponse[Document]
            The extracted document has been parsed and added to the corpus.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/corpora/{jsonable_encoder(corpus_key)}/upload_file",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            data={},
            files={
                **(
                    {"metadata": (None, json.dumps(jsonable_encoder(metadata)), "application/json")}
                    if metadata is not OMIT
                    else {}
                ),
                **(
                    {"chunking_strategy": (None, json.dumps(jsonable_encoder(chunking_strategy)), "application/json")}
                    if chunking_strategy is not OMIT
                    else {}
                ),
                **(
                    {
                        "table_extraction_config": (
                            None,
                            json.dumps(jsonable_encoder(table_extraction_config)),
                            "application/json",
                        )
                    }
                    if table_extraction_config is not OMIT
                    else {}
                ),
                **({"filename": (None, jsonable_encoder(filename), "text/plain")} if filename is not OMIT else {}),
                "file": core.with_content_type(file=file, default_content_type="application/octet-stream"),
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Document,
                    parse_obj_as(
                        type_=Document,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 415:
                raise UnsupportedMediaTypeError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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 AsyncRawUploadClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def file(
        self,
        corpus_key: CorpusKey,
        *,
        file: core.File,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        chunking_strategy: typing.Optional[ChunkingStrategy] = OMIT,
        table_extraction_config: typing.Optional[TableExtractionConfig] = OMIT,
        filename: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Document]:
        """
        Upload a file, such as a PDF or Word document, to the specified corpus for automatic text extraction and metadata parsing.

        This endpoint expects a `multipart/form-data` request with the following fields:

        - **metadata**: An optional JSON object containing additional metadata to associate with the document.
          Example: `metadata={"key": "value"}`
        - **chunking_strategy**: An optional JSON object that sets the chunking method for text extraction.
          - By default, the platform uses sentence-based chunking (one chunk per sentence).
          - Example for explicit sentence chunking: `chunking_strategy={"type":"sentence_chunking_strategy"}`
          - Example for max chars chunking: `chunking_strategy={"type":"max_chars_chunking_strategy","max_chars_per_chunk":512}`
        - **table_extraction_config**: An optional JSON object to control table extraction from supported file types (e.g., PDF).
          Example: `table_extraction_config={"extract_tables": true}`
        - **file**: The file to upload. Attach your file as the value for this field.
        - **filename**: The desired name for the uploaded file. Specify as part of the file field in your request.

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus of which to upload the file.

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

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Arbitrary object that will be attached as document metadata to the extracted document.

        chunking_strategy : typing.Optional[ChunkingStrategy]

        table_extraction_config : typing.Optional[TableExtractionConfig]

        filename : typing.Optional[str]
            Optional multipart section to override the filename.

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

        Returns
        -------
        AsyncHttpResponse[Document]
            The extracted document has been parsed and added to the corpus.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/corpora/{jsonable_encoder(corpus_key)}/upload_file",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            data={},
            files={
                **(
                    {"metadata": (None, json.dumps(jsonable_encoder(metadata)), "application/json")}
                    if metadata is not OMIT
                    else {}
                ),
                **(
                    {"chunking_strategy": (None, json.dumps(jsonable_encoder(chunking_strategy)), "application/json")}
                    if chunking_strategy is not OMIT
                    else {}
                ),
                **(
                    {
                        "table_extraction_config": (
                            None,
                            json.dumps(jsonable_encoder(table_extraction_config)),
                            "application/json",
                        )
                    }
                    if table_extraction_config is not OMIT
                    else {}
                ),
                **({"filename": (None, jsonable_encoder(filename), "text/plain")} if filename is not OMIT else {}),
                "file": core.with_content_type(file=file, default_content_type="application/octet-stream"),
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Document,
                    parse_obj_as(
                        type_=Document,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 415:
                raise UnsupportedMediaTypeError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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)
