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

import typing
from .....core.client_wrapper import SyncClientWrapper
from ....claims.types.claim_status import ClaimStatus
from .types.encounter_sort_options import EncounterSortOptions
from ....commons.types.page_token import PageToken
import datetime as dt
from ....commons.types.encounter_external_id import EncounterExternalId
from ....tags.types.tag_id import TagId
from ....commons.types.work_queue_id import WorkQueueId
from .types.billable_status_type import BillableStatusType
from .types.responsible_party_type import ResponsiblePartyType
from .types.encounter_owner_of_next_action_type import EncounterOwnerOfNextActionType
from .....core.request_options import RequestOptions
from .types.encounter_page import EncounterPage
from .....core.datetime_utils import serialize_datetime
from json.decoder import JSONDecodeError
from .....core.api_error import ApiError
from .....core.pydantic_utilities import parse_obj_as
from ....commons.types.encounter_id import EncounterId
from .types.encounter import Encounter
from .....core.jsonable_encoder import jsonable_encoder
from ....individual.types.patient_create import PatientCreate
from ....encounter_providers.resources.v_2.types.billing_provider import BillingProvider
from ....encounter_providers.resources.v_2.types.rendering_provider import RenderingProvider
from ....diagnoses.types.diagnosis_create import DiagnosisCreate
from ....commons.types.facility_type_code import FacilityTypeCode
from ....encounter_providers.resources.v_2.types.referring_provider import ReferringProvider
from ....encounter_providers.resources.v_2.types.initial_referring_provider import InitialReferringProvider
from ....encounter_providers.resources.v_2.types.supervising_provider import SupervisingProvider
from ....service_facility.types.encounter_service_facility_base import EncounterServiceFacilityBase
from ....individual.types.subscriber_create import SubscriberCreate
from .types.prior_authorization_number import PriorAuthorizationNumber
from .types.clinical_note_category_create import ClinicalNoteCategoryCreate
from ....billing_notes.resources.v_2.types.billing_note_base import BillingNoteBase
from .types.patient_history_category import PatientHistoryCategory
from ....service_lines.resources.v_2.types.service_line_create import ServiceLineCreate
from ....guarantor.resources.v_1.types.guarantor_create import GuarantorCreate
from ....claim_submission.resources.v_1.types.external_claim_submission_create import ExternalClaimSubmissionCreate
from ....custom_schemas.resources.v_1.types.schema_instance import SchemaInstance
from .types.medication import Medication
from .types.vitals import Vitals
from .types.intervention import Intervention
from ....commons.types.street_address_long_zip import StreetAddressLongZip
from .types.synchronicity_type import SynchronicityType
from .types.service_authorization_exception_code import ServiceAuthorizationExceptionCode
from ....commons.types.delay_reason_code import DelayReasonCode
from .errors.encounter_external_id_uniqueness_error import EncounterExternalIdUniquenessError
from .types.encounter_external_id_uniqueness_error_type import EncounterExternalIdUniquenessErrorType
from .errors.encounter_patient_control_number_uniqueness_error import EncounterPatientControlNumberUniquenessError
from .types.encounter_patient_control_number_uniqueness_error_type import (
    EncounterPatientControlNumberUniquenessErrorType,
)
from ....commons.errors.entity_not_found_error import EntityNotFoundError
from ....commons.types.entity_not_found_error_message import EntityNotFoundErrorMessage
from .errors.encounter_guarantor_missing_contact_info_error import EncounterGuarantorMissingContactInfoError
from .types.encounter_guarantor_missing_contact_info_error_type import EncounterGuarantorMissingContactInfoErrorType
from ....commons.errors.http_request_validations_error import HttpRequestValidationsError
from ....commons.types.request_validation_error import RequestValidationError
from .errors.cash_pay_payer_error import CashPayPayerError
from .types.cash_pay_payer_error_message import CashPayPayerErrorMessage
from .errors.schema_instance_validation_http_failure import SchemaInstanceValidationHttpFailure
from .types.schema_instance_validation_failure import SchemaInstanceValidationFailure
from .errors.invalid_tag_names_error import InvalidTagNamesError
from .types.invalid_tag_names_error_type import InvalidTagNamesErrorType
from ....commons.errors.http_request_validation_error import HttpRequestValidationError
from ....commons.types.pre_encounter_patient_id import PreEncounterPatientId
from ....commons.types.pre_encounter_appointment_id import PreEncounterAppointmentId
from ....diagnoses.types.diagnosis_id import DiagnosisId
from ....individual.types.patient_update import PatientUpdate
from .types.vitals_update import VitalsUpdate
from ....encounter_providers.resources.v_2.types.rendering_provider_update import RenderingProviderUpdate
from ....service_facility.types.encounter_service_facility_update import EncounterServiceFacilityUpdate
from ....guarantor.resources.v_1.types.guarantor_update import GuarantorUpdate
from ....encounter_providers.resources.v_2.types.billing_provider_update import BillingProviderUpdate
from ....encounter_providers.resources.v_2.types.supervising_provider_update import SupervisingProviderUpdate
from ....encounter_providers.resources.v_2.types.referring_provider_update import ReferringProviderUpdate
from ....encounter_providers.resources.v_2.types.initial_referring_provider_update import InitialReferringProviderUpdate
from ....commons.errors.unauthorized_error import UnauthorizedError
from ....commons.types.unauthorized_error_message import UnauthorizedErrorMessage
from ....commons.errors.unprocessable_entity_error import UnprocessableEntityError
from ....commons.types.unprocessable_entity_error_message import UnprocessableEntityErrorMessage
from .....core.client_wrapper import AsyncClientWrapper

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


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

    def get_all(
        self,
        *,
        limit: typing.Optional[int] = None,
        claim_status: typing.Optional[ClaimStatus] = None,
        sort: typing.Optional[EncounterSortOptions] = None,
        page_token: typing.Optional[PageToken] = None,
        date_of_service_min: typing.Optional[dt.date] = None,
        date_of_service_max: typing.Optional[dt.date] = None,
        primary_payer_names: typing.Optional[str] = None,
        search_term: typing.Optional[str] = None,
        external_id: typing.Optional[EncounterExternalId] = None,
        diagnoses_updated_since: typing.Optional[dt.datetime] = None,
        tag_ids: typing.Optional[typing.Union[TagId, typing.Sequence[TagId]]] = None,
        work_queue_id: typing.Optional[WorkQueueId] = None,
        billable_status: typing.Optional[BillableStatusType] = None,
        responsible_party: typing.Optional[ResponsiblePartyType] = None,
        owner_of_next_action: typing.Optional[EncounterOwnerOfNextActionType] = None,
        patient_external_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> EncounterPage:
        """
        Parameters
        ----------
        limit : typing.Optional[int]
            Maximum number of entities per page, defaults to 100.

        claim_status : typing.Optional[ClaimStatus]
            Indicates the current status of an insurance claim within the billing process.

        sort : typing.Optional[EncounterSortOptions]
            Defaults to created_at:desc.

        page_token : typing.Optional[PageToken]

        date_of_service_min : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.

        date_of_service_max : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.

        primary_payer_names : typing.Optional[str]
            Comma delimited string.

        search_term : typing.Optional[str]
            Filter by any of the following fields: encounter_id, claim_id, patient external_id,
            patient date of birth, patient first name, patient last name,
            or encounter external id.

        external_id : typing.Optional[EncounterExternalId]
            Filter to an exact match on encounter external_id, if one exists.

        diagnoses_updated_since : typing.Optional[dt.datetime]
            ISO 8601 timestamp; ideally in UTC (although not required): 2019-08-24T14:15:22Z.

        tag_ids : typing.Optional[typing.Union[TagId, typing.Sequence[TagId]]]
            Filter by name of tags on encounters.

        work_queue_id : typing.Optional[WorkQueueId]

        billable_status : typing.Optional[BillableStatusType]
            Defines if the Encounter is to be billed by Candid to the responsible_party. Examples for when this should be set to NOT_BILLABLE include if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        responsible_party : typing.Optional[ResponsiblePartyType]
            Defines the party to be billed with the initial balance owed on the claim. Use SELF_PAY if you intend to bill self pay/cash pay.

        owner_of_next_action : typing.Optional[EncounterOwnerOfNextActionType]
            The party who is responsible for taking the next action on an Encounter, as defined by ownership of open Tasks.

        patient_external_id : typing.Optional[str]
            The patient ID from the external EMR platform for the patient

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

        Returns
        -------
        EncounterPage

        Examples
        --------
        import datetime

        from candid import CandidApiClient
        from candid.resources.claims import ClaimStatus
        from candid.resources.encounters.resources.v_4 import EncounterSortOptions

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.encounters.v_4.get_all(
            limit=100,
            claim_status=ClaimStatus.BILLER_RECEIVED,
            sort=EncounterSortOptions.CREATED_AT_ASC,
            page_token="eyJ0b2tlbiI6IjEiLCJwYWdlX3Rva2VuIjoiMiJ9",
            date_of_service_min=datetime.date.fromisoformat(
                "2019-08-24",
            ),
            date_of_service_max=datetime.date.fromisoformat(
                "2019-08-25",
            ),
            primary_payer_names="Medicare,Medicaid",
            search_term="doe",
            external_id="123456",
            diagnoses_updated_since=datetime.datetime.fromisoformat(
                "2019-08-24 14:15:22+00:00",
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/encounters/v4",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "limit": limit,
                "claim_status": claim_status,
                "sort": sort,
                "page_token": page_token,
                "date_of_service_min": str(date_of_service_min) if date_of_service_min is not None else None,
                "date_of_service_max": str(date_of_service_max) if date_of_service_max is not None else None,
                "primary_payer_names": primary_payer_names,
                "search_term": search_term,
                "external_id": external_id,
                "diagnoses_updated_since": serialize_datetime(diagnoses_updated_since)
                if diagnoses_updated_since is not None
                else None,
                "tag_ids": tag_ids,
                "work_queue_id": work_queue_id,
                "billable_status": billable_status,
                "responsible_party": responsible_party,
                "owner_of_next_action": owner_of_next_action,
                "patient_external_id": patient_external_id,
            },
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                EncounterPage,
                parse_obj_as(
                    type_=EncounterPage,  # type: ignore
                    object_=_response_json,
                ),
            )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, encounter_id: EncounterId, *, request_options: typing.Optional[RequestOptions] = None) -> Encounter:
        """
        Parameters
        ----------
        encounter_id : EncounterId

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

        Returns
        -------
        Encounter

        Examples
        --------
        import uuid

        from candid import CandidApiClient

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.encounters.v_4.get(
            encounter_id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/encounters/v4/{jsonable_encoder(encounter_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        patient: PatientCreate,
        billing_provider: BillingProvider,
        rendering_provider: RenderingProvider,
        responsible_party: ResponsiblePartyType,
        diagnoses: typing.Sequence[DiagnosisCreate],
        place_of_service_code: FacilityTypeCode,
        external_id: EncounterExternalId,
        patient_authorized_release: bool,
        benefits_assigned_to_provider: bool,
        provider_accepts_assignment: bool,
        billable_status: BillableStatusType,
        referring_provider: typing.Optional[ReferringProvider] = OMIT,
        initial_referring_provider: typing.Optional[InitialReferringProvider] = OMIT,
        supervising_provider: typing.Optional[SupervisingProvider] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityBase] = OMIT,
        subscriber_primary: typing.Optional[SubscriberCreate] = OMIT,
        subscriber_secondary: typing.Optional[SubscriberCreate] = OMIT,
        prior_authorization_number: typing.Optional[PriorAuthorizationNumber] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        billing_notes: typing.Optional[typing.Sequence[BillingNoteBase]] = OMIT,
        patient_histories: typing.Optional[typing.Sequence[PatientHistoryCategory]] = OMIT,
        service_lines: typing.Optional[typing.Sequence[ServiceLineCreate]] = OMIT,
        guarantor: typing.Optional[GuarantorCreate] = OMIT,
        external_claim_submission: typing.Optional[ExternalClaimSubmissionCreate] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        referral_number: typing.Optional[str] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        vitals: typing.Optional[Vitals] = OMIT,
        interventions: typing.Optional[typing.Sequence[Intervention]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Parameters
        ----------
        patient : PatientCreate
            Contains the identification information of the individual receiving medical services.


        billing_provider : BillingProvider
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.


        rendering_provider : RenderingProvider
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.


        responsible_party : ResponsiblePartyType
            Defines the party to be billed with the initial balance owed on the claim.


        diagnoses : typing.Sequence[DiagnosisCreate]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code : FacilityTypeCode
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        external_id : EncounterExternalId
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        patient_authorized_release : bool
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        benefits_assigned_to_provider : bool
            Whether this patient has authorized insurance payments to be made to you,
            not them. If false, patient may receive reimbursement.
            Box 13 on the CMS-1500 claim form.

        provider_accepts_assignment : bool
            Whether you have accepted the patient's authorization for insurance payments
            to be made to you, not them.
            Box 27 on the CMS-1500 claim form.

        billable_status : BillableStatusType
            Defines if the Encounter is to be billed by Candid to the responsible_party.
            Examples for when this should be set to NOT_BILLABLE include
            if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        referring_provider : typing.Optional[ReferringProvider]
            The final provider who referred the services that were rendered.
            All physicians who order services or refer Medicare beneficiaries must
            report this data.


        initial_referring_provider : typing.Optional[InitialReferringProvider]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.


        supervising_provider : typing.Optional[SupervisingProvider]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.


        service_facility : typing.Optional[EncounterServiceFacilityBase]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.


        subscriber_primary : typing.Optional[SubscriberCreate]
            Subscriber_primary is required when responsible_party is INSURANCE_PAY (i.e. when the claim should be billed to insurance).
            These are not required fields when responsible_party is SELF_PAY (i.e. when the claim should be billed to the patient).
            However, if you collect this for patients, even self-pay, we recommend including it when sending encounters to Candid.
            Note: Cash Pay is no longer a valid payer_id in v4, please use responsible party to define self-pay claims.


        subscriber_secondary : typing.Optional[SubscriberCreate]
            Please always include this when you have it, even for self-pay claims.


        prior_authorization_number : typing.Optional[PriorAuthorizationNumber]
            Box 23 on the CMS-1500 claim form.

        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        billing_notes : typing.Optional[typing.Sequence[BillingNoteBase]]
            Spot to store misc, human-readable, notes about this encounter to be used
            in the billing process.


        patient_histories : typing.Optional[typing.Sequence[PatientHistoryCategory]]

        service_lines : typing.Optional[typing.Sequence[ServiceLineCreate]]
            Each service line must be linked to a diagnosis. Concretely,
            `service_line.diagnosis_pointers`must contain at least one entry which should be
            in bounds of the diagnoses list field.


        guarantor : typing.Optional[GuarantorCreate]
            Personal and contact info for the guarantor of the patient responsibility.


        external_claim_submission : typing.Optional[ExternalClaimSubmissionCreate]
            ***This field is in beta.***
            To be included for claims that have been submitted outside of Candid.
            Candid supports posting remits and payments to these claims and working them in-platform (e.g. editing, resubmitting).


        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter.


        referral_number : typing.Optional[str]
            Refers to REF*9F on the 837p. Value cannot be greater than 50 characters.


        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            date_of_service must be defined on either the encounter or the service lines but not both.
            If there are greater than zero service lines, it is recommended to specify date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If there are greater than zero service lines, it is recommended to specify end_date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        existing_medications : typing.Optional[typing.Sequence[Medication]]

        vitals : typing.Optional[Vitals]

        interventions : typing.Optional[typing.Sequence[Intervention]]

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter.
            Asynchronous encounters occur when providers and patients communicate online using
            forms, instant messaging, or other pre-recorded digital mediums.
            Synchronous encounters occur in live, real-time settings where the patient interacts
            directly with the provider, such as over video or a phone call.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

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

        Returns
        -------
        Encounter

        Examples
        --------
        import datetime
        import uuid

        from candid import CandidApiClient
        from candid.resources.billing_notes.resources.v_2 import BillingNoteBase
        from candid.resources.claim_submission.resources.v_1 import (
            ClaimFrequencyTypeCode,
            ClaimSubmissionRecordCreate,
            ExternalClaimSubmissionCreate,
        )
        from candid.resources.commons import (
            BillingProviderCommercialLicenseType,
            ClaimSubmissionPayerResponsibilityType,
            DelayReasonCode,
            EmrPayerCrosswalk,
            FacilityTypeCode,
            InsuranceTypeCode,
            IntendedSubmissionMedium,
            PatientRelationshipToInsuredCodeAll,
            PhoneNumber,
            PhoneNumberType,
            ProcedureModifier,
            QualifierCode,
            ServiceLineUnits,
            SourceOfPaymentCode,
            State,
            StreetAddressLongZip,
            StreetAddressShortZip,
        )
        from candid.resources.custom_schemas.resources.v_1 import SchemaInstance
        from candid.resources.diagnoses import DiagnosisCreate, DiagnosisTypeCode
        from candid.resources.encounter_providers.resources.v_2 import (
            BillingProvider,
            InitialReferringProvider,
            OrderingProvider,
            ReferringProvider,
            RenderingProvider,
            SupervisingProvider,
        )
        from candid.resources.encounters.resources.v_4 import (
            BillableStatusType,
            ClinicalNote,
            ClinicalNoteCategoryCreate,
            IntakeFollowUp,
            IntakeQuestion,
            IntakeResponseAndFollowUps,
            Intervention,
            InterventionCategory,
            Lab,
            LabCodeType,
            Medication,
            NoteCategory,
            PatientHistoryCategory,
            PatientHistoryCategoryEnum,
            ResponsiblePartyType,
            ServiceAuthorizationExceptionCode,
            SynchronicityType,
            Vitals,
        )
        from candid.resources.guarantor.resources.v_1 import GuarantorCreate
        from candid.resources.individual import (
            Gender,
            PatientCreate,
            PatientNonInsurancePayerInfoCreate,
            SubscriberCreate,
        )
        from candid.resources.insurance_cards.resources.v_2 import InsuranceCardCreate
        from candid.resources.service_facility import EncounterServiceFacilityBase
        from candid.resources.service_lines.resources.v_2 import (
            DrugIdentification,
            MeasurementUnitCode,
            ServiceIdQualifier,
            ServiceLineCreate,
            TestResult,
            TestResultType,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.encounters.v_4.create(
            patient=PatientCreate(
                phone_numbers=[
                    PhoneNumber(
                        number="1234567890",
                        type=PhoneNumberType.HOME,
                    )
                ],
                phone_consent=True,
                email="johndoe@joincandidhealth.com",
                non_insurance_payers=[
                    uuid.UUID(
                        "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                    )
                ],
                non_insurance_payers_info=[
                    PatientNonInsurancePayerInfoCreate(
                        non_insurance_payer_id=uuid.UUID(
                            "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                        ),
                        member_id="string",
                    )
                ],
                email_consent=True,
                external_id="string",
                date_of_birth=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                address=StreetAddressShortZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                gender=Gender.MALE,
            ),
            billing_provider=BillingProvider(
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                tax_id="string",
                npi="string",
                taxonomy_code="string",
                provider_commercial_license_type=BillingProviderCommercialLicenseType.LICENSED_CLINICAL_SOCIAL_WORKER,
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            rendering_provider=RenderingProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            referring_provider=ReferringProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            initial_referring_provider=InitialReferringProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                qualifier=QualifierCode.DQ,
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            supervising_provider=SupervisingProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            service_facility=EncounterServiceFacilityBase(
                organization_name="string",
                npi="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                secondary_identification="string",
            ),
            subscriber_primary=SubscriberCreate(
                insurance_card=InsuranceCardCreate(
                    member_id="string",
                    payer_name="string",
                    payer_id="string",
                    rx_bin="string",
                    rx_pcn="string",
                    image_url_front="string",
                    image_url_back="string",
                    emr_payer_crosswalk=EmrPayerCrosswalk.HEALTHIE,
                    group_number="string",
                    plan_name="string",
                    plan_type=SourceOfPaymentCode.SELF_PAY,
                    insurance_type=InsuranceTypeCode.C_01,
                ),
                patient_relationship_to_subscriber_code=PatientRelationshipToInsuredCodeAll.SPOUSE,
                date_of_birth=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                address=StreetAddressShortZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                gender=Gender.MALE,
            ),
            subscriber_secondary=SubscriberCreate(
                insurance_card=InsuranceCardCreate(
                    member_id="string",
                    payer_name="string",
                    payer_id="string",
                    rx_bin="string",
                    rx_pcn="string",
                    image_url_front="string",
                    image_url_back="string",
                    emr_payer_crosswalk=EmrPayerCrosswalk.HEALTHIE,
                    group_number="string",
                    plan_name="string",
                    plan_type=SourceOfPaymentCode.SELF_PAY,
                    insurance_type=InsuranceTypeCode.C_01,
                ),
                patient_relationship_to_subscriber_code=PatientRelationshipToInsuredCodeAll.SPOUSE,
                date_of_birth=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                address=StreetAddressShortZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                gender=Gender.MALE,
            ),
            prior_authorization_number="string",
            responsible_party=ResponsiblePartyType.INSURANCE_PAY,
            diagnoses=[
                DiagnosisCreate(
                    name="string",
                    code_type=DiagnosisTypeCode.ABF,
                    code="string",
                )
            ],
            clinical_notes=[
                ClinicalNoteCategoryCreate(
                    category=NoteCategory.CLINICAL,
                    notes=[
                        ClinicalNote(
                            text="string",
                            author_name="string",
                            author_npi="string",
                            timestamp=datetime.datetime.fromisoformat(
                                "2024-01-15 09:30:00+00:00",
                            ),
                        )
                    ],
                )
            ],
            billing_notes=[
                BillingNoteBase(
                    text="string",
                )
            ],
            place_of_service_code=FacilityTypeCode.PHARMACY,
            patient_histories=[
                PatientHistoryCategory(
                    category=PatientHistoryCategoryEnum.PRESENT_ILLNESS,
                    questions=[
                        IntakeQuestion(
                            id="6E7FBCE4-A8EA-46D0-A8D8-FF83CA3BB176",
                            text="Do you have any allergies?",
                            responses=[
                                IntakeResponseAndFollowUps(
                                    response="No allergies",
                                    follow_ups=[
                                        IntakeFollowUp(
                                            id="4F3D57F9-AC94-49D6-87E4-E804B709917A",
                                            text="Do you have any allergies?",
                                            response="No allergies",
                                        )
                                    ],
                                )
                            ],
                        )
                    ],
                )
            ],
            service_lines=[
                ServiceLineCreate(
                    modifiers=[ProcedureModifier.TWENTY_TWO],
                    procedure_code="string",
                    quantity="string",
                    units=ServiceLineUnits.MJ,
                    charge_amount_cents=1,
                    diagnosis_pointers=[1],
                    drug_identification=DrugIdentification(
                        service_id_qualifier=ServiceIdQualifier.EAN_UCC_13,
                        national_drug_code="string",
                        national_drug_unit_count="string",
                        measurement_unit_code=MeasurementUnitCode.MILLILITERS,
                        link_sequence_number="string",
                        pharmacy_prescription_number="string",
                        conversion_formula="string",
                        drug_description="string",
                    ),
                    place_of_service_code=FacilityTypeCode.PHARMACY,
                    description="string",
                    date_of_service=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    end_date_of_service=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    ordering_provider=OrderingProvider(
                        npi="string",
                        taxonomy_code="string",
                        address=StreetAddressLongZip(
                            address_1="123 Main St",
                            address_2="Apt 1",
                            city="New York",
                            state=State.NY,
                            zip_code="10001",
                            zip_plus_four_code="1234",
                        ),
                        first_name="string",
                        last_name="string",
                        organization_name="string",
                    ),
                    test_results=[
                        TestResult(
                            value=1.1,
                            result_type=TestResultType.HEMATOCRIT,
                        )
                    ],
                )
            ],
            guarantor=GuarantorCreate(
                phone_numbers=[
                    PhoneNumber(
                        number="1234567890",
                        type=PhoneNumberType.HOME,
                    )
                ],
                phone_consent=True,
                email="johndoe@joincandidhealth.com",
                email_consent=True,
                first_name="string",
                last_name="string",
                external_id="string",
                date_of_birth=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                address=StreetAddressShortZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
            ),
            external_claim_submission=ExternalClaimSubmissionCreate(
                claim_created_at=datetime.datetime.fromisoformat(
                    "2023-01-01 12:00:00+00:00",
                ),
                patient_control_number="PATIENT_CONTROL_NUMBER",
                submission_records=[
                    ClaimSubmissionRecordCreate(
                        submitted_at=datetime.datetime.fromisoformat(
                            "2023-01-01 13:00:00+00:00",
                        ),
                        claim_frequency_code=ClaimFrequencyTypeCode.ORIGINAL,
                        payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                        intended_submission_medium=IntendedSubmissionMedium.ELECTRONIC,
                    ),
                    ClaimSubmissionRecordCreate(
                        submitted_at=datetime.datetime.fromisoformat(
                            "2023-01-04 12:00:00+00:00",
                        ),
                        claim_frequency_code=ClaimFrequencyTypeCode.REPLACEMENT,
                        payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                        intended_submission_medium=IntendedSubmissionMedium.PAPER,
                    ),
                ],
            ),
            tag_ids=["string"],
            schema_instances=[
                SchemaInstance(
                    schema_id=uuid.UUID(
                        "ec096b13-f80a-471d-aaeb-54b021c9d582",
                    ),
                    content={
                        "provider_category": "internist",
                        "is_urgent_care": True,
                        "bmi": 24.2,
                        "age": 38,
                    },
                )
            ],
            referral_number="string",
            external_id="string",
            date_of_service=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            end_date_of_service=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            patient_authorized_release=True,
            benefits_assigned_to_provider=True,
            provider_accepts_assignment=True,
            appointment_type="string",
            existing_medications=[
                Medication(
                    name="Lisinopril",
                    rx_cui="860975",
                    dosage="10mg",
                    dosage_form="Tablet",
                    frequency="Once Daily",
                    as_needed=True,
                )
            ],
            vitals=Vitals(
                height_in=70,
                weight_lbs=165,
                blood_pressure_systolic_mmhg=115,
                blood_pressure_diastolic_mmhg=85,
                body_temperature_f=98.0,
                hemoglobin_gdl=15.1,
                hematocrit_pct=51.2,
            ),
            interventions=[
                Intervention(
                    name="Physical Therapy Session",
                    category=InterventionCategory.LIFESTYLE,
                    description="A session focused on improving muscular strength, flexibility, and range of motion post-injury.",
                    medication=Medication(
                        name="Lisinopril",
                        rx_cui="860975",
                        dosage="10mg",
                        dosage_form="Tablet",
                        frequency="Once Daily",
                        as_needed=True,
                    ),
                    labs=[
                        Lab(
                            name="Genetic Health Labs",
                            code="GH12345",
                            code_type=LabCodeType.QUEST,
                        )
                    ],
                )
            ],
            pay_to_address=StreetAddressLongZip(
                address_1="123 Main St",
                address_2="Apt 1",
                city="New York",
                state=State.NY,
                zip_code="10001",
                zip_plus_four_code="1234",
            ),
            synchronicity=SynchronicityType.SYNCHRONOUS,
            billable_status=BillableStatusType.BILLABLE,
            additional_information="string",
            service_authorization_exception_code=ServiceAuthorizationExceptionCode.C_1,
            admission_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            discharge_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            onset_of_current_illness_or_symptom_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            last_menstrual_period_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            delay_reason_code=DelayReasonCode.C_1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/encounters/v4",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "patient": patient,
                "billing_provider": billing_provider,
                "rendering_provider": rendering_provider,
                "referring_provider": referring_provider,
                "initial_referring_provider": initial_referring_provider,
                "supervising_provider": supervising_provider,
                "service_facility": service_facility,
                "subscriber_primary": subscriber_primary,
                "subscriber_secondary": subscriber_secondary,
                "prior_authorization_number": prior_authorization_number,
                "responsible_party": responsible_party,
                "diagnoses": diagnoses,
                "clinical_notes": clinical_notes,
                "billing_notes": billing_notes,
                "place_of_service_code": place_of_service_code,
                "patient_histories": patient_histories,
                "service_lines": service_lines,
                "guarantor": guarantor,
                "external_claim_submission": external_claim_submission,
                "tag_ids": tag_ids,
                "schema_instances": schema_instances,
                "referral_number": referral_number,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "end_date_of_service": end_date_of_service,
                "patient_authorized_release": patient_authorized_release,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "provider_accepts_assignment": provider_accepts_assignment,
                "appointment_type": appointment_type,
                "existing_medications": existing_medications,
                "vitals": vitals,
                "interventions": interventions,
                "pay_to_address": pay_to_address,
                "synchronicity": synchronicity,
                "billable_status": billable_status,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterPatientControlNumberUniquenessError":
                raise EncounterPatientControlNumberUniquenessError(
                    typing.cast(
                        EncounterPatientControlNumberUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterPatientControlNumberUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterGuarantorMissingContactInfoError":
                raise EncounterGuarantorMissingContactInfoError(
                    typing.cast(
                        EncounterGuarantorMissingContactInfoErrorType,
                        parse_obj_as(
                            type_=EncounterGuarantorMissingContactInfoErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "CashPayPayerError":
                raise CashPayPayerError(
                    typing.cast(
                        CashPayPayerErrorMessage,
                        parse_obj_as(
                            type_=CashPayPayerErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "InvalidTagNamesError":
                raise InvalidTagNamesError(
                    typing.cast(
                        InvalidTagNamesErrorType,
                        parse_obj_as(
                            type_=InvalidTagNamesErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationError":
                raise HttpRequestValidationError(
                    typing.cast(
                        RequestValidationError,
                        parse_obj_as(
                            type_=RequestValidationError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create_from_pre_encounter_patient(
        self,
        *,
        pre_encounter_patient_id: PreEncounterPatientId,
        pre_encounter_appointment_ids: typing.Sequence[PreEncounterAppointmentId],
        billing_provider: BillingProvider,
        rendering_provider: RenderingProvider,
        diagnoses: typing.Sequence[DiagnosisCreate],
        place_of_service_code: FacilityTypeCode,
        external_id: EncounterExternalId,
        patient_authorized_release: bool,
        benefits_assigned_to_provider: bool,
        provider_accepts_assignment: bool,
        billable_status: BillableStatusType,
        initial_referring_provider: typing.Optional[InitialReferringProvider] = OMIT,
        supervising_provider: typing.Optional[SupervisingProvider] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityBase] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        billing_notes: typing.Optional[typing.Sequence[BillingNoteBase]] = OMIT,
        patient_histories: typing.Optional[typing.Sequence[PatientHistoryCategory]] = OMIT,
        service_lines: typing.Optional[typing.Sequence[ServiceLineCreate]] = OMIT,
        external_claim_submission: typing.Optional[ExternalClaimSubmissionCreate] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        vitals: typing.Optional[Vitals] = OMIT,
        interventions: typing.Optional[typing.Sequence[Intervention]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Create an encounter from a pre-encounter patient and appointment. This endpoint is intended to be used by consumers who are managing
        patients and appointments in the pre-encounter service and is currently under development. Consumers who are not taking advantage
        of the pre-encounter service should use the standard create endpoint.

        The endpoint will create an encounter from the provided fields, pulling information from the provided patient and appointment objects
        where applicable. In particular, the following fields are populated from the patient and appointment objects:

        - Patient
        - Referring Provider
        - Subscriber Primary
        - Subscriber Secondary
        - Referral Number
        - Responsible Party
        - Guarantor

        Utilizing this endpoint opts you into automatic updating of the encounter when the patient or appointment is updated, assuming the
        encounter has not already been submitted or adjudicated.

        Parameters
        ----------
        pre_encounter_patient_id : PreEncounterPatientId

        pre_encounter_appointment_ids : typing.Sequence[PreEncounterAppointmentId]

        billing_provider : BillingProvider
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.


        rendering_provider : RenderingProvider
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.


        diagnoses : typing.Sequence[DiagnosisCreate]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code : FacilityTypeCode
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms .gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        external_id : EncounterExternalId
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        patient_authorized_release : bool
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        benefits_assigned_to_provider : bool
            Whether this patient has authorized insurance payments to be made to you,
            not them. If false, patient may receive reimbursement.
            Box 13 on the CMS-1500 claim form.

        provider_accepts_assignment : bool
            Whether you have accepted the patient's authorization for insurance payments
            to be made to you, not them.
            Box 27 on the CMS-1500 claim form.

        billable_status : BillableStatusType
            Defines if the Encounter is to be billed by Candid to the responsible_party.
            Examples for when this should be set to NOT_BILLABLE include
            if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        initial_referring_provider : typing.Optional[InitialReferringProvider]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.


        supervising_provider : typing.Optional[SupervisingProvider]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.


        service_facility : typing.Optional[EncounterServiceFacilityBase]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.


        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        billing_notes : typing.Optional[typing.Sequence[BillingNoteBase]]
            Spot to store misc, human-readable, notes about this encounter to be used
            in the billing process.


        patient_histories : typing.Optional[typing.Sequence[PatientHistoryCategory]]

        service_lines : typing.Optional[typing.Sequence[ServiceLineCreate]]
            Each service line must be linked to a diagnosis. Concretely,
            `service_line.diagnosis_pointers`must contain at least one entry which should be
            in bounds of the diagnoses list field.


        external_claim_submission : typing.Optional[ExternalClaimSubmissionCreate]
            ***This field is in beta.***
            To be included for claims that have been submitted outside of Candid.
            Candid supports posting remits and payments to these claims and working them in-platform (e.g. editing, resubmitting).


        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter.


        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            date_of_service must be defined on either the encounter or the service lines but not both.
            If there are greater than zero service lines, it is recommended to specify date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If there are greater than zero service lines, it is recommended to specify end_date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        existing_medications : typing.Optional[typing.Sequence[Medication]]

        vitals : typing.Optional[Vitals]

        interventions : typing.Optional[typing.Sequence[Intervention]]

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter.
            Asynchronous encounters occur when providers and patients communicate online using
            forms, instant messaging, or other pre-recorded digital mediums.
            Synchronous encounters occur in live, real-time settings where the patient interacts
            directly with the provider, such as over video or a phone call.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

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

        Returns
        -------
        Encounter

        Examples
        --------
        import datetime
        import uuid

        from candid import CandidApiClient
        from candid.resources.billing_notes.resources.v_2 import BillingNoteBase
        from candid.resources.claim_submission.resources.v_1 import (
            ClaimFrequencyTypeCode,
            ClaimSubmissionRecordCreate,
            ExternalClaimSubmissionCreate,
        )
        from candid.resources.commons import (
            BillingProviderCommercialLicenseType,
            ClaimSubmissionPayerResponsibilityType,
            DelayReasonCode,
            FacilityTypeCode,
            IntendedSubmissionMedium,
            ProcedureModifier,
            QualifierCode,
            ServiceLineUnits,
            State,
            StreetAddressLongZip,
        )
        from candid.resources.custom_schemas.resources.v_1 import SchemaInstance
        from candid.resources.diagnoses import DiagnosisCreate, DiagnosisTypeCode
        from candid.resources.encounter_providers.resources.v_2 import (
            BillingProvider,
            InitialReferringProvider,
            OrderingProvider,
            RenderingProvider,
            SupervisingProvider,
        )
        from candid.resources.encounters.resources.v_4 import (
            BillableStatusType,
            ClinicalNote,
            ClinicalNoteCategoryCreate,
            IntakeFollowUp,
            IntakeQuestion,
            IntakeResponseAndFollowUps,
            Intervention,
            InterventionCategory,
            Lab,
            LabCodeType,
            Medication,
            NoteCategory,
            PatientHistoryCategory,
            PatientHistoryCategoryEnum,
            ServiceAuthorizationExceptionCode,
            SynchronicityType,
            Vitals,
        )
        from candid.resources.service_facility import EncounterServiceFacilityBase
        from candid.resources.service_lines.resources.v_2 import (
            DrugIdentification,
            MeasurementUnitCode,
            ServiceIdQualifier,
            ServiceLineCreate,
            TestResult,
            TestResultType,
        )

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.encounters.v_4.create_from_pre_encounter_patient(
            pre_encounter_patient_id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
            pre_encounter_appointment_ids=[
                uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                )
            ],
            billing_provider=BillingProvider(
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                tax_id="string",
                npi="string",
                taxonomy_code="string",
                provider_commercial_license_type=BillingProviderCommercialLicenseType.LICENSED_CLINICAL_SOCIAL_WORKER,
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            rendering_provider=RenderingProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            initial_referring_provider=InitialReferringProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                qualifier=QualifierCode.DQ,
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            supervising_provider=SupervisingProvider(
                npi="string",
                taxonomy_code="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                first_name="string",
                last_name="string",
                organization_name="string",
            ),
            service_facility=EncounterServiceFacilityBase(
                organization_name="string",
                npi="string",
                address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                secondary_identification="string",
            ),
            diagnoses=[
                DiagnosisCreate(
                    name="string",
                    code_type=DiagnosisTypeCode.ABF,
                    code="string",
                )
            ],
            clinical_notes=[
                ClinicalNoteCategoryCreate(
                    category=NoteCategory.CLINICAL,
                    notes=[
                        ClinicalNote(
                            text="string",
                            author_name="string",
                            author_npi="string",
                            timestamp=datetime.datetime.fromisoformat(
                                "2024-01-15 09:30:00+00:00",
                            ),
                        )
                    ],
                )
            ],
            billing_notes=[
                BillingNoteBase(
                    text="string",
                )
            ],
            place_of_service_code=FacilityTypeCode.PHARMACY,
            patient_histories=[
                PatientHistoryCategory(
                    category=PatientHistoryCategoryEnum.PRESENT_ILLNESS,
                    questions=[
                        IntakeQuestion(
                            id="6E7FBCE4-A8EA-46D0-A8D8-FF83CA3BB176",
                            text="Do you have any allergies?",
                            responses=[
                                IntakeResponseAndFollowUps(
                                    response="No allergies",
                                    follow_ups=[
                                        IntakeFollowUp(
                                            id="4F3D57F9-AC94-49D6-87E4-E804B709917A",
                                            text="Do you have any allergies?",
                                            response="No allergies",
                                        )
                                    ],
                                )
                            ],
                        )
                    ],
                )
            ],
            service_lines=[
                ServiceLineCreate(
                    modifiers=[ProcedureModifier.TWENTY_TWO],
                    procedure_code="string",
                    quantity="string",
                    units=ServiceLineUnits.MJ,
                    charge_amount_cents=1,
                    diagnosis_pointers=[1],
                    drug_identification=DrugIdentification(
                        service_id_qualifier=ServiceIdQualifier.EAN_UCC_13,
                        national_drug_code="string",
                        national_drug_unit_count="string",
                        measurement_unit_code=MeasurementUnitCode.MILLILITERS,
                        link_sequence_number="string",
                        pharmacy_prescription_number="string",
                        conversion_formula="string",
                        drug_description="string",
                    ),
                    place_of_service_code=FacilityTypeCode.PHARMACY,
                    description="string",
                    date_of_service=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    end_date_of_service=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    ordering_provider=OrderingProvider(
                        npi="string",
                        taxonomy_code="string",
                        address=StreetAddressLongZip(
                            address_1="123 Main St",
                            address_2="Apt 1",
                            city="New York",
                            state=State.NY,
                            zip_code="10001",
                            zip_plus_four_code="1234",
                        ),
                        first_name="string",
                        last_name="string",
                        organization_name="string",
                    ),
                    test_results=[
                        TestResult(
                            value=1.1,
                            result_type=TestResultType.HEMATOCRIT,
                        )
                    ],
                )
            ],
            external_claim_submission=ExternalClaimSubmissionCreate(
                claim_created_at=datetime.datetime.fromisoformat(
                    "2023-01-01 12:00:00+00:00",
                ),
                patient_control_number="PATIENT_CONTROL_NUMBER",
                submission_records=[
                    ClaimSubmissionRecordCreate(
                        submitted_at=datetime.datetime.fromisoformat(
                            "2023-01-01 13:00:00+00:00",
                        ),
                        claim_frequency_code=ClaimFrequencyTypeCode.ORIGINAL,
                        payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                        intended_submission_medium=IntendedSubmissionMedium.ELECTRONIC,
                    ),
                    ClaimSubmissionRecordCreate(
                        submitted_at=datetime.datetime.fromisoformat(
                            "2023-01-04 12:00:00+00:00",
                        ),
                        claim_frequency_code=ClaimFrequencyTypeCode.REPLACEMENT,
                        payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                        intended_submission_medium=IntendedSubmissionMedium.PAPER,
                    ),
                ],
            ),
            tag_ids=["string"],
            schema_instances=[
                SchemaInstance(
                    schema_id=uuid.UUID(
                        "ec096b13-f80a-471d-aaeb-54b021c9d582",
                    ),
                    content={
                        "provider_category": "internist",
                        "is_urgent_care": True,
                        "bmi": 24.2,
                        "age": 38,
                    },
                )
            ],
            external_id="string",
            date_of_service=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            end_date_of_service=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            patient_authorized_release=True,
            benefits_assigned_to_provider=True,
            provider_accepts_assignment=True,
            appointment_type="string",
            existing_medications=[
                Medication(
                    name="Lisinopril",
                    rx_cui="860975",
                    dosage="10mg",
                    dosage_form="Tablet",
                    frequency="Once Daily",
                    as_needed=True,
                )
            ],
            vitals=Vitals(
                height_in=70,
                weight_lbs=165,
                blood_pressure_systolic_mmhg=115,
                blood_pressure_diastolic_mmhg=85,
                body_temperature_f=98.0,
                hemoglobin_gdl=15.1,
                hematocrit_pct=51.2,
            ),
            interventions=[
                Intervention(
                    name="Physical Therapy Session",
                    category=InterventionCategory.LIFESTYLE,
                    description="A session focused on improving muscular strength, flexibility, and range of motion post-injury.",
                    medication=Medication(
                        name="Lisinopril",
                        rx_cui="860975",
                        dosage="10mg",
                        dosage_form="Tablet",
                        frequency="Once Daily",
                        as_needed=True,
                    ),
                    labs=[
                        Lab(
                            name="Genetic Health Labs",
                            code="GH12345",
                            code_type=LabCodeType.QUEST,
                        )
                    ],
                )
            ],
            pay_to_address=StreetAddressLongZip(
                address_1="123 Main St",
                address_2="Apt 1",
                city="New York",
                state=State.NY,
                zip_code="10001",
                zip_plus_four_code="1234",
            ),
            synchronicity=SynchronicityType.SYNCHRONOUS,
            billable_status=BillableStatusType.BILLABLE,
            additional_information="string",
            service_authorization_exception_code=ServiceAuthorizationExceptionCode.C_1,
            admission_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            discharge_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            onset_of_current_illness_or_symptom_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            last_menstrual_period_date=datetime.date.fromisoformat(
                "2023-01-15",
            ),
            delay_reason_code=DelayReasonCode.C_1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/encounters/v4/create-from-pre-encounter",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "pre_encounter_patient_id": pre_encounter_patient_id,
                "pre_encounter_appointment_ids": pre_encounter_appointment_ids,
                "billing_provider": billing_provider,
                "rendering_provider": rendering_provider,
                "initial_referring_provider": initial_referring_provider,
                "supervising_provider": supervising_provider,
                "service_facility": service_facility,
                "diagnoses": diagnoses,
                "clinical_notes": clinical_notes,
                "billing_notes": billing_notes,
                "place_of_service_code": place_of_service_code,
                "patient_histories": patient_histories,
                "service_lines": service_lines,
                "external_claim_submission": external_claim_submission,
                "tag_ids": tag_ids,
                "schema_instances": schema_instances,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "end_date_of_service": end_date_of_service,
                "patient_authorized_release": patient_authorized_release,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "provider_accepts_assignment": provider_accepts_assignment,
                "appointment_type": appointment_type,
                "existing_medications": existing_medications,
                "vitals": vitals,
                "interventions": interventions,
                "pay_to_address": pay_to_address,
                "synchronicity": synchronicity,
                "billable_status": billable_status,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterPatientControlNumberUniquenessError":
                raise EncounterPatientControlNumberUniquenessError(
                    typing.cast(
                        EncounterPatientControlNumberUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterPatientControlNumberUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationError":
                raise HttpRequestValidationError(
                    typing.cast(
                        RequestValidationError,
                        parse_obj_as(
                            type_=RequestValidationError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        encounter_id: EncounterId,
        *,
        diagnosis_ids: typing.Optional[typing.Sequence[DiagnosisId]] = OMIT,
        place_of_service_code_as_submitted: typing.Optional[FacilityTypeCode] = OMIT,
        benefits_assigned_to_provider: typing.Optional[bool] = OMIT,
        prior_authorization_number: typing.Optional[PriorAuthorizationNumber] = OMIT,
        external_id: typing.Optional[EncounterExternalId] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        billable_status: typing.Optional[BillableStatusType] = OMIT,
        responsible_party: typing.Optional[ResponsiblePartyType] = OMIT,
        provider_accepts_assignment: typing.Optional[bool] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        place_of_service_code: typing.Optional[FacilityTypeCode] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        subscriber_primary: typing.Optional[SubscriberCreate] = OMIT,
        subscriber_secondary: typing.Optional[SubscriberCreate] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        patient: typing.Optional[PatientUpdate] = OMIT,
        patient_authorized_release: typing.Optional[bool] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        vitals: typing.Optional[VitalsUpdate] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        rendering_provider: typing.Optional[RenderingProviderUpdate] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityUpdate] = OMIT,
        guarantor: typing.Optional[GuarantorUpdate] = OMIT,
        billing_provider: typing.Optional[BillingProviderUpdate] = OMIT,
        supervising_provider: typing.Optional[SupervisingProviderUpdate] = OMIT,
        referring_provider: typing.Optional[ReferringProviderUpdate] = OMIT,
        initial_referring_provider: typing.Optional[InitialReferringProviderUpdate] = OMIT,
        referral_number: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Parameters
        ----------
        encounter_id : EncounterId

        diagnosis_ids : typing.Optional[typing.Sequence[DiagnosisId]]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code_as_submitted : typing.Optional[FacilityTypeCode]
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        benefits_assigned_to_provider : typing.Optional[bool]
            Whether this patient has authorized insurance payments to be made to you, not them. If false, patient may receive reimbursement. Box 13 on the CMS-1500 claim form.

        prior_authorization_number : typing.Optional[PriorAuthorizationNumber]
            Box 23 on the CMS-1500 claim form.

        external_id : typing.Optional[EncounterExternalId]
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            If service lines have distinct date_of_service values, updating the encounter's date_of_service will fail. If all service line date_of_service values are the same, updating the encounter's date_of_service will update all service line date_of_service values.

        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter. Note all tags on encounter will be overridden with this list.

        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        billable_status : typing.Optional[BillableStatusType]
            Defines if the Encounter is to be billed by Candid to the responsible_party. Examples for when this should be set to NOT_BILLABLE include if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        responsible_party : typing.Optional[ResponsiblePartyType]
            Defines the party to be billed with the initial balance owed on the claim. Use SELF_PAY if you intend to bill self pay/cash pay.

        provider_accepts_assignment : typing.Optional[bool]
            Whether you have accepted the patient's authorization for insurance payments to be made to you, not them. Box 27 on the CMS-1500 claim form.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter. Asynchronous encounters occur when providers and patients communicate online using forms, instant messaging, or other pre-recorded digital mediums. Synchronous encounters occur in live, real-time settings where the patient interacts directly with the provider, such as over video or a phone call.

        place_of_service_code : typing.Optional[FacilityTypeCode]
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If service lines have distinct end_date_of_service values, updating the encounter's end_date_of_service will fail. If all service line end_date_of_service values are the same, updating the encounter's end_date_of_service will update all service line date_of_service values.

        subscriber_primary : typing.Optional[SubscriberCreate]
            Contains details of the primary insurance subscriber.

        subscriber_secondary : typing.Optional[SubscriberCreate]
            Contains details of the secondary insurance subscriber.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.de

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

        patient : typing.Optional[PatientUpdate]
            Contains the identification information of the individual receiving medical services.

        patient_authorized_release : typing.Optional[bool]
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter. Updating schema instances utilizes PUT
            semantics, so the schema instances on the encounter will be set to whatever inputs are provided. If null
            is provided as an input, then the encounter's schema instances will be cleared.

        vitals : typing.Optional[VitalsUpdate]
            If a vitals entity already exists for the encounter, then all values will be updated to the provided values.
            Otherwise, a new vitals object will be created for the encounter.

        existing_medications : typing.Optional[typing.Sequence[Medication]]
            Existing medications that should be on the encounter.
            Note all current existing medications on encounter will be overridden with this list.

        rendering_provider : typing.Optional[RenderingProviderUpdate]
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.

        service_facility : typing.Optional[EncounterServiceFacilityUpdate]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.

        guarantor : typing.Optional[GuarantorUpdate]
            Personal and contact info for the guarantor of the patient responsibility.

        billing_provider : typing.Optional[BillingProviderUpdate]
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.

        supervising_provider : typing.Optional[SupervisingProviderUpdate]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.

        referring_provider : typing.Optional[ReferringProviderUpdate]
            The final provider who referred the services that were rendered.
            All physicians who order services or refer Medicare beneficiaries must
            report this data.

        initial_referring_provider : typing.Optional[InitialReferringProviderUpdate]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.

        referral_number : typing.Optional[str]
            Refers to REF\*9F on the 837p. Value cannot be greater than 50 characters.

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

        Returns
        -------
        Encounter

        Examples
        --------
        import uuid

        from candid import CandidApiClient
        from candid.resources.commons import FacilityTypeCode

        client = CandidApiClient(
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.encounters.v_4.update(
            encounter_id=uuid.UUID(
                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
            ),
            diagnosis_ids=[
                uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                )
            ],
            place_of_service_code_as_submitted=FacilityTypeCode.PHARMACY,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/encounters/v4/{jsonable_encoder(encounter_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "diagnosis_ids": diagnosis_ids,
                "place_of_service_code_as_submitted": place_of_service_code_as_submitted,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "prior_authorization_number": prior_authorization_number,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "tag_ids": tag_ids,
                "clinical_notes": clinical_notes,
                "pay_to_address": pay_to_address,
                "billable_status": billable_status,
                "responsible_party": responsible_party,
                "provider_accepts_assignment": provider_accepts_assignment,
                "synchronicity": synchronicity,
                "place_of_service_code": place_of_service_code,
                "appointment_type": appointment_type,
                "end_date_of_service": end_date_of_service,
                "subscriber_primary": subscriber_primary,
                "subscriber_secondary": subscriber_secondary,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
                "patient": patient,
                "patient_authorized_release": patient_authorized_release,
                "schema_instances": schema_instances,
                "vitals": vitals,
                "existing_medications": existing_medications,
                "rendering_provider": rendering_provider,
                "service_facility": service_facility,
                "guarantor": guarantor,
                "billing_provider": billing_provider,
                "supervising_provider": supervising_provider,
                "referring_provider": referring_provider,
                "initial_referring_provider": initial_referring_provider,
                "referral_number": referral_number,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "InvalidTagNamesError":
                raise InvalidTagNamesError(
                    typing.cast(
                        InvalidTagNamesErrorType,
                        parse_obj_as(
                            type_=InvalidTagNamesErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def get_all(
        self,
        *,
        limit: typing.Optional[int] = None,
        claim_status: typing.Optional[ClaimStatus] = None,
        sort: typing.Optional[EncounterSortOptions] = None,
        page_token: typing.Optional[PageToken] = None,
        date_of_service_min: typing.Optional[dt.date] = None,
        date_of_service_max: typing.Optional[dt.date] = None,
        primary_payer_names: typing.Optional[str] = None,
        search_term: typing.Optional[str] = None,
        external_id: typing.Optional[EncounterExternalId] = None,
        diagnoses_updated_since: typing.Optional[dt.datetime] = None,
        tag_ids: typing.Optional[typing.Union[TagId, typing.Sequence[TagId]]] = None,
        work_queue_id: typing.Optional[WorkQueueId] = None,
        billable_status: typing.Optional[BillableStatusType] = None,
        responsible_party: typing.Optional[ResponsiblePartyType] = None,
        owner_of_next_action: typing.Optional[EncounterOwnerOfNextActionType] = None,
        patient_external_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> EncounterPage:
        """
        Parameters
        ----------
        limit : typing.Optional[int]
            Maximum number of entities per page, defaults to 100.

        claim_status : typing.Optional[ClaimStatus]
            Indicates the current status of an insurance claim within the billing process.

        sort : typing.Optional[EncounterSortOptions]
            Defaults to created_at:desc.

        page_token : typing.Optional[PageToken]

        date_of_service_min : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.

        date_of_service_max : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.

        primary_payer_names : typing.Optional[str]
            Comma delimited string.

        search_term : typing.Optional[str]
            Filter by any of the following fields: encounter_id, claim_id, patient external_id,
            patient date of birth, patient first name, patient last name,
            or encounter external id.

        external_id : typing.Optional[EncounterExternalId]
            Filter to an exact match on encounter external_id, if one exists.

        diagnoses_updated_since : typing.Optional[dt.datetime]
            ISO 8601 timestamp; ideally in UTC (although not required): 2019-08-24T14:15:22Z.

        tag_ids : typing.Optional[typing.Union[TagId, typing.Sequence[TagId]]]
            Filter by name of tags on encounters.

        work_queue_id : typing.Optional[WorkQueueId]

        billable_status : typing.Optional[BillableStatusType]
            Defines if the Encounter is to be billed by Candid to the responsible_party. Examples for when this should be set to NOT_BILLABLE include if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        responsible_party : typing.Optional[ResponsiblePartyType]
            Defines the party to be billed with the initial balance owed on the claim. Use SELF_PAY if you intend to bill self pay/cash pay.

        owner_of_next_action : typing.Optional[EncounterOwnerOfNextActionType]
            The party who is responsible for taking the next action on an Encounter, as defined by ownership of open Tasks.

        patient_external_id : typing.Optional[str]
            The patient ID from the external EMR platform for the patient

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

        Returns
        -------
        EncounterPage

        Examples
        --------
        import asyncio
        import datetime

        from candid import AsyncCandidApiClient
        from candid.resources.claims import ClaimStatus
        from candid.resources.encounters.resources.v_4 import EncounterSortOptions

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


        async def main() -> None:
            await client.encounters.v_4.get_all(
                limit=100,
                claim_status=ClaimStatus.BILLER_RECEIVED,
                sort=EncounterSortOptions.CREATED_AT_ASC,
                page_token="eyJ0b2tlbiI6IjEiLCJwYWdlX3Rva2VuIjoiMiJ9",
                date_of_service_min=datetime.date.fromisoformat(
                    "2019-08-24",
                ),
                date_of_service_max=datetime.date.fromisoformat(
                    "2019-08-25",
                ),
                primary_payer_names="Medicare,Medicaid",
                search_term="doe",
                external_id="123456",
                diagnoses_updated_since=datetime.datetime.fromisoformat(
                    "2019-08-24 14:15:22+00:00",
                ),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/encounters/v4",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            params={
                "limit": limit,
                "claim_status": claim_status,
                "sort": sort,
                "page_token": page_token,
                "date_of_service_min": str(date_of_service_min) if date_of_service_min is not None else None,
                "date_of_service_max": str(date_of_service_max) if date_of_service_max is not None else None,
                "primary_payer_names": primary_payer_names,
                "search_term": search_term,
                "external_id": external_id,
                "diagnoses_updated_since": serialize_datetime(diagnoses_updated_since)
                if diagnoses_updated_since is not None
                else None,
                "tag_ids": tag_ids,
                "work_queue_id": work_queue_id,
                "billable_status": billable_status,
                "responsible_party": responsible_party,
                "owner_of_next_action": owner_of_next_action,
                "patient_external_id": patient_external_id,
            },
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                EncounterPage,
                parse_obj_as(
                    type_=EncounterPage,  # type: ignore
                    object_=_response_json,
                ),
            )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(
        self, encounter_id: EncounterId, *, request_options: typing.Optional[RequestOptions] = None
    ) -> Encounter:
        """
        Parameters
        ----------
        encounter_id : EncounterId

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

        Returns
        -------
        Encounter

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

        from candid import AsyncCandidApiClient

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


        async def main() -> None:
            await client.encounters.v_4.get(
                encounter_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/encounters/v4/{jsonable_encoder(encounter_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="GET",
            request_options=request_options,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        patient: PatientCreate,
        billing_provider: BillingProvider,
        rendering_provider: RenderingProvider,
        responsible_party: ResponsiblePartyType,
        diagnoses: typing.Sequence[DiagnosisCreate],
        place_of_service_code: FacilityTypeCode,
        external_id: EncounterExternalId,
        patient_authorized_release: bool,
        benefits_assigned_to_provider: bool,
        provider_accepts_assignment: bool,
        billable_status: BillableStatusType,
        referring_provider: typing.Optional[ReferringProvider] = OMIT,
        initial_referring_provider: typing.Optional[InitialReferringProvider] = OMIT,
        supervising_provider: typing.Optional[SupervisingProvider] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityBase] = OMIT,
        subscriber_primary: typing.Optional[SubscriberCreate] = OMIT,
        subscriber_secondary: typing.Optional[SubscriberCreate] = OMIT,
        prior_authorization_number: typing.Optional[PriorAuthorizationNumber] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        billing_notes: typing.Optional[typing.Sequence[BillingNoteBase]] = OMIT,
        patient_histories: typing.Optional[typing.Sequence[PatientHistoryCategory]] = OMIT,
        service_lines: typing.Optional[typing.Sequence[ServiceLineCreate]] = OMIT,
        guarantor: typing.Optional[GuarantorCreate] = OMIT,
        external_claim_submission: typing.Optional[ExternalClaimSubmissionCreate] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        referral_number: typing.Optional[str] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        vitals: typing.Optional[Vitals] = OMIT,
        interventions: typing.Optional[typing.Sequence[Intervention]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Parameters
        ----------
        patient : PatientCreate
            Contains the identification information of the individual receiving medical services.


        billing_provider : BillingProvider
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.


        rendering_provider : RenderingProvider
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.


        responsible_party : ResponsiblePartyType
            Defines the party to be billed with the initial balance owed on the claim.


        diagnoses : typing.Sequence[DiagnosisCreate]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code : FacilityTypeCode
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        external_id : EncounterExternalId
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        patient_authorized_release : bool
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        benefits_assigned_to_provider : bool
            Whether this patient has authorized insurance payments to be made to you,
            not them. If false, patient may receive reimbursement.
            Box 13 on the CMS-1500 claim form.

        provider_accepts_assignment : bool
            Whether you have accepted the patient's authorization for insurance payments
            to be made to you, not them.
            Box 27 on the CMS-1500 claim form.

        billable_status : BillableStatusType
            Defines if the Encounter is to be billed by Candid to the responsible_party.
            Examples for when this should be set to NOT_BILLABLE include
            if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        referring_provider : typing.Optional[ReferringProvider]
            The final provider who referred the services that were rendered.
            All physicians who order services or refer Medicare beneficiaries must
            report this data.


        initial_referring_provider : typing.Optional[InitialReferringProvider]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.


        supervising_provider : typing.Optional[SupervisingProvider]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.


        service_facility : typing.Optional[EncounterServiceFacilityBase]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.


        subscriber_primary : typing.Optional[SubscriberCreate]
            Subscriber_primary is required when responsible_party is INSURANCE_PAY (i.e. when the claim should be billed to insurance).
            These are not required fields when responsible_party is SELF_PAY (i.e. when the claim should be billed to the patient).
            However, if you collect this for patients, even self-pay, we recommend including it when sending encounters to Candid.
            Note: Cash Pay is no longer a valid payer_id in v4, please use responsible party to define self-pay claims.


        subscriber_secondary : typing.Optional[SubscriberCreate]
            Please always include this when you have it, even for self-pay claims.


        prior_authorization_number : typing.Optional[PriorAuthorizationNumber]
            Box 23 on the CMS-1500 claim form.

        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        billing_notes : typing.Optional[typing.Sequence[BillingNoteBase]]
            Spot to store misc, human-readable, notes about this encounter to be used
            in the billing process.


        patient_histories : typing.Optional[typing.Sequence[PatientHistoryCategory]]

        service_lines : typing.Optional[typing.Sequence[ServiceLineCreate]]
            Each service line must be linked to a diagnosis. Concretely,
            `service_line.diagnosis_pointers`must contain at least one entry which should be
            in bounds of the diagnoses list field.


        guarantor : typing.Optional[GuarantorCreate]
            Personal and contact info for the guarantor of the patient responsibility.


        external_claim_submission : typing.Optional[ExternalClaimSubmissionCreate]
            ***This field is in beta.***
            To be included for claims that have been submitted outside of Candid.
            Candid supports posting remits and payments to these claims and working them in-platform (e.g. editing, resubmitting).


        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter.


        referral_number : typing.Optional[str]
            Refers to REF*9F on the 837p. Value cannot be greater than 50 characters.


        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            date_of_service must be defined on either the encounter or the service lines but not both.
            If there are greater than zero service lines, it is recommended to specify date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If there are greater than zero service lines, it is recommended to specify end_date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        existing_medications : typing.Optional[typing.Sequence[Medication]]

        vitals : typing.Optional[Vitals]

        interventions : typing.Optional[typing.Sequence[Intervention]]

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter.
            Asynchronous encounters occur when providers and patients communicate online using
            forms, instant messaging, or other pre-recorded digital mediums.
            Synchronous encounters occur in live, real-time settings where the patient interacts
            directly with the provider, such as over video or a phone call.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

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

        Returns
        -------
        Encounter

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

        from candid import AsyncCandidApiClient
        from candid.resources.billing_notes.resources.v_2 import BillingNoteBase
        from candid.resources.claim_submission.resources.v_1 import (
            ClaimFrequencyTypeCode,
            ClaimSubmissionRecordCreate,
            ExternalClaimSubmissionCreate,
        )
        from candid.resources.commons import (
            BillingProviderCommercialLicenseType,
            ClaimSubmissionPayerResponsibilityType,
            DelayReasonCode,
            EmrPayerCrosswalk,
            FacilityTypeCode,
            InsuranceTypeCode,
            IntendedSubmissionMedium,
            PatientRelationshipToInsuredCodeAll,
            PhoneNumber,
            PhoneNumberType,
            ProcedureModifier,
            QualifierCode,
            ServiceLineUnits,
            SourceOfPaymentCode,
            State,
            StreetAddressLongZip,
            StreetAddressShortZip,
        )
        from candid.resources.custom_schemas.resources.v_1 import SchemaInstance
        from candid.resources.diagnoses import DiagnosisCreate, DiagnosisTypeCode
        from candid.resources.encounter_providers.resources.v_2 import (
            BillingProvider,
            InitialReferringProvider,
            OrderingProvider,
            ReferringProvider,
            RenderingProvider,
            SupervisingProvider,
        )
        from candid.resources.encounters.resources.v_4 import (
            BillableStatusType,
            ClinicalNote,
            ClinicalNoteCategoryCreate,
            IntakeFollowUp,
            IntakeQuestion,
            IntakeResponseAndFollowUps,
            Intervention,
            InterventionCategory,
            Lab,
            LabCodeType,
            Medication,
            NoteCategory,
            PatientHistoryCategory,
            PatientHistoryCategoryEnum,
            ResponsiblePartyType,
            ServiceAuthorizationExceptionCode,
            SynchronicityType,
            Vitals,
        )
        from candid.resources.guarantor.resources.v_1 import GuarantorCreate
        from candid.resources.individual import (
            Gender,
            PatientCreate,
            PatientNonInsurancePayerInfoCreate,
            SubscriberCreate,
        )
        from candid.resources.insurance_cards.resources.v_2 import InsuranceCardCreate
        from candid.resources.service_facility import EncounterServiceFacilityBase
        from candid.resources.service_lines.resources.v_2 import (
            DrugIdentification,
            MeasurementUnitCode,
            ServiceIdQualifier,
            ServiceLineCreate,
            TestResult,
            TestResultType,
        )

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


        async def main() -> None:
            await client.encounters.v_4.create(
                patient=PatientCreate(
                    phone_numbers=[
                        PhoneNumber(
                            number="1234567890",
                            type=PhoneNumberType.HOME,
                        )
                    ],
                    phone_consent=True,
                    email="johndoe@joincandidhealth.com",
                    non_insurance_payers=[
                        uuid.UUID(
                            "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                        )
                    ],
                    non_insurance_payers_info=[
                        PatientNonInsurancePayerInfoCreate(
                            non_insurance_payer_id=uuid.UUID(
                                "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                            ),
                            member_id="string",
                        )
                    ],
                    email_consent=True,
                    external_id="string",
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    address=StreetAddressShortZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    gender=Gender.MALE,
                ),
                billing_provider=BillingProvider(
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    tax_id="string",
                    npi="string",
                    taxonomy_code="string",
                    provider_commercial_license_type=BillingProviderCommercialLicenseType.LICENSED_CLINICAL_SOCIAL_WORKER,
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                rendering_provider=RenderingProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                referring_provider=ReferringProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                initial_referring_provider=InitialReferringProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    qualifier=QualifierCode.DQ,
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                supervising_provider=SupervisingProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                service_facility=EncounterServiceFacilityBase(
                    organization_name="string",
                    npi="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    secondary_identification="string",
                ),
                subscriber_primary=SubscriberCreate(
                    insurance_card=InsuranceCardCreate(
                        member_id="string",
                        payer_name="string",
                        payer_id="string",
                        rx_bin="string",
                        rx_pcn="string",
                        image_url_front="string",
                        image_url_back="string",
                        emr_payer_crosswalk=EmrPayerCrosswalk.HEALTHIE,
                        group_number="string",
                        plan_name="string",
                        plan_type=SourceOfPaymentCode.SELF_PAY,
                        insurance_type=InsuranceTypeCode.C_01,
                    ),
                    patient_relationship_to_subscriber_code=PatientRelationshipToInsuredCodeAll.SPOUSE,
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    address=StreetAddressShortZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    gender=Gender.MALE,
                ),
                subscriber_secondary=SubscriberCreate(
                    insurance_card=InsuranceCardCreate(
                        member_id="string",
                        payer_name="string",
                        payer_id="string",
                        rx_bin="string",
                        rx_pcn="string",
                        image_url_front="string",
                        image_url_back="string",
                        emr_payer_crosswalk=EmrPayerCrosswalk.HEALTHIE,
                        group_number="string",
                        plan_name="string",
                        plan_type=SourceOfPaymentCode.SELF_PAY,
                        insurance_type=InsuranceTypeCode.C_01,
                    ),
                    patient_relationship_to_subscriber_code=PatientRelationshipToInsuredCodeAll.SPOUSE,
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    address=StreetAddressShortZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    gender=Gender.MALE,
                ),
                prior_authorization_number="string",
                responsible_party=ResponsiblePartyType.INSURANCE_PAY,
                diagnoses=[
                    DiagnosisCreate(
                        name="string",
                        code_type=DiagnosisTypeCode.ABF,
                        code="string",
                    )
                ],
                clinical_notes=[
                    ClinicalNoteCategoryCreate(
                        category=NoteCategory.CLINICAL,
                        notes=[
                            ClinicalNote(
                                text="string",
                                author_name="string",
                                author_npi="string",
                                timestamp=datetime.datetime.fromisoformat(
                                    "2024-01-15 09:30:00+00:00",
                                ),
                            )
                        ],
                    )
                ],
                billing_notes=[
                    BillingNoteBase(
                        text="string",
                    )
                ],
                place_of_service_code=FacilityTypeCode.PHARMACY,
                patient_histories=[
                    PatientHistoryCategory(
                        category=PatientHistoryCategoryEnum.PRESENT_ILLNESS,
                        questions=[
                            IntakeQuestion(
                                id="6E7FBCE4-A8EA-46D0-A8D8-FF83CA3BB176",
                                text="Do you have any allergies?",
                                responses=[
                                    IntakeResponseAndFollowUps(
                                        response="No allergies",
                                        follow_ups=[
                                            IntakeFollowUp(
                                                id="4F3D57F9-AC94-49D6-87E4-E804B709917A",
                                                text="Do you have any allergies?",
                                                response="No allergies",
                                            )
                                        ],
                                    )
                                ],
                            )
                        ],
                    )
                ],
                service_lines=[
                    ServiceLineCreate(
                        modifiers=[ProcedureModifier.TWENTY_TWO],
                        procedure_code="string",
                        quantity="string",
                        units=ServiceLineUnits.MJ,
                        charge_amount_cents=1,
                        diagnosis_pointers=[1],
                        drug_identification=DrugIdentification(
                            service_id_qualifier=ServiceIdQualifier.EAN_UCC_13,
                            national_drug_code="string",
                            national_drug_unit_count="string",
                            measurement_unit_code=MeasurementUnitCode.MILLILITERS,
                            link_sequence_number="string",
                            pharmacy_prescription_number="string",
                            conversion_formula="string",
                            drug_description="string",
                        ),
                        place_of_service_code=FacilityTypeCode.PHARMACY,
                        description="string",
                        date_of_service=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        end_date_of_service=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        ordering_provider=OrderingProvider(
                            npi="string",
                            taxonomy_code="string",
                            address=StreetAddressLongZip(
                                address_1="123 Main St",
                                address_2="Apt 1",
                                city="New York",
                                state=State.NY,
                                zip_code="10001",
                                zip_plus_four_code="1234",
                            ),
                            first_name="string",
                            last_name="string",
                            organization_name="string",
                        ),
                        test_results=[
                            TestResult(
                                value=1.1,
                                result_type=TestResultType.HEMATOCRIT,
                            )
                        ],
                    )
                ],
                guarantor=GuarantorCreate(
                    phone_numbers=[
                        PhoneNumber(
                            number="1234567890",
                            type=PhoneNumberType.HOME,
                        )
                    ],
                    phone_consent=True,
                    email="johndoe@joincandidhealth.com",
                    email_consent=True,
                    first_name="string",
                    last_name="string",
                    external_id="string",
                    date_of_birth=datetime.date.fromisoformat(
                        "2023-01-15",
                    ),
                    address=StreetAddressShortZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                ),
                external_claim_submission=ExternalClaimSubmissionCreate(
                    claim_created_at=datetime.datetime.fromisoformat(
                        "2023-01-01 12:00:00+00:00",
                    ),
                    patient_control_number="PATIENT_CONTROL_NUMBER",
                    submission_records=[
                        ClaimSubmissionRecordCreate(
                            submitted_at=datetime.datetime.fromisoformat(
                                "2023-01-01 13:00:00+00:00",
                            ),
                            claim_frequency_code=ClaimFrequencyTypeCode.ORIGINAL,
                            payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                            intended_submission_medium=IntendedSubmissionMedium.ELECTRONIC,
                        ),
                        ClaimSubmissionRecordCreate(
                            submitted_at=datetime.datetime.fromisoformat(
                                "2023-01-04 12:00:00+00:00",
                            ),
                            claim_frequency_code=ClaimFrequencyTypeCode.REPLACEMENT,
                            payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                            intended_submission_medium=IntendedSubmissionMedium.PAPER,
                        ),
                    ],
                ),
                tag_ids=["string"],
                schema_instances=[
                    SchemaInstance(
                        schema_id=uuid.UUID(
                            "ec096b13-f80a-471d-aaeb-54b021c9d582",
                        ),
                        content={
                            "provider_category": "internist",
                            "is_urgent_care": True,
                            "bmi": 24.2,
                            "age": 38,
                        },
                    )
                ],
                referral_number="string",
                external_id="string",
                date_of_service=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                end_date_of_service=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                patient_authorized_release=True,
                benefits_assigned_to_provider=True,
                provider_accepts_assignment=True,
                appointment_type="string",
                existing_medications=[
                    Medication(
                        name="Lisinopril",
                        rx_cui="860975",
                        dosage="10mg",
                        dosage_form="Tablet",
                        frequency="Once Daily",
                        as_needed=True,
                    )
                ],
                vitals=Vitals(
                    height_in=70,
                    weight_lbs=165,
                    blood_pressure_systolic_mmhg=115,
                    blood_pressure_diastolic_mmhg=85,
                    body_temperature_f=98.0,
                    hemoglobin_gdl=15.1,
                    hematocrit_pct=51.2,
                ),
                interventions=[
                    Intervention(
                        name="Physical Therapy Session",
                        category=InterventionCategory.LIFESTYLE,
                        description="A session focused on improving muscular strength, flexibility, and range of motion post-injury.",
                        medication=Medication(
                            name="Lisinopril",
                            rx_cui="860975",
                            dosage="10mg",
                            dosage_form="Tablet",
                            frequency="Once Daily",
                            as_needed=True,
                        ),
                        labs=[
                            Lab(
                                name="Genetic Health Labs",
                                code="GH12345",
                                code_type=LabCodeType.QUEST,
                            )
                        ],
                    )
                ],
                pay_to_address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                synchronicity=SynchronicityType.SYNCHRONOUS,
                billable_status=BillableStatusType.BILLABLE,
                additional_information="string",
                service_authorization_exception_code=ServiceAuthorizationExceptionCode.C_1,
                admission_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                discharge_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                onset_of_current_illness_or_symptom_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                last_menstrual_period_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                delay_reason_code=DelayReasonCode.C_1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/encounters/v4",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "patient": patient,
                "billing_provider": billing_provider,
                "rendering_provider": rendering_provider,
                "referring_provider": referring_provider,
                "initial_referring_provider": initial_referring_provider,
                "supervising_provider": supervising_provider,
                "service_facility": service_facility,
                "subscriber_primary": subscriber_primary,
                "subscriber_secondary": subscriber_secondary,
                "prior_authorization_number": prior_authorization_number,
                "responsible_party": responsible_party,
                "diagnoses": diagnoses,
                "clinical_notes": clinical_notes,
                "billing_notes": billing_notes,
                "place_of_service_code": place_of_service_code,
                "patient_histories": patient_histories,
                "service_lines": service_lines,
                "guarantor": guarantor,
                "external_claim_submission": external_claim_submission,
                "tag_ids": tag_ids,
                "schema_instances": schema_instances,
                "referral_number": referral_number,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "end_date_of_service": end_date_of_service,
                "patient_authorized_release": patient_authorized_release,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "provider_accepts_assignment": provider_accepts_assignment,
                "appointment_type": appointment_type,
                "existing_medications": existing_medications,
                "vitals": vitals,
                "interventions": interventions,
                "pay_to_address": pay_to_address,
                "synchronicity": synchronicity,
                "billable_status": billable_status,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterPatientControlNumberUniquenessError":
                raise EncounterPatientControlNumberUniquenessError(
                    typing.cast(
                        EncounterPatientControlNumberUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterPatientControlNumberUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterGuarantorMissingContactInfoError":
                raise EncounterGuarantorMissingContactInfoError(
                    typing.cast(
                        EncounterGuarantorMissingContactInfoErrorType,
                        parse_obj_as(
                            type_=EncounterGuarantorMissingContactInfoErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "CashPayPayerError":
                raise CashPayPayerError(
                    typing.cast(
                        CashPayPayerErrorMessage,
                        parse_obj_as(
                            type_=CashPayPayerErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "InvalidTagNamesError":
                raise InvalidTagNamesError(
                    typing.cast(
                        InvalidTagNamesErrorType,
                        parse_obj_as(
                            type_=InvalidTagNamesErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationError":
                raise HttpRequestValidationError(
                    typing.cast(
                        RequestValidationError,
                        parse_obj_as(
                            type_=RequestValidationError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create_from_pre_encounter_patient(
        self,
        *,
        pre_encounter_patient_id: PreEncounterPatientId,
        pre_encounter_appointment_ids: typing.Sequence[PreEncounterAppointmentId],
        billing_provider: BillingProvider,
        rendering_provider: RenderingProvider,
        diagnoses: typing.Sequence[DiagnosisCreate],
        place_of_service_code: FacilityTypeCode,
        external_id: EncounterExternalId,
        patient_authorized_release: bool,
        benefits_assigned_to_provider: bool,
        provider_accepts_assignment: bool,
        billable_status: BillableStatusType,
        initial_referring_provider: typing.Optional[InitialReferringProvider] = OMIT,
        supervising_provider: typing.Optional[SupervisingProvider] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityBase] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        billing_notes: typing.Optional[typing.Sequence[BillingNoteBase]] = OMIT,
        patient_histories: typing.Optional[typing.Sequence[PatientHistoryCategory]] = OMIT,
        service_lines: typing.Optional[typing.Sequence[ServiceLineCreate]] = OMIT,
        external_claim_submission: typing.Optional[ExternalClaimSubmissionCreate] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        vitals: typing.Optional[Vitals] = OMIT,
        interventions: typing.Optional[typing.Sequence[Intervention]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Create an encounter from a pre-encounter patient and appointment. This endpoint is intended to be used by consumers who are managing
        patients and appointments in the pre-encounter service and is currently under development. Consumers who are not taking advantage
        of the pre-encounter service should use the standard create endpoint.

        The endpoint will create an encounter from the provided fields, pulling information from the provided patient and appointment objects
        where applicable. In particular, the following fields are populated from the patient and appointment objects:

        - Patient
        - Referring Provider
        - Subscriber Primary
        - Subscriber Secondary
        - Referral Number
        - Responsible Party
        - Guarantor

        Utilizing this endpoint opts you into automatic updating of the encounter when the patient or appointment is updated, assuming the
        encounter has not already been submitted or adjudicated.

        Parameters
        ----------
        pre_encounter_patient_id : PreEncounterPatientId

        pre_encounter_appointment_ids : typing.Sequence[PreEncounterAppointmentId]

        billing_provider : BillingProvider
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.


        rendering_provider : RenderingProvider
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.


        diagnoses : typing.Sequence[DiagnosisCreate]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code : FacilityTypeCode
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms .gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        external_id : EncounterExternalId
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        patient_authorized_release : bool
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        benefits_assigned_to_provider : bool
            Whether this patient has authorized insurance payments to be made to you,
            not them. If false, patient may receive reimbursement.
            Box 13 on the CMS-1500 claim form.

        provider_accepts_assignment : bool
            Whether you have accepted the patient's authorization for insurance payments
            to be made to you, not them.
            Box 27 on the CMS-1500 claim form.

        billable_status : BillableStatusType
            Defines if the Encounter is to be billed by Candid to the responsible_party.
            Examples for when this should be set to NOT_BILLABLE include
            if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        initial_referring_provider : typing.Optional[InitialReferringProvider]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.


        supervising_provider : typing.Optional[SupervisingProvider]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.


        service_facility : typing.Optional[EncounterServiceFacilityBase]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.


        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        billing_notes : typing.Optional[typing.Sequence[BillingNoteBase]]
            Spot to store misc, human-readable, notes about this encounter to be used
            in the billing process.


        patient_histories : typing.Optional[typing.Sequence[PatientHistoryCategory]]

        service_lines : typing.Optional[typing.Sequence[ServiceLineCreate]]
            Each service line must be linked to a diagnosis. Concretely,
            `service_line.diagnosis_pointers`must contain at least one entry which should be
            in bounds of the diagnoses list field.


        external_claim_submission : typing.Optional[ExternalClaimSubmissionCreate]
            ***This field is in beta.***
            To be included for claims that have been submitted outside of Candid.
            Candid supports posting remits and payments to these claims and working them in-platform (e.g. editing, resubmitting).


        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter.


        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            date_of_service must be defined on either the encounter or the service lines but not both.
            If there are greater than zero service lines, it is recommended to specify date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If there are greater than zero service lines, it is recommended to specify end_date_of_service on the service_line instead of on the encounter to prepare for future API versions.

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        existing_medications : typing.Optional[typing.Sequence[Medication]]

        vitals : typing.Optional[Vitals]

        interventions : typing.Optional[typing.Sequence[Intervention]]

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter.
            Asynchronous encounters occur when providers and patients communicate online using
            forms, instant messaging, or other pre-recorded digital mediums.
            Synchronous encounters occur in live, real-time settings where the patient interacts
            directly with the provider, such as over video or a phone call.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

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

        Returns
        -------
        Encounter

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

        from candid import AsyncCandidApiClient
        from candid.resources.billing_notes.resources.v_2 import BillingNoteBase
        from candid.resources.claim_submission.resources.v_1 import (
            ClaimFrequencyTypeCode,
            ClaimSubmissionRecordCreate,
            ExternalClaimSubmissionCreate,
        )
        from candid.resources.commons import (
            BillingProviderCommercialLicenseType,
            ClaimSubmissionPayerResponsibilityType,
            DelayReasonCode,
            FacilityTypeCode,
            IntendedSubmissionMedium,
            ProcedureModifier,
            QualifierCode,
            ServiceLineUnits,
            State,
            StreetAddressLongZip,
        )
        from candid.resources.custom_schemas.resources.v_1 import SchemaInstance
        from candid.resources.diagnoses import DiagnosisCreate, DiagnosisTypeCode
        from candid.resources.encounter_providers.resources.v_2 import (
            BillingProvider,
            InitialReferringProvider,
            OrderingProvider,
            RenderingProvider,
            SupervisingProvider,
        )
        from candid.resources.encounters.resources.v_4 import (
            BillableStatusType,
            ClinicalNote,
            ClinicalNoteCategoryCreate,
            IntakeFollowUp,
            IntakeQuestion,
            IntakeResponseAndFollowUps,
            Intervention,
            InterventionCategory,
            Lab,
            LabCodeType,
            Medication,
            NoteCategory,
            PatientHistoryCategory,
            PatientHistoryCategoryEnum,
            ServiceAuthorizationExceptionCode,
            SynchronicityType,
            Vitals,
        )
        from candid.resources.service_facility import EncounterServiceFacilityBase
        from candid.resources.service_lines.resources.v_2 import (
            DrugIdentification,
            MeasurementUnitCode,
            ServiceIdQualifier,
            ServiceLineCreate,
            TestResult,
            TestResultType,
        )

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


        async def main() -> None:
            await client.encounters.v_4.create_from_pre_encounter_patient(
                pre_encounter_patient_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
                pre_encounter_appointment_ids=[
                    uuid.UUID(
                        "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                    )
                ],
                billing_provider=BillingProvider(
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    tax_id="string",
                    npi="string",
                    taxonomy_code="string",
                    provider_commercial_license_type=BillingProviderCommercialLicenseType.LICENSED_CLINICAL_SOCIAL_WORKER,
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                rendering_provider=RenderingProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                initial_referring_provider=InitialReferringProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    qualifier=QualifierCode.DQ,
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                supervising_provider=SupervisingProvider(
                    npi="string",
                    taxonomy_code="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    first_name="string",
                    last_name="string",
                    organization_name="string",
                ),
                service_facility=EncounterServiceFacilityBase(
                    organization_name="string",
                    npi="string",
                    address=StreetAddressLongZip(
                        address_1="123 Main St",
                        address_2="Apt 1",
                        city="New York",
                        state=State.NY,
                        zip_code="10001",
                        zip_plus_four_code="1234",
                    ),
                    secondary_identification="string",
                ),
                diagnoses=[
                    DiagnosisCreate(
                        name="string",
                        code_type=DiagnosisTypeCode.ABF,
                        code="string",
                    )
                ],
                clinical_notes=[
                    ClinicalNoteCategoryCreate(
                        category=NoteCategory.CLINICAL,
                        notes=[
                            ClinicalNote(
                                text="string",
                                author_name="string",
                                author_npi="string",
                                timestamp=datetime.datetime.fromisoformat(
                                    "2024-01-15 09:30:00+00:00",
                                ),
                            )
                        ],
                    )
                ],
                billing_notes=[
                    BillingNoteBase(
                        text="string",
                    )
                ],
                place_of_service_code=FacilityTypeCode.PHARMACY,
                patient_histories=[
                    PatientHistoryCategory(
                        category=PatientHistoryCategoryEnum.PRESENT_ILLNESS,
                        questions=[
                            IntakeQuestion(
                                id="6E7FBCE4-A8EA-46D0-A8D8-FF83CA3BB176",
                                text="Do you have any allergies?",
                                responses=[
                                    IntakeResponseAndFollowUps(
                                        response="No allergies",
                                        follow_ups=[
                                            IntakeFollowUp(
                                                id="4F3D57F9-AC94-49D6-87E4-E804B709917A",
                                                text="Do you have any allergies?",
                                                response="No allergies",
                                            )
                                        ],
                                    )
                                ],
                            )
                        ],
                    )
                ],
                service_lines=[
                    ServiceLineCreate(
                        modifiers=[ProcedureModifier.TWENTY_TWO],
                        procedure_code="string",
                        quantity="string",
                        units=ServiceLineUnits.MJ,
                        charge_amount_cents=1,
                        diagnosis_pointers=[1],
                        drug_identification=DrugIdentification(
                            service_id_qualifier=ServiceIdQualifier.EAN_UCC_13,
                            national_drug_code="string",
                            national_drug_unit_count="string",
                            measurement_unit_code=MeasurementUnitCode.MILLILITERS,
                            link_sequence_number="string",
                            pharmacy_prescription_number="string",
                            conversion_formula="string",
                            drug_description="string",
                        ),
                        place_of_service_code=FacilityTypeCode.PHARMACY,
                        description="string",
                        date_of_service=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        end_date_of_service=datetime.date.fromisoformat(
                            "2023-01-15",
                        ),
                        ordering_provider=OrderingProvider(
                            npi="string",
                            taxonomy_code="string",
                            address=StreetAddressLongZip(
                                address_1="123 Main St",
                                address_2="Apt 1",
                                city="New York",
                                state=State.NY,
                                zip_code="10001",
                                zip_plus_four_code="1234",
                            ),
                            first_name="string",
                            last_name="string",
                            organization_name="string",
                        ),
                        test_results=[
                            TestResult(
                                value=1.1,
                                result_type=TestResultType.HEMATOCRIT,
                            )
                        ],
                    )
                ],
                external_claim_submission=ExternalClaimSubmissionCreate(
                    claim_created_at=datetime.datetime.fromisoformat(
                        "2023-01-01 12:00:00+00:00",
                    ),
                    patient_control_number="PATIENT_CONTROL_NUMBER",
                    submission_records=[
                        ClaimSubmissionRecordCreate(
                            submitted_at=datetime.datetime.fromisoformat(
                                "2023-01-01 13:00:00+00:00",
                            ),
                            claim_frequency_code=ClaimFrequencyTypeCode.ORIGINAL,
                            payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                            intended_submission_medium=IntendedSubmissionMedium.ELECTRONIC,
                        ),
                        ClaimSubmissionRecordCreate(
                            submitted_at=datetime.datetime.fromisoformat(
                                "2023-01-04 12:00:00+00:00",
                            ),
                            claim_frequency_code=ClaimFrequencyTypeCode.REPLACEMENT,
                            payer_responsibility=ClaimSubmissionPayerResponsibilityType.PRIMARY,
                            intended_submission_medium=IntendedSubmissionMedium.PAPER,
                        ),
                    ],
                ),
                tag_ids=["string"],
                schema_instances=[
                    SchemaInstance(
                        schema_id=uuid.UUID(
                            "ec096b13-f80a-471d-aaeb-54b021c9d582",
                        ),
                        content={
                            "provider_category": "internist",
                            "is_urgent_care": True,
                            "bmi": 24.2,
                            "age": 38,
                        },
                    )
                ],
                external_id="string",
                date_of_service=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                end_date_of_service=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                patient_authorized_release=True,
                benefits_assigned_to_provider=True,
                provider_accepts_assignment=True,
                appointment_type="string",
                existing_medications=[
                    Medication(
                        name="Lisinopril",
                        rx_cui="860975",
                        dosage="10mg",
                        dosage_form="Tablet",
                        frequency="Once Daily",
                        as_needed=True,
                    )
                ],
                vitals=Vitals(
                    height_in=70,
                    weight_lbs=165,
                    blood_pressure_systolic_mmhg=115,
                    blood_pressure_diastolic_mmhg=85,
                    body_temperature_f=98.0,
                    hemoglobin_gdl=15.1,
                    hematocrit_pct=51.2,
                ),
                interventions=[
                    Intervention(
                        name="Physical Therapy Session",
                        category=InterventionCategory.LIFESTYLE,
                        description="A session focused on improving muscular strength, flexibility, and range of motion post-injury.",
                        medication=Medication(
                            name="Lisinopril",
                            rx_cui="860975",
                            dosage="10mg",
                            dosage_form="Tablet",
                            frequency="Once Daily",
                            as_needed=True,
                        ),
                        labs=[
                            Lab(
                                name="Genetic Health Labs",
                                code="GH12345",
                                code_type=LabCodeType.QUEST,
                            )
                        ],
                    )
                ],
                pay_to_address=StreetAddressLongZip(
                    address_1="123 Main St",
                    address_2="Apt 1",
                    city="New York",
                    state=State.NY,
                    zip_code="10001",
                    zip_plus_four_code="1234",
                ),
                synchronicity=SynchronicityType.SYNCHRONOUS,
                billable_status=BillableStatusType.BILLABLE,
                additional_information="string",
                service_authorization_exception_code=ServiceAuthorizationExceptionCode.C_1,
                admission_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                discharge_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                onset_of_current_illness_or_symptom_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                last_menstrual_period_date=datetime.date.fromisoformat(
                    "2023-01-15",
                ),
                delay_reason_code=DelayReasonCode.C_1,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/encounters/v4/create-from-pre-encounter",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="POST",
            json={
                "pre_encounter_patient_id": pre_encounter_patient_id,
                "pre_encounter_appointment_ids": pre_encounter_appointment_ids,
                "billing_provider": billing_provider,
                "rendering_provider": rendering_provider,
                "initial_referring_provider": initial_referring_provider,
                "supervising_provider": supervising_provider,
                "service_facility": service_facility,
                "diagnoses": diagnoses,
                "clinical_notes": clinical_notes,
                "billing_notes": billing_notes,
                "place_of_service_code": place_of_service_code,
                "patient_histories": patient_histories,
                "service_lines": service_lines,
                "external_claim_submission": external_claim_submission,
                "tag_ids": tag_ids,
                "schema_instances": schema_instances,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "end_date_of_service": end_date_of_service,
                "patient_authorized_release": patient_authorized_release,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "provider_accepts_assignment": provider_accepts_assignment,
                "appointment_type": appointment_type,
                "existing_medications": existing_medications,
                "vitals": vitals,
                "interventions": interventions,
                "pay_to_address": pay_to_address,
                "synchronicity": synchronicity,
                "billable_status": billable_status,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EncounterPatientControlNumberUniquenessError":
                raise EncounterPatientControlNumberUniquenessError(
                    typing.cast(
                        EncounterPatientControlNumberUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterPatientControlNumberUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationError":
                raise HttpRequestValidationError(
                    typing.cast(
                        RequestValidationError,
                        parse_obj_as(
                            type_=RequestValidationError,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        encounter_id: EncounterId,
        *,
        diagnosis_ids: typing.Optional[typing.Sequence[DiagnosisId]] = OMIT,
        place_of_service_code_as_submitted: typing.Optional[FacilityTypeCode] = OMIT,
        benefits_assigned_to_provider: typing.Optional[bool] = OMIT,
        prior_authorization_number: typing.Optional[PriorAuthorizationNumber] = OMIT,
        external_id: typing.Optional[EncounterExternalId] = OMIT,
        date_of_service: typing.Optional[dt.date] = OMIT,
        tag_ids: typing.Optional[typing.Sequence[TagId]] = OMIT,
        clinical_notes: typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]] = OMIT,
        pay_to_address: typing.Optional[StreetAddressLongZip] = OMIT,
        billable_status: typing.Optional[BillableStatusType] = OMIT,
        responsible_party: typing.Optional[ResponsiblePartyType] = OMIT,
        provider_accepts_assignment: typing.Optional[bool] = OMIT,
        synchronicity: typing.Optional[SynchronicityType] = OMIT,
        place_of_service_code: typing.Optional[FacilityTypeCode] = OMIT,
        appointment_type: typing.Optional[str] = OMIT,
        end_date_of_service: typing.Optional[dt.date] = OMIT,
        subscriber_primary: typing.Optional[SubscriberCreate] = OMIT,
        subscriber_secondary: typing.Optional[SubscriberCreate] = OMIT,
        additional_information: typing.Optional[str] = OMIT,
        service_authorization_exception_code: typing.Optional[ServiceAuthorizationExceptionCode] = OMIT,
        admission_date: typing.Optional[dt.date] = OMIT,
        discharge_date: typing.Optional[dt.date] = OMIT,
        onset_of_current_illness_or_symptom_date: typing.Optional[dt.date] = OMIT,
        last_menstrual_period_date: typing.Optional[dt.date] = OMIT,
        delay_reason_code: typing.Optional[DelayReasonCode] = OMIT,
        patient: typing.Optional[PatientUpdate] = OMIT,
        patient_authorized_release: typing.Optional[bool] = OMIT,
        schema_instances: typing.Optional[typing.Sequence[SchemaInstance]] = OMIT,
        vitals: typing.Optional[VitalsUpdate] = OMIT,
        existing_medications: typing.Optional[typing.Sequence[Medication]] = OMIT,
        rendering_provider: typing.Optional[RenderingProviderUpdate] = OMIT,
        service_facility: typing.Optional[EncounterServiceFacilityUpdate] = OMIT,
        guarantor: typing.Optional[GuarantorUpdate] = OMIT,
        billing_provider: typing.Optional[BillingProviderUpdate] = OMIT,
        supervising_provider: typing.Optional[SupervisingProviderUpdate] = OMIT,
        referring_provider: typing.Optional[ReferringProviderUpdate] = OMIT,
        initial_referring_provider: typing.Optional[InitialReferringProviderUpdate] = OMIT,
        referral_number: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Encounter:
        """
        Parameters
        ----------
        encounter_id : EncounterId

        diagnosis_ids : typing.Optional[typing.Sequence[DiagnosisId]]
            Ideally, this field should contain no more than 12 diagnoses. However, more diagnoses
            may be submitted at this time, and coders will later prioritize the 12 that will be
            submitted to the payor.


        place_of_service_code_as_submitted : typing.Optional[FacilityTypeCode]
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).


        benefits_assigned_to_provider : typing.Optional[bool]
            Whether this patient has authorized insurance payments to be made to you, not them. If false, patient may receive reimbursement. Box 13 on the CMS-1500 claim form.

        prior_authorization_number : typing.Optional[PriorAuthorizationNumber]
            Box 23 on the CMS-1500 claim form.

        external_id : typing.Optional[EncounterExternalId]
            A client-specified unique ID to associate with this encounter;
            for example, your internal encounter ID or a Dr. Chrono encounter ID.
            This field should not contain PHI.

        date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-24.
            This date must be the local date in the timezone where the service occurred.
            Box 24a on the CMS-1500 claim form.
            If service occurred over a range of dates, this should be the start date.
            If service lines have distinct date_of_service values, updating the encounter's date_of_service will fail. If all service line date_of_service values are the same, updating the encounter's date_of_service will update all service line date_of_service values.

        tag_ids : typing.Optional[typing.Sequence[TagId]]
            Names of tags that should be on the encounter. Note all tags on encounter will be overridden with this list.

        clinical_notes : typing.Optional[typing.Sequence[ClinicalNoteCategoryCreate]]
            Holds a collection of clinical observations made by healthcare providers during patient encounters.

        pay_to_address : typing.Optional[StreetAddressLongZip]
            Specifies the address to which payments for the claim should be sent.

        billable_status : typing.Optional[BillableStatusType]
            Defines if the Encounter is to be billed by Candid to the responsible_party. Examples for when this should be set to NOT_BILLABLE include if the Encounter has not occurred yet or if there is no intention of ever billing the responsible_party.

        responsible_party : typing.Optional[ResponsiblePartyType]
            Defines the party to be billed with the initial balance owed on the claim. Use SELF_PAY if you intend to bill self pay/cash pay.

        provider_accepts_assignment : typing.Optional[bool]
            Whether you have accepted the patient's authorization for insurance payments to be made to you, not them. Box 27 on the CMS-1500 claim form.

        synchronicity : typing.Optional[SynchronicityType]
            Whether or not this was a synchronous or asynchronous encounter. Asynchronous encounters occur when providers and patients communicate online using forms, instant messaging, or other pre-recorded digital mediums. Synchronous encounters occur in live, real-time settings where the patient interacts directly with the provider, such as over video or a phone call.

        place_of_service_code : typing.Optional[FacilityTypeCode]
            Box 24B on the CMS-1500 claim form. 837p Loop2300, CLM-05-1. 02 for telemedicine, 11 for in-person. Full list [here](https://www.cms.gov/Medicare/Coding/place-of-service-codes/Place_of_Service_Code_Set).

        appointment_type : typing.Optional[str]
            Human-readable description of the appointment type (ex: "Acupuncture - Headaches").

        end_date_of_service : typing.Optional[dt.date]
            Date formatted as YYYY-MM-DD; eg: 2019-08-25.
            This date must be the local date in the timezone where the service occurred.
            If omitted, the Encounter is assumed to be for a single day.
            Must not be temporally before the date_of_service field.
            If service lines have distinct end_date_of_service values, updating the encounter's end_date_of_service will fail. If all service line end_date_of_service values are the same, updating the encounter's end_date_of_service will update all service line date_of_service values.

        subscriber_primary : typing.Optional[SubscriberCreate]
            Contains details of the primary insurance subscriber.

        subscriber_secondary : typing.Optional[SubscriberCreate]
            Contains details of the secondary insurance subscriber.

        additional_information : typing.Optional[str]
            Defines additional information on the claim needed by the payer.
            Box 19 on the CMS-1500 claim form.

        service_authorization_exception_code : typing.Optional[ServiceAuthorizationExceptionCode]
            837p Loop2300 REF\*4N
            Required when mandated by government law or regulation to obtain authorization for specific service(s) but, for the
            reasons listed in one of the enum values of ServiceAuthorizationExceptionCode, the service was performed without
            obtaining the authorization.

        admission_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*435, CMS-1500 Box 18
            Required on all ambulance claims when the patient was known to be admitted to the hospital.
            OR
            Required on all claims involving inpatient medical visits.

        discharge_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*096, CMS-1500 Box 18
            Required for inpatient claims when the patient was discharged from the facility and the discharge date is known.

        onset_of_current_illness_or_symptom_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*431, CMS-1500 Box 14
            Required for the initial medical service or visit performed in response to a medical emergency when the date is available and is different than the date of service.
            OR
            This date is the onset of acute symptoms for the current illness or condition.

        last_menstrual_period_date : typing.Optional[dt.date]
            837p Loop2300 DTP\*484, CMS-1500 Box 14
            Required when, in the judgment of the provider, the services on this claim are related to the patient's pregnancy.de

        delay_reason_code : typing.Optional[DelayReasonCode]
            837i Loop2300, CLM-1300 Box 20
            Code indicating the reason why a request was delayed

        patient : typing.Optional[PatientUpdate]
            Contains the identification information of the individual receiving medical services.

        patient_authorized_release : typing.Optional[bool]
            Whether this patient has authorized the release of medical information
            for billing purpose.
            Box 12 on the CMS-1500 claim form.

        schema_instances : typing.Optional[typing.Sequence[SchemaInstance]]
            Key-value pairs that must adhere to a schema created via the Custom Schema API. Multiple schema
            instances cannot be created for the same schema on an encounter. Updating schema instances utilizes PUT
            semantics, so the schema instances on the encounter will be set to whatever inputs are provided. If null
            is provided as an input, then the encounter's schema instances will be cleared.

        vitals : typing.Optional[VitalsUpdate]
            If a vitals entity already exists for the encounter, then all values will be updated to the provided values.
            Otherwise, a new vitals object will be created for the encounter.

        existing_medications : typing.Optional[typing.Sequence[Medication]]
            Existing medications that should be on the encounter.
            Note all current existing medications on encounter will be overridden with this list.

        rendering_provider : typing.Optional[RenderingProviderUpdate]
            The rendering provider is the practitioner -- physician, nurse practitioner, etc. -- performing the service.
            For telehealth services, the rendering provider performs the visit, asynchronous communication, or other service. The rendering provider address should generally be the same as the service facility address.

        service_facility : typing.Optional[EncounterServiceFacilityUpdate]
            Encounter Service facility is typically the location a medical service was rendered, such as a provider office or hospital. For telehealth, service facility can represent the provider's location when the service was delivered (e.g., home), or the location where an in-person visit would have taken place, whichever is easier to identify. If the provider is in-network, service facility may be defined in payer contracts. Box 32 on the CMS-1500 claim form. Note that for an in-network claim to be successfully adjudicated, the service facility address listed on claims must match what was provided to the payer during the credentialing process.

        guarantor : typing.Optional[GuarantorUpdate]
            Personal and contact info for the guarantor of the patient responsibility.

        billing_provider : typing.Optional[BillingProviderUpdate]
            The billing provider is the provider or business entity submitting the claim. Billing provider may be, but is not necessarily, the same person/NPI as the rendering provider. From a payer's perspective, this represents the person or entity being reimbursed. When a contract exists with the target payer, the billing provider should be the entity contracted with the payer. In some circumstances, this will be an individual provider. In that case, submit that provider's NPI and the tax ID (TIN) that the provider gave to the payer during contracting. In other cases, the billing entity will be a medical group. If so, submit the group NPI and the group's tax ID. Box 33 on the CMS-1500 claim form.

        supervising_provider : typing.Optional[SupervisingProviderUpdate]
            Required when the rendering provider is supervised by a physician. If not required by this implementation guide, do not send.

        referring_provider : typing.Optional[ReferringProviderUpdate]
            The final provider who referred the services that were rendered.
            All physicians who order services or refer Medicare beneficiaries must
            report this data.

        initial_referring_provider : typing.Optional[InitialReferringProviderUpdate]
            The second iteration of Loop ID-2310. Use code "P3 - Primary Care Provider" in this loop to
            indicate the initial referral from the primary care provider or whatever provider wrote the initial referral for this patient's episode of care being billed/reported in this transaction.

        referral_number : typing.Optional[str]
            Refers to REF\*9F on the 837p. Value cannot be greater than 50 characters.

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

        Returns
        -------
        Encounter

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

        from candid import AsyncCandidApiClient
        from candid.resources.commons import FacilityTypeCode

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


        async def main() -> None:
            await client.encounters.v_4.update(
                encounter_id=uuid.UUID(
                    "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                ),
                diagnosis_ids=[
                    uuid.UUID(
                        "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
                    )
                ],
                place_of_service_code_as_submitted=FacilityTypeCode.PHARMACY,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/encounters/v4/{jsonable_encoder(encounter_id)}",
            base_url=self._client_wrapper.get_environment().candid_api,
            method="PATCH",
            json={
                "diagnosis_ids": diagnosis_ids,
                "place_of_service_code_as_submitted": place_of_service_code_as_submitted,
                "benefits_assigned_to_provider": benefits_assigned_to_provider,
                "prior_authorization_number": prior_authorization_number,
                "external_id": external_id,
                "date_of_service": date_of_service,
                "tag_ids": tag_ids,
                "clinical_notes": clinical_notes,
                "pay_to_address": pay_to_address,
                "billable_status": billable_status,
                "responsible_party": responsible_party,
                "provider_accepts_assignment": provider_accepts_assignment,
                "synchronicity": synchronicity,
                "place_of_service_code": place_of_service_code,
                "appointment_type": appointment_type,
                "end_date_of_service": end_date_of_service,
                "subscriber_primary": subscriber_primary,
                "subscriber_secondary": subscriber_secondary,
                "additional_information": additional_information,
                "service_authorization_exception_code": service_authorization_exception_code,
                "admission_date": admission_date,
                "discharge_date": discharge_date,
                "onset_of_current_illness_or_symptom_date": onset_of_current_illness_or_symptom_date,
                "last_menstrual_period_date": last_menstrual_period_date,
                "delay_reason_code": delay_reason_code,
                "patient": patient,
                "patient_authorized_release": patient_authorized_release,
                "schema_instances": schema_instances,
                "vitals": vitals,
                "existing_medications": existing_medications,
                "rendering_provider": rendering_provider,
                "service_facility": service_facility,
                "guarantor": guarantor,
                "billing_provider": billing_provider,
                "supervising_provider": supervising_provider,
                "referring_provider": referring_provider,
                "initial_referring_provider": initial_referring_provider,
                "referral_number": referral_number,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        if 200 <= _response.status_code < 300:
            return typing.cast(
                Encounter,
                parse_obj_as(
                    type_=Encounter,  # type: ignore
                    object_=_response_json,
                ),
            )
        if "errorName" in _response_json:
            if _response_json["errorName"] == "EncounterExternalIdUniquenessError":
                raise EncounterExternalIdUniquenessError(
                    typing.cast(
                        EncounterExternalIdUniquenessErrorType,
                        parse_obj_as(
                            type_=EncounterExternalIdUniquenessErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "EntityNotFoundError":
                raise EntityNotFoundError(
                    typing.cast(
                        EntityNotFoundErrorMessage,
                        parse_obj_as(
                            type_=EntityNotFoundErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "UnauthorizedError":
                raise UnauthorizedError(
                    typing.cast(
                        UnauthorizedErrorMessage,
                        parse_obj_as(
                            type_=UnauthorizedErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "HttpRequestValidationsError":
                raise HttpRequestValidationsError(
                    typing.cast(
                        typing.List[RequestValidationError],
                        parse_obj_as(
                            type_=typing.List[RequestValidationError],  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "SchemaInstanceValidationHttpFailure":
                raise SchemaInstanceValidationHttpFailure(
                    typing.cast(
                        SchemaInstanceValidationFailure,
                        parse_obj_as(
                            type_=SchemaInstanceValidationFailure,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "UnprocessableEntityError":
                raise UnprocessableEntityError(
                    typing.cast(
                        UnprocessableEntityErrorMessage,
                        parse_obj_as(
                            type_=UnprocessableEntityErrorMessage,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
            if _response_json["errorName"] == "InvalidTagNamesError":
                raise InvalidTagNamesError(
                    typing.cast(
                        InvalidTagNamesErrorType,
                        parse_obj_as(
                            type_=InvalidTagNamesErrorType,  # type: ignore
                            object_=_response_json["content"],
                        ),
                    )
                )
        raise ApiError(status_code=_response.status_code, body=_response_json)
