"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from ascend_sdk import utils
from ascend_sdk.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
)
from ascend_sdk.utils import validate_open_enum
from enum import Enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict


class LegalEntityBusinessIndustrialClassification(
    str, Enum, metaclass=utils.OpenEnumMeta
):
    BUSINESS_INDUSTRIAL_CLASSIFICATION_UNSPECIFIED = (
        "BUSINESS_INDUSTRIAL_CLASSIFICATION_UNSPECIFIED"
    )
    AGRICULTURE_FORESTRY_AND_FISHING = "AGRICULTURE_FORESTRY_AND_FISHING"
    MINING = "MINING"
    CONSTRUCTION = "CONSTRUCTION"
    MANUFACTURING = "MANUFACTURING"
    TRANSPORTATION_COMMUNICATIONS_ELECTRIC_GAS_AND_SANITARY_SERVICES = (
        "TRANSPORTATION_COMMUNICATIONS_ELECTRIC_GAS_AND_SANITARY_SERVICES"
    )
    WHOLESALE_TRADE = "WHOLESALE_TRADE"
    RETAIL_TRADE = "RETAIL_TRADE"
    FINANCE_INSURANCE_AND_REAL_ESTATE = "FINANCE_INSURANCE_AND_REAL_ESTATE"
    SERVICES = "SERVICES"
    PUBLIC_ADMINISTRATION = "PUBLIC_ADMINISTRATION"


