# 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.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.internal_server_error import InternalServerError
from ..errors.too_many_requests_error import TooManyRequestsError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.domain_code import DomainCode
from ..types.drug_safety_check_response import DrugSafetyCheckResponse
from ..types.error_response import ErrorResponse
from ..types.metadata_response import MetadataResponse
from ..types.patient_profile import PatientProfile
from .types.drug_safety_check_request_lang import DrugSafetyCheckRequestLang
from .types.get_drug_safety_health_response import GetDrugSafetyHealthResponse

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


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

    def check(
        self,
        *,
        drugs: typing.Sequence[str],
        patient_profile: typing.Optional[PatientProfile] = OMIT,
        include: typing.Optional[typing.Sequence[DomainCode]] = OMIT,
        lang: typing.Optional[DrugSafetyCheckRequestLang] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DrugSafetyCheckResponse]:
        """
        Screen one or more drugs across six safety domains in a single request.

        The API resolves drug names via fuzzy matching, runs all requested safety
        checks in parallel, and returns a unified response with alerts bubbled to
        the top for easy triage.

        **Typical response time:** ~40ms (warm cache, 3 drugs, all domains).

        Parameters
        ----------
        drugs : typing.Sequence[str]
            Drug names to screen. Accepts trade names (e.g., "Augmentin 1g"),
            generic names (e.g., "amoxicillin"), or partial matches.
            Fuzzy matching resolves names to SafeRx product IDs.

            - **Free/Pro tier:** max 20 drugs per request
            - **Enterprise tier:** max 50 drugs per request

        patient_profile : typing.Optional[PatientProfile]

        include : typing.Optional[typing.Sequence[DomainCode]]
            Safety domains to check. Omit to run all six domains.
            Including fewer domains reduces response size and may improve latency.

        lang : typing.Optional[DrugSafetyCheckRequestLang]
            Response language. Controls bilingual fields such as rationale text,
            drug name translations, and clinical advice.

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

        Returns
        -------
        HttpResponse[DrugSafetyCheckResponse]
            Successful safety check
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/drug_safety/check",
            method="POST",
            json={
                "drugs": drugs,
                "patient_profile": convert_and_respect_annotation_metadata(
                    object_=patient_profile, annotation=PatientProfile, direction="write"
                ),
                "include": include,
                "lang": lang,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DrugSafetyCheckResponse,
                    parse_obj_as(
                        type_=DrugSafetyCheckResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get_metadata(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[MetadataResponse]:
        """
        Returns available populations, conditions, database versions, risk level
        scales, and current tier limits.

        Use this endpoint to:
        - Populate dropdown menus with valid population and condition values
        - Check database versions and coverage statistics
        - Verify your tier and rate limits
        - Cache metadata locally (changes infrequently — safe to cache for 24 hours)

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

        Returns
        -------
        HttpResponse[MetadataResponse]
            Metadata response
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/drug_safety/metadata",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MetadataResponse,
                    parse_obj_as(
                        type_=MetadataResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get_drug_safety_health(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetDrugSafetyHealthResponse]:
        """
        Returns health status of the Drug Safety API subsystem including
        overall system health and availability.

        No authentication required. Designed for monitoring services.

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

        Returns
        -------
        HttpResponse[GetDrugSafetyHealthResponse]
            Health status
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/drug_safety/health",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetDrugSafetyHealthResponse,
                    parse_obj_as(
                        type_=GetDrugSafetyHealthResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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 AsyncRawDrugSafetyClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def check(
        self,
        *,
        drugs: typing.Sequence[str],
        patient_profile: typing.Optional[PatientProfile] = OMIT,
        include: typing.Optional[typing.Sequence[DomainCode]] = OMIT,
        lang: typing.Optional[DrugSafetyCheckRequestLang] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DrugSafetyCheckResponse]:
        """
        Screen one or more drugs across six safety domains in a single request.

        The API resolves drug names via fuzzy matching, runs all requested safety
        checks in parallel, and returns a unified response with alerts bubbled to
        the top for easy triage.

        **Typical response time:** ~40ms (warm cache, 3 drugs, all domains).

        Parameters
        ----------
        drugs : typing.Sequence[str]
            Drug names to screen. Accepts trade names (e.g., "Augmentin 1g"),
            generic names (e.g., "amoxicillin"), or partial matches.
            Fuzzy matching resolves names to SafeRx product IDs.

            - **Free/Pro tier:** max 20 drugs per request
            - **Enterprise tier:** max 50 drugs per request

        patient_profile : typing.Optional[PatientProfile]

        include : typing.Optional[typing.Sequence[DomainCode]]
            Safety domains to check. Omit to run all six domains.
            Including fewer domains reduces response size and may improve latency.

        lang : typing.Optional[DrugSafetyCheckRequestLang]
            Response language. Controls bilingual fields such as rationale text,
            drug name translations, and clinical advice.

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

        Returns
        -------
        AsyncHttpResponse[DrugSafetyCheckResponse]
            Successful safety check
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/drug_safety/check",
            method="POST",
            json={
                "drugs": drugs,
                "patient_profile": convert_and_respect_annotation_metadata(
                    object_=patient_profile, annotation=PatientProfile, direction="write"
                ),
                "include": include,
                "lang": lang,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DrugSafetyCheckResponse,
                    parse_obj_as(
                        type_=DrugSafetyCheckResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get_metadata(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[MetadataResponse]:
        """
        Returns available populations, conditions, database versions, risk level
        scales, and current tier limits.

        Use this endpoint to:
        - Populate dropdown menus with valid population and condition values
        - Check database versions and coverage statistics
        - Verify your tier and rate limits
        - Cache metadata locally (changes infrequently — safe to cache for 24 hours)

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

        Returns
        -------
        AsyncHttpResponse[MetadataResponse]
            Metadata response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/drug_safety/metadata",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    MetadataResponse,
                    parse_obj_as(
                        type_=MetadataResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get_drug_safety_health(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetDrugSafetyHealthResponse]:
        """
        Returns health status of the Drug Safety API subsystem including
        overall system health and availability.

        No authentication required. Designed for monitoring services.

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

        Returns
        -------
        AsyncHttpResponse[GetDrugSafetyHealthResponse]
            Health status
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/drug_safety/health",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetDrugSafetyHealthResponse,
                    parse_obj_as(
                        type_=GetDrugSafetyHealthResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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)
