# 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 .errors.bad_request_error import BadRequestError
from .errors.failed_dependency_error import FailedDependencyError
from .errors.forbidden_error import ForbiddenError
from .errors.internal_server_error import InternalServerError
from .errors.unauthorized_error import UnauthorizedError
from .types.cohort_response import CohortResponse
from .types.lang2fhir_and_create_multi_response import Lang2FhirAndCreateMultiResponse
from .types.lang2fhir_and_create_request_resource import Lang2FhirAndCreateRequestResource
from .types.lang2fhir_and_create_response import Lang2FhirAndCreateResponse
from .types.lang2fhir_and_search_response import Lang2FhirAndSearchResponse

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


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

    def create_fhir_resource(
        self,
        *,
        resource: Lang2FhirAndCreateRequestResource,
        text: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Lang2FhirAndCreateResponse]:
        """
        Converts natural language to FHIR resource and optionally stores it in a FHIR server

        Parameters
        ----------
        resource : Lang2FhirAndCreateRequestResource
            Type of FHIR resource to create. Use 'auto' for automatic resource type detection, or specify a supported US Core profile.

        text : str
            Natural language text to convert to FHIR resource

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        provider : typing.Optional[str]
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

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

        Returns
        -------
        HttpResponse[Lang2FhirAndCreateResponse]
            Successfully created FHIR resource
        """
        _response = self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-create",
            method="POST",
            json={
                "resource": resource,
                "text": text,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndCreateResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndCreateResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 create_fhir_resources_multi(
        self,
        *,
        text: str,
        provider: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Lang2FhirAndCreateMultiResponse]:
        """
        Extracts multiple FHIR resources from natural language text and stores them in a FHIR server.
        Automatically detects Patient, Condition, MedicationRequest, Observation, and other resource types.
        Resources are linked with proper references and submitted as a transaction bundle.
        For FHIR servers that don't auto-resolve urn:uuid references, this endpoint will automatically
        resolve them via PUT requests after the initial bundle creation.

        Parameters
        ----------
        text : str
            Natural language text containing multiple clinical concepts to extract

        provider : str
            FHIR provider ID or name

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        version : typing.Optional[str]
            FHIR version to use

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

        Returns
        -------
        HttpResponse[Lang2FhirAndCreateMultiResponse]
            Successfully created FHIR resources
        """
        _response = self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-create-multi",
            method="POST",
            json={
                "text": text,
                "version": version,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndCreateMultiResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndCreateMultiResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 search_fhir_resources(
        self,
        *,
        text: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        patient_id: typing.Optional[str] = OMIT,
        practitioner_id: typing.Optional[str] = OMIT,
        count: typing.Optional[int] = OMIT,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Lang2FhirAndSearchResponse]:
        """
        Converts natural language to FHIR search parameters and executes search in FHIR server

        Parameters
        ----------
        text : str
            Natural language text to convert to FHIR search parameters

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        patient_id : typing.Optional[str]
            Patient ID to filter results

        practitioner_id : typing.Optional[str]
            Practitioner ID to filter results

        count : typing.Optional[int]
            Maximum number of results to return

        provider : typing.Optional[str]
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

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

        Returns
        -------
        HttpResponse[Lang2FhirAndSearchResponse]
            Successfully generated search and retrieved results
        """
        _response = self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-search",
            method="POST",
            json={
                "text": text,
                "patient_id": patient_id,
                "practitioner_id": practitioner_id,
                "count": count,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndSearchResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndSearchResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 analyze_cohort(
        self,
        *,
        text: str,
        provider: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CohortResponse]:
        """
        Uses LLM to extract search concepts from natural language and builds patient cohorts with inclusion/exclusion criteria

        Parameters
        ----------
        text : str
            Natural language text describing the patient cohort criteria

        provider : str
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        HttpResponse[CohortResponse]
            Successfully analyzed cohort and retrieved patient list
        """
        _response = self._client_wrapper.httpx_client.request(
            "tools/cohort",
            method="POST",
            json={
                "text": text,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CohortResponse,
                    parse_obj_as(
                        type_=CohortResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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)


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

    async def create_fhir_resource(
        self,
        *,
        resource: Lang2FhirAndCreateRequestResource,
        text: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Lang2FhirAndCreateResponse]:
        """
        Converts natural language to FHIR resource and optionally stores it in a FHIR server

        Parameters
        ----------
        resource : Lang2FhirAndCreateRequestResource
            Type of FHIR resource to create. Use 'auto' for automatic resource type detection, or specify a supported US Core profile.

        text : str
            Natural language text to convert to FHIR resource

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        provider : typing.Optional[str]
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

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

        Returns
        -------
        AsyncHttpResponse[Lang2FhirAndCreateResponse]
            Successfully created FHIR resource
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-create",
            method="POST",
            json={
                "resource": resource,
                "text": text,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndCreateResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndCreateResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 create_fhir_resources_multi(
        self,
        *,
        text: str,
        provider: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Lang2FhirAndCreateMultiResponse]:
        """
        Extracts multiple FHIR resources from natural language text and stores them in a FHIR server.
        Automatically detects Patient, Condition, MedicationRequest, Observation, and other resource types.
        Resources are linked with proper references and submitted as a transaction bundle.
        For FHIR servers that don't auto-resolve urn:uuid references, this endpoint will automatically
        resolve them via PUT requests after the initial bundle creation.

        Parameters
        ----------
        text : str
            Natural language text containing multiple clinical concepts to extract

        provider : str
            FHIR provider ID or name

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        version : typing.Optional[str]
            FHIR version to use

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

        Returns
        -------
        AsyncHttpResponse[Lang2FhirAndCreateMultiResponse]
            Successfully created FHIR resources
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-create-multi",
            method="POST",
            json={
                "text": text,
                "version": version,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndCreateMultiResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndCreateMultiResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 search_fhir_resources(
        self,
        *,
        text: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        patient_id: typing.Optional[str] = OMIT,
        practitioner_id: typing.Optional[str] = OMIT,
        count: typing.Optional[int] = OMIT,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Lang2FhirAndSearchResponse]:
        """
        Converts natural language to FHIR search parameters and executes search in FHIR server

        Parameters
        ----------
        text : str
            Natural language text to convert to FHIR search parameters

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

        patient_id : typing.Optional[str]
            Patient ID to filter results

        practitioner_id : typing.Optional[str]
            Practitioner ID to filter results

        count : typing.Optional[int]
            Maximum number of results to return

        provider : typing.Optional[str]
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

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

        Returns
        -------
        AsyncHttpResponse[Lang2FhirAndSearchResponse]
            Successfully generated search and retrieved results
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tools/lang2fhir-and-search",
            method="POST",
            json={
                "text": text,
                "patient_id": patient_id,
                "practitioner_id": practitioner_id,
                "count": count,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Lang2FhirAndSearchResponse,
                    parse_obj_as(
                        type_=Lang2FhirAndSearchResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 424:
                raise FailedDependencyError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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 analyze_cohort(
        self,
        *,
        text: str,
        provider: str,
        phenoml_on_behalf_of: typing.Optional[str] = None,
        phenoml_fhir_provider: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CohortResponse]:
        """
        Uses LLM to extract search concepts from natural language and builds patient cohorts with inclusion/exclusion criteria

        Parameters
        ----------
        text : str
            Natural language text describing the patient cohort criteria

        provider : str
            FHIR provider ID - must be a valid UUID from existing FHIR providers. also supports provider by name (e.g. medplum)

        phenoml_on_behalf_of : typing.Optional[str]
            Optional header for on-behalf-of authentication. Used when making requests on behalf of another user or entity.
            Must be in the format: Patient/{uuid} or Practitioner/{uuid}

        phenoml_fhir_provider : typing.Optional[str]
            Optional header for FHIR provider authentication. Contains credentials in the format {fhir_provider_id}:{oauth2_token}.
            Multiple FHIR provider integrations can be provided as comma-separated values.

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

        Returns
        -------
        AsyncHttpResponse[CohortResponse]
            Successfully analyzed cohort and retrieved patient list
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tools/cohort",
            method="POST",
            json={
                "text": text,
                "provider": provider,
            },
            headers={
                "content-type": "application/json",
                "X-Phenoml-On-Behalf-Of": str(phenoml_on_behalf_of) if phenoml_on_behalf_of is not None else None,
                "X-Phenoml-Fhir-Provider": str(phenoml_fhir_provider) if phenoml_fhir_provider is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CohortResponse,
                    parse_obj_as(
                        type_=CohortResponse,  # 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.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[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)
