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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..types.v_1_batch_record import V1BatchRecord
from ..types.v_1_byot import V1Byot
from ..core.request_options import RequestOptions
from ..types.v_1_batch_operation_response import V1BatchOperationResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.pydantic_utilities import parse_obj_as
from ..errors.not_found_error import NotFoundError
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper

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


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

    def batch_operation(
        self,
        vault_id: str,
        *,
        records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT,
        continue_on_error: typing.Optional[bool] = OMIT,
        byot: typing.Optional[V1Byot] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> V1BatchOperationResponse:
        """
        Performs multiple record operations in a single transaction.

        Parameters
        ----------
        vault_id : str
            ID of the vault.

        records : typing.Optional[typing.Sequence[V1BatchRecord]]
            Record operations to perform.

        continue_on_error : typing.Optional[bool]
            Continue performing operations on partial errors.

        byot : typing.Optional[V1Byot]

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

        Returns
        -------
        V1BatchOperationResponse
            A successful response.

        Examples
        --------
        from skyflow import Skyflow, V1BatchRecord

        client = Skyflow(
            api_key="YOUR_API_KEY",
        )
        client.records.batch_operation(
            vault_id="vaultID",
            records=[
                V1BatchRecord(
                    fields={
                        "drivers_license_number": "89867453",
                        "name": "Connor",
                        "phone_number": "8794523160",
                        "ssn": "143-89-2306",
                    },
                    table_name="persons",
                    method="POST",
                    batch_id="persons-12345",
                    redaction="PLAIN_TEXT",
                    tokenization=False,
                    download_url=False,
                    upsert="drivers_license_number",
                ),
                V1BatchRecord(
                    table_name="persons",
                    method="GET",
                    batch_id="persons-12345",
                    redaction="PLAIN_TEXT",
                    tokenization=False,
                    id="f1dbc55c-7c9b-495d-9a36-72bb2b619202",
                    download_url=True,
                ),
            ],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/vaults/{jsonable_encoder(vault_id)}",
            method="POST",
            json={
                "records": convert_and_respect_annotation_metadata(
                    object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write"
                ),
                "continueOnError": continue_on_error,
                "byot": byot,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    V1BatchOperationResponse,
                    parse_obj_as(
                        type_=V1BatchOperationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Dict[str, typing.Optional[typing.Any]],
                        parse_obj_as(
                            type_=typing.Dict[str, typing.Optional[typing.Any]],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 AsyncRecordsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def batch_operation(
        self,
        vault_id: str,
        *,
        records: typing.Optional[typing.Sequence[V1BatchRecord]] = OMIT,
        continue_on_error: typing.Optional[bool] = OMIT,
        byot: typing.Optional[V1Byot] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> V1BatchOperationResponse:
        """
        Performs multiple record operations in a single transaction.

        Parameters
        ----------
        vault_id : str
            ID of the vault.

        records : typing.Optional[typing.Sequence[V1BatchRecord]]
            Record operations to perform.

        continue_on_error : typing.Optional[bool]
            Continue performing operations on partial errors.

        byot : typing.Optional[V1Byot]

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

        Returns
        -------
        V1BatchOperationResponse
            A successful response.

        Examples
        --------
        import asyncio

        from skyflow import AsyncSkyflow, V1BatchRecord

        client = AsyncSkyflow(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.records.batch_operation(
                vault_id="vaultID",
                records=[
                    V1BatchRecord(
                        fields={
                            "drivers_license_number": "89867453",
                            "name": "Connor",
                            "phone_number": "8794523160",
                            "ssn": "143-89-2306",
                        },
                        table_name="persons",
                        method="POST",
                        batch_id="persons-12345",
                        redaction="PLAIN_TEXT",
                        tokenization=False,
                        download_url=False,
                        upsert="drivers_license_number",
                    ),
                    V1BatchRecord(
                        table_name="persons",
                        method="GET",
                        batch_id="persons-12345",
                        redaction="PLAIN_TEXT",
                        tokenization=False,
                        id="f1dbc55c-7c9b-495d-9a36-72bb2b619202",
                        download_url=True,
                    ),
                ],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/vaults/{jsonable_encoder(vault_id)}",
            method="POST",
            json={
                "records": convert_and_respect_annotation_metadata(
                    object_=records, annotation=typing.Sequence[V1BatchRecord], direction="write"
                ),
                "continueOnError": continue_on_error,
                "byot": byot,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    V1BatchOperationResponse,
                    parse_obj_as(
                        type_=V1BatchOperationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Dict[str, typing.Optional[typing.Any]],
                        parse_obj_as(
                            type_=typing.Dict[str, typing.Optional[typing.Any]],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)