class LegalEntityCorporateStructure(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""Corporate structure of the entity."""

    ENTITY_CORPORATE_STRUCTURE_UNSPECIFIED = "ENTITY_CORPORATE_STRUCTURE_UNSPECIFIED"
    CORPORATION_C_CORP = "CORPORATION_C_CORP"
    CORPORATION_S_CORP = "CORPORATION_S_CORP"
    CORPORATION_B_CORP = "CORPORATION_B_CORP"
    CORPORATION_NONPROFIT = "CORPORATION_NONPROFIT"


class LegalEntityNegativeNewsTypedDict(TypedDict):
    r"""Information about any negative news against related parties and entities"""

    negative_news_against_related_parties: NotRequired[bool]
    r"""Indicates whether there is negative news against related parties"""
    negative_news_against_related_parties_description: NotRequired[str]
    r"""Description of the negative news against related parties"""


class LegalEntityNegativeNews(BaseModel):
    r"""Information about any negative news against related parties and entities"""

    negative_news_against_related_parties: Optional[bool] = None
    r"""Indicates whether there is negative news against related parties"""

    negative_news_against_related_parties_description: Optional[str] = None
    r"""Description of the negative news against related parties"""


class EntityDueDiligenceTypedDict(TypedDict):
    r"""Due Diligence for Legal Entities"""

    entity_issues_bearer_shares: NotRequired[bool]
    r"""Indicates whether the entity issues bearer shares"""
    negative_news: NotRequired[Nullable[LegalEntityNegativeNewsTypedDict]]
    r"""Information about any negative news against related parties and entities"""


class EntityDueDiligence(BaseModel):
    r"""Due Diligence for Legal Entities"""

    entity_issues_bearer_shares: Optional[bool] = None
    r"""Indicates whether the entity issues bearer shares"""

    negative_news: OptionalNullable[LegalEntityNegativeNews] = UNSET
    r"""Information about any negative news against related parties and entities"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["entity_issues_bearer_shares", "negative_news"]
        nullable_fields = ["negative_news"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class LegalEntityEntityType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The entity type."""

    ENTITY_TYPE_UNSPECIFIED = "ENTITY_TYPE_UNSPECIFIED"
    CORPORATION = "CORPORATION"
    LIMITED_LIABILITY_COMPANY = "LIMITED_LIABILITY_COMPANY"
    PARTNERSHIP = "PARTNERSHIP"
    SOLE_PROPRIETORSHIP_OR_SINGLE_MEMBER_LLC = (
        "SOLE_PROPRIETORSHIP_OR_SINGLE_MEMBER_LLC"
    )
    TRUST = "TRUST"
    ESTATE = "ESTATE"


class LegalEntityExemptCustomerReason(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The reason the customer is exempt from verifying beneficial owners, if applicable."""

    EXEMPT_REASON_UNSPECIFIED = "EXEMPT_REASON_UNSPECIFIED"
    REGULATED_FINANCIAL_INSTITUTION = "REGULATED_FINANCIAL_INSTITUTION"
    DEPARTMENT_OR_AGENCY_OF_FEDERAL_STATE_OR_SUBDIVISION = (
        "DEPARTMENT_OR_AGENCY_OF_FEDERAL_STATE_OR_SUBDIVISION"
    )
    NON_BANK_LISTED_ENTITY = "NON_BANK_LISTED_ENTITY"
    SECTION_12_SECURITIES_EXCHANGE_ACT_1934_OR_15_D = (
        "SECTION_12_SECURITIES_EXCHANGE_ACT_1934_OR_15D"
    )
    SECTION_3_INVESTMENT_COMPANY_ACT_1940 = "SECTION_3_INVESTMENT_COMPANY_ACT_1940"
    SECTION_202_A_INVESTMENT_ADVISORS_ACT_1940 = (
        "SECTION_202A_INVESTMENT_ADVISORS_ACT_1940"
    )
    SECTION_3_SECURITIES_EXCHANGE_ACT_1934_SECTION_6_OR_17_A = (
        "SECTION_3_SECURITIES_EXCHANGE_ACT_1934_SECTION_6_OR_17A"
    )
    ANY_OTHER_SECURITIES_EXCHANGE_ACT_1934 = "ANY_OTHER_SECURITIES_EXCHANGE_ACT_1934"
    COMMODITY_FUTURES_TRADING_COMMISSION_REGISTERED = (
        "COMMODITY_FUTURES_TRADING_COMMISSION_REGISTERED"
    )
    PUBLIC_ACCOUNTING_FIRM_SECTION_102_SARBANES_OXLEY = (
        "PUBLIC_ACCOUNTING_FIRM_SECTION_102_SARBANES_OXLEY"
    )
    STATE_REGULATED_INSURANCE_COMPANY = "STATE_REGULATED_INSURANCE_COMPANY"


class FormationDateTypedDict(TypedDict):
    r"""If the legal entity is a trust, the formation date is required."""

    day: NotRequired[int]
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""
    month: NotRequired[int]
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""
    year: NotRequired[int]
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class FormationDate(BaseModel):
    r"""If the legal entity is a trust, the formation date is required."""

    day: Optional[int] = None
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""

    month: Optional[int] = None
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""

    year: Optional[int] = None
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityEffectiveDateTypedDict(TypedDict):
    r"""The date on which the trader meets or exceeds the large trader reporting threshold, which is defined by the U.S. Securities and Exchange Commission (SEC) as trades of 2 million shares or $20 million in a single day or 20 million shares or $200 million during a calendar month"""

    day: NotRequired[int]
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""
    month: NotRequired[int]
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""
    year: NotRequired[int]
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityEffectiveDate(BaseModel):
    r"""The date on which the trader meets or exceeds the large trader reporting threshold, which is defined by the U.S. Securities and Exchange Commission (SEC) as trades of 2 million shares or $20 million in a single day or 20 million shares or $200 million during a calendar month"""

    day: Optional[int] = None
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""

    month: Optional[int] = None
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""

    year: Optional[int] = None
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityLargeTraderTypedDict(TypedDict):
    r"""Large trader for the legal entity."""

    effective_date: NotRequired[Nullable[LegalEntityEffectiveDateTypedDict]]
    r"""The date on which the trader meets or exceeds the large trader reporting threshold, which is defined by the U.S. Securities and Exchange Commission (SEC) as trades of 2 million shares or $20 million in a single day or 20 million shares or $200 million during a calendar month"""
    large_trader_id: NotRequired[str]
    r"""SEC-issued ID signifying the person/entity as a large trader; Required for CAIS regulatory reporting."""


class LegalEntityLargeTrader(BaseModel):
    r"""Large trader for the legal entity."""

    effective_date: OptionalNullable[LegalEntityEffectiveDate] = UNSET
    r"""The date on which the trader meets or exceeds the large trader reporting threshold, which is defined by the U.S. Securities and Exchange Commission (SEC) as trades of 2 million shares or $20 million in a single day or 20 million shares or $200 million during a calendar month"""

    large_trader_id: Optional[str] = None
    r"""SEC-issued ID signifying the person/entity as a large trader; Required for CAIS regulatory reporting."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["effective_date", "large_trader_id"]
        nullable_fields = ["effective_date"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class LegalAddressTypedDict(TypedDict):
    r"""The mailing address of the legal entity. Required fields within the `legal_address` object include:
    - `administrative_area`
    - `region_code` - 2 character CLDR Code
    - `postal_code`
    - `locality`
    - `address_lines` - max 5 lines
    """

    address_lines: NotRequired[List[str]]
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """
    administrative_area: NotRequired[str]
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""
    language_code: NotRequired[str]
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """
    locality: NotRequired[str]
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""
    organization: NotRequired[str]
    r"""Optional. The name of the organization at the address."""
    postal_code: NotRequired[str]
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""
    recipients: NotRequired[List[str]]
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""
    region_code: NotRequired[str]
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""
    revision: NotRequired[int]
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """
    sorting_code: NotRequired[str]
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""
    sublocality: NotRequired[str]
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class LegalAddress(BaseModel):
    r"""The mailing address of the legal entity. Required fields within the `legal_address` object include:
    - `administrative_area`
    - `region_code` - 2 character CLDR Code
    - `postal_code`
    - `locality`
    - `address_lines` - max 5 lines
    """

    address_lines: Optional[List[str]] = None
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """

    administrative_area: Optional[str] = None
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""

    language_code: Optional[str] = None
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """

    locality: Optional[str] = None
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""

    organization: Optional[str] = None
    r"""Optional. The name of the organization at the address."""

    postal_code: Optional[str] = None
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""

    recipients: Optional[List[str]] = None
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""

    region_code: Optional[str] = None
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""

    revision: Optional[int] = None
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """

    sorting_code: Optional[str] = None
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""

    sublocality: Optional[str] = None
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class LegalEntityTaxIDType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The nature of the U.S. Tax ID indicated in the related tax_id field; Examples include ITIN, SSN, EIN."""

    TAX_ID_TYPE_UNSPECIFIED = "TAX_ID_TYPE_UNSPECIFIED"
    TAX_ID_TYPE_SSN = "TAX_ID_TYPE_SSN"
    TAX_ID_TYPE_ITIN = "TAX_ID_TYPE_ITIN"
    TAX_ID_TYPE_EIN = "TAX_ID_TYPE_EIN"


class LegalEntityCNoticeDateTypedDict(TypedDict):
    r"""C Notice date."""

    day: NotRequired[int]
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""
    month: NotRequired[int]
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""
    year: NotRequired[int]
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityCNoticeDate(BaseModel):
    r"""C Notice date."""

    day: Optional[int] = None
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""

    month: Optional[int] = None
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""

    year: Optional[int] = None
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityFederalTaxClassification(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""Federal tax classification."""

    FEDERAL_TAX_CLASSIFICATION_UNSPECIFIED = "FEDERAL_TAX_CLASSIFICATION_UNSPECIFIED"
    INDIV_SOLEPROP_OR_SINGLEMEMBERLLC = "INDIV_SOLEPROP_OR_SINGLEMEMBERLLC"
    PARTNERSHIP = "PARTNERSHIP"
    C_CORPORATION = "C_CORPORATION"
    S_CORPORATION = "S_CORPORATION"
    TRUST_ESTATE = "TRUST_ESTATE"
    LLC_TAXED_AS_C_CORP = "LLC_TAXED_AS_C_CORP"
    LLC_TAXED_AS_S_CORP = "LLC_TAXED_AS_S_CORP"
    LLC_TAXED_AS_PARTNERSHIP = "LLC_TAXED_AS_PARTNERSHIP"
    OTHER = "OTHER"


class LegalEntityFirstBNoticeDateTypedDict(TypedDict):
    r"""Initial B Notice date."""

    day: NotRequired[int]
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""
    month: NotRequired[int]
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""
    year: NotRequired[int]
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityFirstBNoticeDate(BaseModel):
    r"""Initial B Notice date."""

    day: Optional[int] = None
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""

    month: Optional[int] = None
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""

    year: Optional[int] = None
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityIrsFormType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""IRS form type."""

    IRS_FORM_TYPE_UNSPECIFIED = "IRS_FORM_TYPE_UNSPECIFIED"
    W_9 = "W_9"


class LegalEntityReportingEligibility(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""Tax reporting eligibility."""

    TAX_REPORTING_ELIGIBILITY_UNSPECIFIED = "TAX_REPORTING_ELIGIBILITY_UNSPECIFIED"
    ELIGIBLE = "ELIGIBLE"
    INELIGIBLE = "INELIGIBLE"


class LegalEntityTaxCertificationDateTypedDict(TypedDict):
    r"""Tax Certification date."""

    day: NotRequired[int]
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""
    month: NotRequired[int]
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""
    year: NotRequired[int]
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityTaxCertificationDate(BaseModel):
    r"""Tax Certification date."""

    day: Optional[int] = None
    r"""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant."""

    month: Optional[int] = None
    r"""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day."""

    year: Optional[int] = None
    r"""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year."""


class LegalEntityTaxpayerCertificationState(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""Taxpayer certification status."""

    TAXPAYER_CERTIFICATION_STATE_UNSPECIFIED = (
        "TAXPAYER_CERTIFICATION_STATE_UNSPECIFIED"
    )
    CERTIFIED = "CERTIFIED"
    UNCERTIFIED = "UNCERTIFIED"


class LegalEntityUsTinStatus(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""United States Individual Taxpayer Identification Number (ITIN) status."""

    US_TIN_STATUS_UNSPECIFIED = "US_TIN_STATUS_UNSPECIFIED"
    PASSING = "PASSING"
    FAILING = "FAILING"


class LegalEntityWithholdingState(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""B/C Notice status."""

    WITHHOLDING_STATE_UNSPECIFIED = "WITHHOLDING_STATE_UNSPECIFIED"
    FIRST_B_NOTICE_RECEIVED = "FIRST_B_NOTICE_RECEIVED"
    SECOND_B_NOTICE_RECEIVED = "SECOND_B_NOTICE_RECEIVED"
    C_NOTICE_RECEIVED = "C_NOTICE_RECEIVED"
    C_NOTICE_INDICATED_BY_CUSTOMER = "C_NOTICE_INDICATED_BY_CUSTOMER"


class LegalEntityTaxProfileTypedDict(TypedDict):
    r"""The tax profile for the legal entity."""

    c_notice_date: NotRequired[Nullable[LegalEntityCNoticeDateTypedDict]]
    r"""C Notice date."""
    federal_tax_classification: NotRequired[LegalEntityFederalTaxClassification]
    r"""Federal tax classification."""
    first_b_notice_date: NotRequired[Nullable[LegalEntityFirstBNoticeDateTypedDict]]
    r"""Initial B Notice date."""
    irs_form_type: NotRequired[LegalEntityIrsFormType]
    r"""IRS form type."""
    legal_tax_region_code: NotRequired[str]
    r"""Legal tax region must be \"US\" if provided W-9, otherwise must be a non-US country."""
    reporting_eligibility: NotRequired[LegalEntityReportingEligibility]
    r"""Tax reporting eligibility."""
    tax_certification_date: NotRequired[
        Nullable[LegalEntityTaxCertificationDateTypedDict]
    ]
    r"""Tax Certification date."""
    taxpayer_certification_state: NotRequired[LegalEntityTaxpayerCertificationState]
    r"""Taxpayer certification status."""
    us_tin_status: NotRequired[LegalEntityUsTinStatus]
    r"""United States Individual Taxpayer Identification Number (ITIN) status."""
    withholding_state: NotRequired[LegalEntityWithholdingState]
    r"""B/C Notice status."""


class LegalEntityTaxProfile(BaseModel):
    r"""The tax profile for the legal entity."""

    c_notice_date: OptionalNullable[LegalEntityCNoticeDate] = UNSET
    r"""C Notice date."""

    federal_tax_classification: Annotated[
        Optional[LegalEntityFederalTaxClassification],
        PlainValidator(validate_open_enum(False)),
    ] = None
    r"""Federal tax classification."""

    first_b_notice_date: OptionalNullable[LegalEntityFirstBNoticeDate] = UNSET
    r"""Initial B Notice date."""

    irs_form_type: Annotated[
        Optional[LegalEntityIrsFormType], PlainValidator(validate_open_enum(False))
    ] = None
    r"""IRS form type."""

    legal_tax_region_code: Optional[str] = None
    r"""Legal tax region must be \"US\" if provided W-9, otherwise must be a non-US country."""

    reporting_eligibility: Annotated[
        Optional[LegalEntityReportingEligibility],
        PlainValidator(validate_open_enum(False)),
    ] = None
    r"""Tax reporting eligibility."""

    tax_certification_date: OptionalNullable[LegalEntityTaxCertificationDate] = UNSET
    r"""Tax Certification date."""

    taxpayer_certification_state: Annotated[
        Optional[LegalEntityTaxpayerCertificationState],
        PlainValidator(validate_open_enum(False)),
    ] = None
    r"""Taxpayer certification status."""

    us_tin_status: Annotated[
        Optional[LegalEntityUsTinStatus], PlainValidator(validate_open_enum(False))
    ] = None
    r"""United States Individual Taxpayer Identification Number (ITIN) status."""

    withholding_state: Annotated[
        Optional[LegalEntityWithholdingState], PlainValidator(validate_open_enum(False))
    ] = None
    r"""B/C Notice status."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "c_notice_date",
            "federal_tax_classification",
            "first_b_notice_date",
            "irs_form_type",
            "legal_tax_region_code",
            "reporting_eligibility",
            "tax_certification_date",
            "taxpayer_certification_state",
            "us_tin_status",
            "withholding_state",
        ]
        nullable_fields = [
            "c_notice_date",
            "first_b_notice_date",
            "tax_certification_date",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class LegalEntityTypedDict(TypedDict):
    r"""A legal entity. Legal entities are organizations, such as companies, that participate in financial transactions"""

    accredited_investor: NotRequired[bool]
    r"""Indicates whether the entity is an accredited investor. By default, this is set to `false`."""
    adviser: NotRequired[bool]
    r"""Indicates whether the entity is an adviser. By default, this is set to `false`."""
    broker_dealer: NotRequired[bool]
    r"""Indicates whether the entity is a broker dealer. By default, this is set to `false`."""
    business_industrial_classification: NotRequired[
        LegalEntityBusinessIndustrialClassification
    ]
    corporate_structure: NotRequired[LegalEntityCorporateStructure]
    r"""Corporate structure of the entity."""
    correspondent_id: NotRequired[str]
    r"""The correspondent id associated with the legal entity."""
    doing_business_as: NotRequired[List[str]]
    r"""DBA (Doing Business As) names. Can list up to 5 associated with the Legal Entity"""
    entity_due_diligence: NotRequired[Nullable[EntityDueDiligenceTypedDict]]
    r"""Due Diligence for Legal Entities"""
    entity_name: NotRequired[str]
    r"""The legal entity name."""
    entity_type: NotRequired[LegalEntityEntityType]
    r"""The entity type."""
    exempt_customer_reason: NotRequired[LegalEntityExemptCustomerReason]
    r"""The reason the customer is exempt from verifying beneficial owners, if applicable."""
    exempt_verifying_beneficial_owners: NotRequired[bool]
    r"""Indicates whether the entity is exempt from verifying beneficial owners. By default, this is set to `false`."""
    for_the_benefit_of: NotRequired[str]
    r"""If the legal entity is a trust, they may set this field to convey ownership and value to a trustee."""
    foreign_entity: NotRequired[bool]
    r"""Indicates whether the entity is a foreign entity. By default, this is set to `false`."""
    foreign_financial_institution: NotRequired[bool]
    r"""Indicates whether the entity is a foreign financial institution. By default, this is set to `false`."""
    formation_date: NotRequired[Nullable[FormationDateTypedDict]]
    r"""If the legal entity is a trust, the formation date is required."""
    global_person_id: NotRequired[str]
    r"""Globally Unique identifier for a legal natural person"""
    institutional_customer: NotRequired[bool]
    r"""Indicates whether the entity is an institutional customer"""
    investigation_id: NotRequired[str]
    r"""Investigation id relating to the Customer Identification Program (CIP) and Customer Due Diligence (CDD)."""
    large_trader: NotRequired[Nullable[LegalEntityLargeTraderTypedDict]]
    r"""Large trader for the legal entity."""
    legal_address: NotRequired[Nullable[LegalAddressTypedDict]]
    r"""The mailing address of the legal entity. Required fields within the `legal_address` object include:
    - `administrative_area`
    - `region_code` - 2 character CLDR Code
    - `postal_code`
    - `locality`
    - `address_lines` - max 5 lines
    """
    legal_entity_id: NotRequired[str]
    r"""A system-generated unique identifier referencing a single juridical (non-natural) person (e.g., a corporation); Used to access the record after creation"""
    lei_code: NotRequired[str]
    r"""The Legal Entity Identifier (LEI) is the financial industry term for a unique global identifier for legal entities participating in financial transactions"""
    name: NotRequired[str]
    r"""The name field Format: legalEntities/{legalEntity}"""
    operating_regions: NotRequired[List[str]]
    r"""The operational footprint of an entity. Operating regions encompass all countries and regions where a company has a significant business presence This includes locations with physical offices, manufacturing plants, service centers, and sales and marketing activities Regions must be provided as two-character CLDR country codes"""
    registration_region: NotRequired[str]
    r"""The legal home of an entity. A region of registration, in the context of a corporation, refers to the specific geographic area where the corporation is legally registered and incorporated Defines the legal jurisdiction and framework under which the corporation operates, including legal regulations, tax obligations, and compliance requirements Region must be provided as a two-character CLDR country code"""
    regulated_investment_company: NotRequired[bool]
    r"""Indicates whether the entity is a regulated investment company. By default, this is set to `false`."""
    related_document_ids: NotRequired[List[str]]
    r"""Document ids related to the legal entity. At least one is required for RIA correspondents when creating Estate or Trust accounts."""
    revocable_trust: NotRequired[bool]
    r"""Indicates whether the trust is a revocable trust. By default, this is set to `false`."""
    tax_id: NotRequired[str]
    r"""The full U.S. tax ID for a related entity; Must be provided with `EIN` tax ID type"""
    tax_id_last_four: NotRequired[str]
    r"""The last four characters of the related person's tax identifier; Masked/truncated to \"last four\" in most usage contexts to preserve data privacy."""
    tax_id_type: NotRequired[LegalEntityTaxIDType]
    r"""The nature of the U.S. Tax ID indicated in the related tax_id field; Examples include ITIN, SSN, EIN."""
    tax_profile: NotRequired[Nullable[LegalEntityTaxProfileTypedDict]]
    r"""The tax profile for the legal entity."""


class LegalEntity(BaseModel):
    r"""A legal entity. Legal entities are organizations, such as companies, that participate in financial transactions"""

    accredited_investor: Optional[bool] = None
    r"""Indicates whether the entity is an accredited investor. By default, this is set to `false`."""

    adviser: Optional[bool] = None
    r"""Indicates whether the entity is an adviser. By default, this is set to `false`."""

    broker_dealer: Optional[bool] = None
    r"""Indicates whether the entity is a broker dealer. By default, this is set to `false`."""

    business_industrial_classification: Annotated[
        Optional[LegalEntityBusinessIndustrialClassification],
        PlainValidator(validate_open_enum(False)),
    ] = None

    corporate_structure: Annotated[
        Optional[LegalEntityCorporateStructure],
        PlainValidator(validate_open_enum(False)),
    ] = None
    r"""Corporate structure of the entity."""

    correspondent_id: Optional[str] = None
    r"""The correspondent id associated with the legal entity."""

    doing_business_as: Optional[List[str]] = None
    r"""DBA (Doing Business As) names. Can list up to 5 associated with the Legal Entity"""

    entity_due_diligence: OptionalNullable[EntityDueDiligence] = UNSET
    r"""Due Diligence for Legal Entities"""

    entity_name: Optional[str] = None
    r"""The legal entity name."""

    entity_type: Annotated[
        Optional[LegalEntityEntityType], PlainValidator(validate_open_enum(False))
    ] = None
    r"""The entity type."""

    exempt_customer_reason: Annotated[
        Optional[LegalEntityExemptCustomerReason],
        PlainValidator(validate_open_enum(False)),
    ] = None
    r"""The reason the customer is exempt from verifying beneficial owners, if applicable."""

    exempt_verifying_beneficial_owners: Optional[bool] = None
    r"""Indicates whether the entity is exempt from verifying beneficial owners. By default, this is set to `false`."""

    for_the_benefit_of: Optional[str] = None
    r"""If the legal entity is a trust, they may set this field to convey ownership and value to a trustee."""

    foreign_entity: Optional[bool] = None
    r"""Indicates whether the entity is a foreign entity. By default, this is set to `false`."""

    foreign_financial_institution: Optional[bool] = None
    r"""Indicates whether the entity is a foreign financial institution. By default, this is set to `false`."""

    formation_date: OptionalNullable[FormationDate] = UNSET
    r"""If the legal entity is a trust, the formation date is required."""

    global_person_id: Optional[str] = None
    r"""Globally Unique identifier for a legal natural person"""

    institutional_customer: Optional[bool] = None
    r"""Indicates whether the entity is an institutional customer"""

    investigation_id: Optional[str] = None
    r"""Investigation id relating to the Customer Identification Program (CIP) and Customer Due Diligence (CDD)."""

    large_trader: OptionalNullable[LegalEntityLargeTrader] = UNSET
    r"""Large trader for the legal entity."""

    legal_address: OptionalNullable[LegalAddress] = UNSET
    r"""The mailing address of the legal entity. Required fields within the `legal_address` object include:
    - `administrative_area`
    - `region_code` - 2 character CLDR Code
    - `postal_code`
    - `locality`
    - `address_lines` - max 5 lines
    """

    legal_entity_id: Optional[str] = None
    r"""A system-generated unique identifier referencing a single juridical (non-natural) person (e.g., a corporation); Used to access the record after creation"""

    lei_code: Optional[str] = None
    r"""The Legal Entity Identifier (LEI) is the financial industry term for a unique global identifier for legal entities participating in financial transactions"""

    name: Optional[str] = None
    r"""The name field Format: legalEntities/{legalEntity}"""

    operating_regions: Optional[List[str]] = None
    r"""The operational footprint of an entity. Operating regions encompass all countries and regions where a company has a significant business presence This includes locations with physical offices, manufacturing plants, service centers, and sales and marketing activities Regions must be provided as two-character CLDR country codes"""

    registration_region: Optional[str] = None
    r"""The legal home of an entity. A region of registration, in the context of a corporation, refers to the specific geographic area where the corporation is legally registered and incorporated Defines the legal jurisdiction and framework under which the corporation operates, including legal regulations, tax obligations, and compliance requirements Region must be provided as a two-character CLDR country code"""

    regulated_investment_company: Optional[bool] = None
    r"""Indicates whether the entity is a regulated investment company. By default, this is set to `false`."""

    related_document_ids: Optional[List[str]] = None
    r"""Document ids related to the legal entity. At least one is required for RIA correspondents when creating Estate or Trust accounts."""

    revocable_trust: Optional[bool] = None
    r"""Indicates whether the trust is a revocable trust. By default, this is set to `false`."""

    tax_id: Optional[str] = None
    r"""The full U.S. tax ID for a related entity; Must be provided with `EIN` tax ID type"""

    tax_id_last_four: Optional[str] = None
    r"""The last four characters of the related person's tax identifier; Masked/truncated to \"last four\" in most usage contexts to preserve data privacy."""

    tax_id_type: Annotated[
        Optional[LegalEntityTaxIDType], PlainValidator(validate_open_enum(False))
    ] = None
    r"""The nature of the U.S. Tax ID indicated in the related tax_id field; Examples include ITIN, SSN, EIN."""

    tax_profile: OptionalNullable[LegalEntityTaxProfile] = UNSET
    r"""The tax profile for the legal entity."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "accredited_investor",
            "adviser",
            "broker_dealer",
            "business_industrial_classification",
            "corporate_structure",
            "correspondent_id",
            "doing_business_as",
            "entity_due_diligence",
            "entity_name",
            "entity_type",
            "exempt_customer_reason",
            "exempt_verifying_beneficial_owners",
            "for_the_benefit_of",
            "foreign_entity",
            "foreign_financial_institution",
            "formation_date",
            "global_person_id",
            "institutional_customer",
            "investigation_id",
            "large_trader",
            "legal_address",
            "legal_entity_id",
            "lei_code",
            "name",
            "operating_regions",
            "registration_region",
            "regulated_investment_company",
            "related_document_ids",
            "revocable_trust",
            "tax_id",
            "tax_id_last_four",
            "tax_id_type",
            "tax_profile",
        ]
        nullable_fields = [
            "entity_due_diligence",
            "formation_date",
            "large_trader",
            "legal_address",
            "tax_profile",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m
