# 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.conflict_error import ConflictError
from .errors.failed_dependency_error import FailedDependencyError
from .errors.internal_server_error import InternalServerError
from .errors.unauthorized_error import UnauthorizedError
from .types.construe_upload_code_system_response import ConstrueUploadCodeSystemResponse
from .types.extract_codes_result import ExtractCodesResult
from .types.extract_request_config import ExtractRequestConfig
from .types.extract_request_system import ExtractRequestSystem
from .types.upload_request_format import UploadRequestFormat

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


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

    def upload_code_system(
        self,
        *,
        name: str,
        version: str,
        format: UploadRequestFormat,
        file: str,
        revision: typing.Optional[float] = OMIT,
        code_col: typing.Optional[str] = OMIT,
        desc_col: typing.Optional[str] = OMIT,
        defn_col: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ConstrueUploadCodeSystemResponse]:
        """
        Upload a custom medical code system with codes and descriptions for use in code extraction.
        Upon upload, construe generates embeddings for all of the codes in the code system and stores them in the vector database so you can
        subsequently use the code system for construe/extract and lang2fhir/create (coming soon!)

        Parameters
        ----------
        name : str
            Name of the code system

        version : str
            Version of the code system

        format : UploadRequestFormat
            Format of the uploaded file

        file : str
            The file contents as a base64-encoded string

        revision : typing.Optional[float]
            Optional revision number

        code_col : typing.Optional[str]
            Column name containing codes (required for CSV format)

        desc_col : typing.Optional[str]
            Column name containing descriptions (required for CSV format)

        defn_col : typing.Optional[str]
            Optional column name containing long definitions (for CSV format)

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

        Returns
        -------
        HttpResponse[ConstrueUploadCodeSystemResponse]
            Successfully uploaded code system
        """
        _response = self._client_wrapper.httpx_client.request(
            "construe/upload",
            method="POST",
            json={
                "name": name,
                "version": version,
                "revision": revision,
                "format": format,
                "file": file,
                "code_col": code_col,
                "desc_col": desc_col,
                "defn_col": defn_col,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConstrueUploadCodeSystemResponse,
                    parse_obj_as(
                        type_=ConstrueUploadCodeSystemResponse,  # 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 == 409:
                raise ConflictError(
                    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 extract_codes(
        self,
        *,
        text: str,
        system: typing.Optional[ExtractRequestSystem] = OMIT,
        config: typing.Optional[ExtractRequestConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ExtractCodesResult]:
        """
        Converts natural language text into structured medical codes

        Parameters
        ----------
        text : str
            Natural language text to extract codes from

        system : typing.Optional[ExtractRequestSystem]

        config : typing.Optional[ExtractRequestConfig]

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

        Returns
        -------
        HttpResponse[ExtractCodesResult]
            Successfully extracted codes
        """
        _response = self._client_wrapper.httpx_client.request(
            "construe/extract",
            method="POST",
            json={
                "text": text,
                "system": convert_and_respect_annotation_metadata(
                    object_=system, annotation=ExtractRequestSystem, direction="write"
                ),
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ExtractRequestConfig, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ExtractCodesResult,
                    parse_obj_as(
                        type_=ExtractCodesResult,  # 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 == 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)


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

    async def upload_code_system(
        self,
        *,
        name: str,
        version: str,
        format: UploadRequestFormat,
        file: str,
        revision: typing.Optional[float] = OMIT,
        code_col: typing.Optional[str] = OMIT,
        desc_col: typing.Optional[str] = OMIT,
        defn_col: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ConstrueUploadCodeSystemResponse]:
        """
        Upload a custom medical code system with codes and descriptions for use in code extraction.
        Upon upload, construe generates embeddings for all of the codes in the code system and stores them in the vector database so you can
        subsequently use the code system for construe/extract and lang2fhir/create (coming soon!)

        Parameters
        ----------
        name : str
            Name of the code system

        version : str
            Version of the code system

        format : UploadRequestFormat
            Format of the uploaded file

        file : str
            The file contents as a base64-encoded string

        revision : typing.Optional[float]
            Optional revision number

        code_col : typing.Optional[str]
            Column name containing codes (required for CSV format)

        desc_col : typing.Optional[str]
            Column name containing descriptions (required for CSV format)

        defn_col : typing.Optional[str]
            Optional column name containing long definitions (for CSV format)

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

        Returns
        -------
        AsyncHttpResponse[ConstrueUploadCodeSystemResponse]
            Successfully uploaded code system
        """
        _response = await self._client_wrapper.httpx_client.request(
            "construe/upload",
            method="POST",
            json={
                "name": name,
                "version": version,
                "revision": revision,
                "format": format,
                "file": file,
                "code_col": code_col,
                "desc_col": desc_col,
                "defn_col": defn_col,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConstrueUploadCodeSystemResponse,
                    parse_obj_as(
                        type_=ConstrueUploadCodeSystemResponse,  # 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 == 409:
                raise ConflictError(
                    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 extract_codes(
        self,
        *,
        text: str,
        system: typing.Optional[ExtractRequestSystem] = OMIT,
        config: typing.Optional[ExtractRequestConfig] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ExtractCodesResult]:
        """
        Converts natural language text into structured medical codes

        Parameters
        ----------
        text : str
            Natural language text to extract codes from

        system : typing.Optional[ExtractRequestSystem]

        config : typing.Optional[ExtractRequestConfig]

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

        Returns
        -------
        AsyncHttpResponse[ExtractCodesResult]
            Successfully extracted codes
        """
        _response = await self._client_wrapper.httpx_client.request(
            "construe/extract",
            method="POST",
            json={
                "text": text,
                "system": convert_and_respect_annotation_metadata(
                    object_=system, annotation=ExtractRequestSystem, direction="write"
                ),
                "config": convert_and_respect_annotation_metadata(
                    object_=config, annotation=ExtractRequestConfig, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ExtractCodesResult,
                    parse_obj_as(
                        type_=ExtractCodesResult,  # 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 == 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)
