"""Internal Variable Definitions Administration API

## Introduction  Variable Definitions are centralized definitions of concrete variables which are typically present in multiple datasets. Variable Definitions support standardization of data and metadata and facilitate sharing and joining of data by clarifying when variables have an identical definition.  ## Maintenance of Variable Definitions This API allows for creation, maintenance and access of Variable Definitions.  ### Ownership Creation and maintenance of variables may only be performed by Statistics Norway employees representing a specific Dapla team, who are defined as the owners of a given Variable Definition. The team an owner represents must be specified when making a request through the `active_group` query parameter. All maintenance is to be performed by the owners, with no intervention from administrators.  ### Status All Variable Definitions have an associated status. The possible values for status are `DRAFT`, `PUBLISHED_INTERNAL` and `PUBLISHED_EXTERNAL`.  #### Draft When a Variable Definition is created it is assigned the status `DRAFT`. Under this status the Variable Definition is:  - Only visible to Statistics Norway employees. - Mutable (it may be changed directly without need for versioning). - Not suitable to refer to from other systems.  This status may be changed to `PUBLISHED_INTERNAL` or `PUBLISHED_EXTERNAL` with a direct update.  #### Published Internal Under this status the Variable Definition is:  - Only visible to Statistics Norway employees. - Immutable (all changes are versioned). - Suitable to refer to in internal systems for statistics production. - Not suitable to refer to for external use (for example in Statistikkbanken).  This status may be changed to `PUBLISHED_EXTERNAL` by creating a Patch version.  #### Published External Under this status the Variable Definition is:  - Visible to the general public. - Immutable (all changes are versioned). - Suitable to refer to from any system.  This status may not be changed as it would break immutability. If a Variable Definition is no longer relevant then its period of validity should be ended by specifying a `valid_until` date in a Patch version.  ### Immutability Variable Definitions are immutable. This means that any changes must be performed in a strict versioning system. Consumers can avoid being exposed to breaking changes by specifying a `date_of_validity` when they request a Variable Definition.  #### Patches Patches are for changes which do not affect the fundamental meaning of the Variable Definition.  #### Validity Periods Validity Periods are versions with a period defined by a `valid_from` date and optionally a `valid_until` date. If the fundamental meaning of a Variable Definition is to be changed, it should be done by creating a new Validity Period.

The version of the OpenAPI document: 0.1
Contact: metadata@ssb.no
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from datetime import date
from typing import Annotated
from typing import Any
from typing import ClassVar

from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from pydantic import StrictBool
from pydantic import StrictStr
from typing_extensions import Self

from ..models.contact import Contact
from ..models.language_string_type import LanguageStringType


class ValidityPeriod(BaseModel):
    """Create a new Validity Period on a Published Variable Definition."""

    name: LanguageStringType | None = None
    definition: LanguageStringType
    classification_reference: StrictStr | None = Field(
        default=None,
        description="ID of a classification or code list from Klass. The given classification defines all possible values for the defined variable.",
    )
    unit_types: list[Annotated[str, Field(min_length=1, strict=True)]] | None = Field(
        default=None,
        description="A list of one or more unit types, e.g. person, vehicle, household. Must be defined as codes from https://www.ssb.no/klass/klassifikasjoner/702.",
    )
    subject_fields: list[Annotated[str, Field(min_length=1, strict=True)]] | None = (
        Field(
            default=None,
            description="A list of subject fields that the variable is used in. Must be defined as codes from https://www.ssb.no/klass/klassifikasjoner/618.",
        )
    )
    contains_special_categories_of_personal_data: StrictBool | None = Field(
        default=None,
        description="True if variable instances contain particularly sensitive information. Applies even if the information or identifiers are pseudonymized. Information within the following categories are regarded as particularly sensitive: Ethnicity, Political alignment, Religion, Philosophical beliefs, Union membership, Genetics, Biometrics, Health, Sexual relations, Sexual orientation",
    )
    measurement_type: StrictStr | None = Field(
        default=None,
        description="Type of measurement for the variable, e.g. length, volume, currency. Must be defined as codes from https://www.ssb.no/klass/klassifikasjoner/303",
    )
    valid_from: date = Field(
        description="The variable definition is valid from this date inclusive"
    )
    external_reference_uri: StrictStr | None = Field(
        default=None, description="A link (URI) to an external definition/documentation"
    )
    comment: LanguageStringType | None = None
    related_variable_definition_uris: list[StrictStr] | None = Field(
        default=None,
        description="Link(s) to related definitions of variables - a list of one or more definitions. For example for a variable after-tax income it could be relevant to link to definitions of income from work, property income etc.",
    )
    contact: Contact | None = None
    __properties: ClassVar[list[str]] = [
        "name",
        "definition",
        "classification_reference",
        "unit_types",
        "subject_fields",
        "contains_special_categories_of_personal_data",
        "measurement_type",
        "valid_from",
        "external_reference_uri",
        "comment",
        "related_variable_definition_uris",
        "contact",
    ]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Self | None:
        """Create an instance of ValidityPeriod from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: set[str] = set([])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of name
        if self.name:
            _dict["name"] = self.name.to_dict()
        # override the default output from pydantic by calling `to_dict()` of definition
        if self.definition:
            _dict["definition"] = self.definition.to_dict()
        # override the default output from pydantic by calling `to_dict()` of comment
        if self.comment:
            _dict["comment"] = self.comment.to_dict()
        # override the default output from pydantic by calling `to_dict()` of contact
        if self.contact:
            _dict["contact"] = self.contact.to_dict()
        # set to None if classification_reference (nullable) is None
        # and model_fields_set contains the field
        if (
            self.classification_reference is None
            and "classification_reference" in self.model_fields_set
        ):
            _dict["classification_reference"] = None

        # set to None if unit_types (nullable) is None
        # and model_fields_set contains the field
        if self.unit_types is None and "unit_types" in self.model_fields_set:
            _dict["unit_types"] = None

        # set to None if subject_fields (nullable) is None
        # and model_fields_set contains the field
        if self.subject_fields is None and "subject_fields" in self.model_fields_set:
            _dict["subject_fields"] = None

        # set to None if contains_special_categories_of_personal_data (nullable) is None
        # and model_fields_set contains the field
        if (
            self.contains_special_categories_of_personal_data is None
            and "contains_special_categories_of_personal_data" in self.model_fields_set
        ):
            _dict["contains_special_categories_of_personal_data"] = None

        # set to None if measurement_type (nullable) is None
        # and model_fields_set contains the field
        if (
            self.measurement_type is None
            and "measurement_type" in self.model_fields_set
        ):
            _dict["measurement_type"] = None

        # set to None if external_reference_uri (nullable) is None
        # and model_fields_set contains the field
        if (
            self.external_reference_uri is None
            and "external_reference_uri" in self.model_fields_set
        ):
            _dict["external_reference_uri"] = None

        # set to None if related_variable_definition_uris (nullable) is None
        # and model_fields_set contains the field
        if (
            self.related_variable_definition_uris is None
            and "related_variable_definition_uris" in self.model_fields_set
        ):
            _dict["related_variable_definition_uris"] = None

        return _dict

    @classmethod
    def from_dict(cls, obj: dict[str, Any] | None) -> Self | None:
        """Create an instance of ValidityPeriod from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate(
            {
                "name": LanguageStringType.from_dict(obj["name"])
                if obj.get("name") is not None
                else None,
                "definition": LanguageStringType.from_dict(obj["definition"])
                if obj.get("definition") is not None
                else None,
                "classification_reference": obj.get("classification_reference"),
                "unit_types": obj.get("unit_types"),
                "subject_fields": obj.get("subject_fields"),
                "contains_special_categories_of_personal_data": obj.get(
                    "contains_special_categories_of_personal_data"
                ),
                "measurement_type": obj.get("measurement_type"),
                "valid_from": obj.get("valid_from"),
                "external_reference_uri": obj.get("external_reference_uri"),
                "comment": LanguageStringType.from_dict(obj["comment"])
                if obj.get("comment") is not None
                else None,
                "related_variable_definition_uris": obj.get(
                    "related_variable_definition_uris"
                ),
                "contact": Contact.from_dict(obj["contact"])
                if obj.get("contact") is not None
                else None,
            }
        )
        return _obj
