"""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
from typing import Any

from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import ValidationError
from pydantic import field_validator
from typing_extensions import Self

from ..models.complete_response import CompleteResponse
from ..models.vardok_id_response import VardokIdResponse

GETVARDOKVARDEFMAPPINGBYID200RESPONSE_ONE_OF_SCHEMAS = [
    "CompleteResponse",
    "VardokIdResponse",
]


class GetVardokVardefMappingById200Response(BaseModel):
    """GetVardokVardefMappingById200Response"""

    # data type: CompleteResponse
    oneof_schema_1_validator: CompleteResponse | None = None
    # data type: VardokIdResponse
    oneof_schema_2_validator: VardokIdResponse | None = None
    actual_instance: CompleteResponse | VardokIdResponse | None = None
    one_of_schemas: set[str] = {"CompleteResponse", "VardokIdResponse"}

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

    def __init__(self, *args, **kwargs) -> None:
        if args:
            if len(args) > 1:
                raise ValueError(
                    "If a position argument is used, only 1 is allowed to set `actual_instance`"
                )
            if kwargs:
                raise ValueError(
                    "If a position argument is used, keyword arguments cannot be used."
                )
            super().__init__(actual_instance=args[0])
        else:
            super().__init__(**kwargs)

    @field_validator("actual_instance")
    def actual_instance_must_validate_oneof(cls, v):
        instance = GetVardokVardefMappingById200Response.model_construct()
        error_messages = []
        match = 0
        # validate data type: CompleteResponse
        if not isinstance(v, CompleteResponse):
            error_messages.append(
                f"Error! Input type `{type(v)}` is not `CompleteResponse`"
            )
        else:
            match += 1
        # validate data type: VardokIdResponse
        if not isinstance(v, VardokIdResponse):
            error_messages.append(
                f"Error! Input type `{type(v)}` is not `VardokIdResponse`"
            )
        else:
            match += 1
        if match > 1:
            # more than 1 match
            raise ValueError(
                "Multiple matches found when setting `actual_instance` in GetVardokVardefMappingById200Response with oneOf schemas: CompleteResponse, VardokIdResponse. Details: "
                + ", ".join(error_messages)
            )
        if match == 0:
            # no match
            raise ValueError(
                "No match found when setting `actual_instance` in GetVardokVardefMappingById200Response with oneOf schemas: CompleteResponse, VardokIdResponse. Details: "
                + ", ".join(error_messages)
            )
        return v

    @classmethod
    def from_dict(cls, obj: str | dict[str, Any]) -> Self:
        return cls.from_json(json.dumps(obj))

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Returns the object represented by the json string"""
        instance = cls.model_construct()
        error_messages = []
        match = 0

        # deserialize data into CompleteResponse
        try:
            instance.actual_instance = CompleteResponse.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into VardokIdResponse
        try:
            instance.actual_instance = VardokIdResponse.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))

        if match > 1:
            # more than 1 match
            raise ValueError(
                "Multiple matches found when deserializing the JSON string into GetVardokVardefMappingById200Response with oneOf schemas: CompleteResponse, VardokIdResponse. Details: "
                + ", ".join(error_messages)
            )
        if match == 0:
            # no match
            raise ValueError(
                "No match found when deserializing the JSON string into GetVardokVardefMappingById200Response with oneOf schemas: CompleteResponse, VardokIdResponse. Details: "
                + ", ".join(error_messages)
            )
        return instance

    def to_json(self) -> str:
        """Returns the JSON representation of the actual instance"""
        if self.actual_instance is None:
            return "null"

        if hasattr(self.actual_instance, "to_json") and callable(
            self.actual_instance.to_json
        ):
            return self.actual_instance.to_json()
        return json.dumps(self.actual_instance)

    def to_dict(self) -> dict[str, Any] | CompleteResponse | VardokIdResponse | None:
        """Returns the dict representation of the actual instance"""
        if self.actual_instance is None:
            return None

        if hasattr(self.actual_instance, "to_dict") and callable(
            self.actual_instance.to_dict
        ):
            return self.actual_instance.to_dict()
        # primitive type
        return self.actual_instance

    def to_str(self) -> str:
        """Returns the string representation of the actual instance"""
        return pprint.pformat(self.model_dump())
