# 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.jsonable_encoder import jsonable_encoder
from ...core.pydantic_utilities import parse_obj_as
from ...core.request_options import RequestOptions
from ..yes_no_indicator.types.yes_no_indicator import YesNoIndicator
from .errors.diagnosis_not_found_http_error import DiagnosisNotFoundHttpError
from .errors.disallow_multiple_primary_diagnosis_http_error import DisallowMultiplePrimaryDiagnosisHttpError
from .errors.service_lines_must_have_at_least_one_diagnosis_http_error import (
    ServiceLinesMustHaveAtLeastOneDiagnosisHttpError,
)
from .types.diagnosis import Diagnosis
from .types.diagnosis_id import DiagnosisId
from .types.diagnosis_not_found_error import DiagnosisNotFoundError
from .types.diagnosis_type_code import DiagnosisTypeCode
from .types.disallow_multiple_primary_diagnosis_error import DisallowMultiplePrimaryDiagnosisError
from .types.service_lines_must_have_at_least_one_diagnosis_error import ServiceLinesMustHaveAtLeastOneDiagnosisError
from .types.standalone_diagnosis_create import StandaloneDiagnosisCreate

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


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

    def create(
        self, *, request: StandaloneDiagnosisCreate, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Diagnosis]:
        """
        Creates a new diagnosis for an encounter

        Parameters
        ----------
        request : StandaloneDiagnosisCreate

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

        Returns
        -------
        HttpResponse[Diagnosis]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/diagnoses/v2",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json=request,
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Diagnosis,
                parse_obj_as(
                    type_=Diagnosis,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update(
        self,
        diagnosis_id: DiagnosisId,
        *,
        name: typing.Optional[str] = OMIT,
        code_type: typing.Optional[DiagnosisTypeCode] = OMIT,
        code: typing.Optional[str] = OMIT,
        present_on_admission_indicator: typing.Optional[YesNoIndicator] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Diagnosis]:
        """
        Updates the diagnosis record matching the provided `diagnosis_id`

        Parameters
        ----------
        diagnosis_id : DiagnosisId

        name : typing.Optional[str]
            Empty string not allowed.

        code_type : typing.Optional[DiagnosisTypeCode]
            Typically, providers submitting claims to Candid are using ICD-10 diagnosis codes. If you are using ICD-10 codes, the primary diagnosis code listed on the claim should use the ABK code_type. If more than one diagnosis is being submitted on a claim, please use ABF for the rest of the listed diagnoses. If you are using ICD-9 diagnosis codes, use BK and BF for the principal and following diagnosis code(s) respectively.

        code : typing.Optional[str]
            Empty string not allowed.
            Should be of the appropriate format for the provided `code_type`.
            Must obey the ICD-10 format if an ICD-10 code_type is provided, specifically:
              - Letter
              - Digit
              - Digit or the letter `A` or `B`
              - (Optional) Period `.`
              - Up to 4 (or as few as 0) letters and digits

        present_on_admission_indicator : typing.Optional[YesNoIndicator]
            For Institutional claims only.
            A "Y" indicates that the onset occurred prior to admission to the hospital.
            An "N" indicates that the onset did NOT occur prior to admission to the hospital.
            A "U" indicates that it is unknown whether the onset occurred prior to admission to the hospital or not.

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

        Returns
        -------
        HttpResponse[Diagnosis]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/diagnoses/v2/{jsonable_encoder(diagnosis_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "name": name,
                "code_type": code_type,
                "code": code,
                "present_on_admission_indicator": present_on_admission_indicator,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Diagnosis,
                parse_obj_as(
                    type_=Diagnosis,  # type: ignore
                    object_=_response_json,
                ),
            )
            return HttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "DiagnosisNotFoundHTTPError":
                raise DiagnosisNotFoundHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DiagnosisNotFoundError,
                        parse_obj_as(
                            type_=DiagnosisNotFoundError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "DisallowMultiplePrimaryDiagnosisHTTPError":
                raise DisallowMultiplePrimaryDiagnosisHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DisallowMultiplePrimaryDiagnosisError,
                        parse_obj_as(
                            type_=DisallowMultiplePrimaryDiagnosisError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, diagnosis_id: DiagnosisId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Deletes the diagnosis record associated with the provided `diagnosis_id`

        Parameters
        ----------
        diagnosis_id : DiagnosisId

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/diagnoses/v2/{jsonable_encoder(diagnosis_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="DELETE",
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return HttpResponse(response=_response, data=None)
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "DiagnosisNotFoundHTTPError":
                raise DiagnosisNotFoundHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DiagnosisNotFoundError,
                        parse_obj_as(
                            type_=DiagnosisNotFoundError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "ServiceLinesMustHaveAtLeastOneDiagnosisHTTPError":
                raise ServiceLinesMustHaveAtLeastOneDiagnosisHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ServiceLinesMustHaveAtLeastOneDiagnosisError,
                        parse_obj_as(
                            type_=ServiceLinesMustHaveAtLeastOneDiagnosisError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def create(
        self, *, request: StandaloneDiagnosisCreate, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Diagnosis]:
        """
        Creates a new diagnosis for an encounter

        Parameters
        ----------
        request : StandaloneDiagnosisCreate

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

        Returns
        -------
        AsyncHttpResponse[Diagnosis]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/diagnoses/v2",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json=request,
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Diagnosis,
                parse_obj_as(
                    type_=Diagnosis,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update(
        self,
        diagnosis_id: DiagnosisId,
        *,
        name: typing.Optional[str] = OMIT,
        code_type: typing.Optional[DiagnosisTypeCode] = OMIT,
        code: typing.Optional[str] = OMIT,
        present_on_admission_indicator: typing.Optional[YesNoIndicator] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Diagnosis]:
        """
        Updates the diagnosis record matching the provided `diagnosis_id`

        Parameters
        ----------
        diagnosis_id : DiagnosisId

        name : typing.Optional[str]
            Empty string not allowed.

        code_type : typing.Optional[DiagnosisTypeCode]
            Typically, providers submitting claims to Candid are using ICD-10 diagnosis codes. If you are using ICD-10 codes, the primary diagnosis code listed on the claim should use the ABK code_type. If more than one diagnosis is being submitted on a claim, please use ABF for the rest of the listed diagnoses. If you are using ICD-9 diagnosis codes, use BK and BF for the principal and following diagnosis code(s) respectively.

        code : typing.Optional[str]
            Empty string not allowed.
            Should be of the appropriate format for the provided `code_type`.
            Must obey the ICD-10 format if an ICD-10 code_type is provided, specifically:
              - Letter
              - Digit
              - Digit or the letter `A` or `B`
              - (Optional) Period `.`
              - Up to 4 (or as few as 0) letters and digits

        present_on_admission_indicator : typing.Optional[YesNoIndicator]
            For Institutional claims only.
            A "Y" indicates that the onset occurred prior to admission to the hospital.
            An "N" indicates that the onset did NOT occur prior to admission to the hospital.
            A "U" indicates that it is unknown whether the onset occurred prior to admission to the hospital or not.

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

        Returns
        -------
        AsyncHttpResponse[Diagnosis]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/diagnoses/v2/{jsonable_encoder(diagnosis_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "name": name,
                "code_type": code_type,
                "code": code,
                "present_on_admission_indicator": present_on_admission_indicator,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if 200 <= _response.status_code < 300:
            _data = typing.cast(
                Diagnosis,
                parse_obj_as(
                    type_=Diagnosis,  # type: ignore
                    object_=_response_json,
                ),
            )
            return AsyncHttpResponse(response=_response, data=_data)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "DiagnosisNotFoundHTTPError":
                raise DiagnosisNotFoundHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DiagnosisNotFoundError,
                        parse_obj_as(
                            type_=DiagnosisNotFoundError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "DisallowMultiplePrimaryDiagnosisHTTPError":
                raise DisallowMultiplePrimaryDiagnosisHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DisallowMultiplePrimaryDiagnosisError,
                        parse_obj_as(
                            type_=DisallowMultiplePrimaryDiagnosisError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, diagnosis_id: DiagnosisId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Deletes the diagnosis record associated with the provided `diagnosis_id`

        Parameters
        ----------
        diagnosis_id : DiagnosisId

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/diagnoses/v2/{jsonable_encoder(diagnosis_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="DELETE",
            request_options=request_options,
        )
        if 200 <= _response.status_code < 300:
            return AsyncHttpResponse(response=_response, data=None)
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        if "errorName" in _response_json:
            if _response_json["errorName"] == "DiagnosisNotFoundHTTPError":
                raise DiagnosisNotFoundHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        DiagnosisNotFoundError,
                        parse_obj_as(
                            type_=DiagnosisNotFoundError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
            if _response_json["errorName"] == "ServiceLinesMustHaveAtLeastOneDiagnosisHTTPError":
                raise ServiceLinesMustHaveAtLeastOneDiagnosisHttpError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ServiceLinesMustHaveAtLeastOneDiagnosisError,
                        parse_obj_as(
                            type_=ServiceLinesMustHaveAtLeastOneDiagnosisError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    ),
                )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
