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

import typing
from json.decoder import JSONDecodeError

from .....core.api_error import ApiError
from .....core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from .....core.jsonable_encoder import jsonable_encoder
from .....core.pydantic_utilities import pydantic_v1
from .....core.request_options import RequestOptions
from ....commons.errors.entity_not_found_error import EntityNotFoundError
from ....commons.errors.unauthorized_error import UnauthorizedError
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from ....commons.types.schema_id import SchemaId
from ....commons.types.unauthorized_error_message import UnauthorizedErrorMessage
from .errors.schema_validation_http_failure import SchemaValidationHttpFailure
from .types.schema import Schema
from .types.schema_field import SchemaField
from .types.schema_get_multi_response import SchemaGetMultiResponse
from .types.schema_validation_failure import SchemaValidationFailure

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


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

    def get_multi(self, *, request_options: typing.Optional[RequestOptions] = None) -> SchemaGetMultiResponse:
        """
        Returns all custom schemas.

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

        Returns
        -------
        SchemaGetMultiResponse

        Examples
        --------
        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.custom_schemas.v_1.get_multi()
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SchemaGetMultiResponse, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, schema_id: SchemaId, *, request_options: typing.Optional[RequestOptions] = None) -> Schema:
        """
        Return a custom schema with a given ID.

        Parameters
        ----------
        schema_id : SchemaId

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

        Returns
        -------
        Schema

        Examples
        --------
        import uuid

        from candid.client import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.custom_schemas.v_1.get(
            schema_id=uuid.UUID(
                "ec096b13-f80a-471d-aaeb-54b021c9d582",
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        name: str,
        fields: typing.Sequence[SchemaField],
        description: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Schema:
        """
        Create custom schema with a set of typed keys. Schema keys can be referenced as inputs in user-configurable rules in the Rules
        Engine, and key-value pairs can be attached to claims via the Encounters API.

        Parameters
        ----------
        name : str

        fields : typing.Sequence[SchemaField]

        description : typing.Optional[str]

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

        Returns
        -------
        Schema

        Examples
        --------
        from candid import Primitive
        from candid.client import CandidApiClient
        from candid.resources.custom_schemas.v_1 import SchemaField

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.custom_schemas.v_1.create(
            name="General Medicine",
            description="Values associated with a generic visit",
            fields=[
                SchemaField(
                    key="provider_category",
                    type=Primitive.STRING,
                ),
                SchemaField(
                    key="is_urgent_care",
                    type=Primitive.BOOLEAN,
                ),
                SchemaField(
                    key="bmi",
                    type=Primitive.DOUBLE,
                ),
                SchemaField(
                    key="age",
                    type=Primitive.INTEGER,
                ),
            ],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={"name": name, "description": description, "fields": fields},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    pydantic_v1.parse_obj_as(SchemaValidationFailure, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        schema_id: SchemaId,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        fields_to_add: typing.Optional[typing.Sequence[SchemaField]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Schema:
        """
        Update the name, description, or keys on a preexisting schema.

        Parameters
        ----------
        schema_id : SchemaId

        name : typing.Optional[str]

        description : typing.Optional[str]

        fields_to_add : typing.Optional[typing.Sequence[SchemaField]]
            A list of typed entries to add to schema. Only additive modifications are permitted.

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

        Returns
        -------
        Schema

        Examples
        --------
        import uuid

        from candid import Primitive
        from candid.client import CandidApiClient
        from candid.resources.custom_schemas.v_1 import SchemaField

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.custom_schemas.v_1.update(
            schema_id=uuid.UUID(
                "ec096b13-f80a-471d-aaeb-54b021c9d582",
            ),
            name="General Medicine and Health",
            description="Values collected during all visits",
            fields_to_add=[
                SchemaField(
                    key="visit_type",
                    type=Primitive.STRING,
                )
            ],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={"name": name, "description": description, "fields_to_add": fields_to_add},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    pydantic_v1.parse_obj_as(SchemaValidationFailure, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncV1Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_multi(self, *, request_options: typing.Optional[RequestOptions] = None) -> SchemaGetMultiResponse:
        """
        Returns all custom schemas.

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

        Returns
        -------
        SchemaGetMultiResponse

        Examples
        --------
        import asyncio

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.custom_schemas.v_1.get_multi()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(SchemaGetMultiResponse, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(self, schema_id: SchemaId, *, request_options: typing.Optional[RequestOptions] = None) -> Schema:
        """
        Return a custom schema with a given ID.

        Parameters
        ----------
        schema_id : SchemaId

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

        Returns
        -------
        Schema

        Examples
        --------
        import asyncio
        import uuid

        from candid.client import AsyncCandidApiClient

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.custom_schemas.v_1.get(
                schema_id=uuid.UUID(
                    "ec096b13-f80a-471d-aaeb-54b021c9d582",
                ),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        name: str,
        fields: typing.Sequence[SchemaField],
        description: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Schema:
        """
        Create custom schema with a set of typed keys. Schema keys can be referenced as inputs in user-configurable rules in the Rules
        Engine, and key-value pairs can be attached to claims via the Encounters API.

        Parameters
        ----------
        name : str

        fields : typing.Sequence[SchemaField]

        description : typing.Optional[str]

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

        Returns
        -------
        Schema

        Examples
        --------
        import asyncio

        from candid import Primitive
        from candid.client import AsyncCandidApiClient
        from candid.resources.custom_schemas.v_1 import SchemaField

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.custom_schemas.v_1.create(
                name="General Medicine",
                description="Values associated with a generic visit",
                fields=[
                    SchemaField(
                        key="provider_category",
                        type=Primitive.STRING,
                    ),
                    SchemaField(
                        key="is_urgent_care",
                        type=Primitive.BOOLEAN,
                    ),
                    SchemaField(
                        key="bmi",
                        type=Primitive.DOUBLE,
                    ),
                    SchemaField(
                        key="age",
                        type=Primitive.INTEGER,
                    ),
                ],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/custom-schemas/v1",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={"name": name, "description": description, "fields": fields},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    pydantic_v1.parse_obj_as(SchemaValidationFailure, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        schema_id: SchemaId,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        fields_to_add: typing.Optional[typing.Sequence[SchemaField]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Schema:
        """
        Update the name, description, or keys on a preexisting schema.

        Parameters
        ----------
        schema_id : SchemaId

        name : typing.Optional[str]

        description : typing.Optional[str]

        fields_to_add : typing.Optional[typing.Sequence[SchemaField]]
            A list of typed entries to add to schema. Only additive modifications are permitted.

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

        Returns
        -------
        Schema

        Examples
        --------
        import asyncio
        import uuid

        from candid import Primitive
        from candid.client import AsyncCandidApiClient
        from candid.resources.custom_schemas.v_1 import SchemaField

        client = AsyncCandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.custom_schemas.v_1.update(
                schema_id=uuid.UUID(
                    "ec096b13-f80a-471d-aaeb-54b021c9d582",
                ),
                name="General Medicine and Health",
                description="Values collected during all visits",
                fields_to_add=[
                    SchemaField(
                        key="visit_type",
                        type=Primitive.STRING,
                    )
                ],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/custom-schemas/v1/{jsonable_encoder(schema_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={"name": name, "description": description, "fields_to_add": fields_to_add},
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Schema, _response_json)  # type: ignore
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    pydantic_v1.parse_obj_as(EntityNotFoundErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    pydantic_v1.parse_obj_as(UnauthorizedErrorMessage, _response_json["content"])  # type: ignore
                )
            if _response_json["errorName"] == "SchemaValidationHttpFailure":
                raise SchemaValidationHttpFailure(
                    pydantic_v1.parse_obj_as(SchemaValidationFailure, _response_json["content"])  # type: ignore
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)
