"""Model Registry REST API.

REST API for Model Registry to create and manage ML model metadata

The version of the OpenAPI document: v1alpha3
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations

import json
import pprint
from typing import Any

from pydantic import (
    BaseModel,
    ConfigDict,
    ValidationError,
    field_validator,
)
from typing_extensions import Self

from mr_openapi.models.metadata_bool_value import MetadataBoolValue
from mr_openapi.models.metadata_double_value import MetadataDoubleValue
from mr_openapi.models.metadata_int_value import MetadataIntValue
from mr_openapi.models.metadata_proto_value import MetadataProtoValue
from mr_openapi.models.metadata_string_value import MetadataStringValue
from mr_openapi.models.metadata_struct_value import MetadataStructValue

METADATAVALUE_ONE_OF_SCHEMAS = [
    "MetadataBoolValue",
    "MetadataDoubleValue",
    "MetadataIntValue",
    "MetadataProtoValue",
    "MetadataStringValue",
    "MetadataStructValue",
]


class MetadataValue(BaseModel):
    """A value in properties."""

    # data type: MetadataIntValue
    oneof_schema_1_validator: MetadataIntValue | None = None
    # data type: MetadataDoubleValue
    oneof_schema_2_validator: MetadataDoubleValue | None = None
    # data type: MetadataStringValue
    oneof_schema_3_validator: MetadataStringValue | None = None
    # data type: MetadataStructValue
    oneof_schema_4_validator: MetadataStructValue | None = None
    # data type: MetadataProtoValue
    oneof_schema_5_validator: MetadataProtoValue | None = None
    # data type: MetadataBoolValue
    oneof_schema_6_validator: MetadataBoolValue | None = None
    actual_instance: (
        MetadataBoolValue
        | MetadataDoubleValue
        | MetadataIntValue
        | MetadataProtoValue
        | MetadataStringValue
        | MetadataStructValue
        | None
    ) = None
    one_of_schemas: set[str] = {
        "MetadataBoolValue",
        "MetadataDoubleValue",
        "MetadataIntValue",
        "MetadataProtoValue",
        "MetadataStringValue",
        "MetadataStructValue",
    }

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

    discriminator_value_class_map: dict[str, str] = {}

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

    @field_validator("actual_instance")
    def actual_instance_must_validate_oneof(cls, v):
        MetadataValue.model_construct()
        error_messages = []
        match = 0
        # validate data type: MetadataIntValue
        if not isinstance(v, MetadataIntValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataIntValue`")
        else:
            match += 1
        # validate data type: MetadataDoubleValue
        if not isinstance(v, MetadataDoubleValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataDoubleValue`")
        else:
            match += 1
        # validate data type: MetadataStringValue
        if not isinstance(v, MetadataStringValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataStringValue`")
        else:
            match += 1
        # validate data type: MetadataStructValue
        if not isinstance(v, MetadataStructValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataStructValue`")
        else:
            match += 1
        # validate data type: MetadataProtoValue
        if not isinstance(v, MetadataProtoValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataProtoValue`")
        else:
            match += 1
        # validate data type: MetadataBoolValue
        if not isinstance(v, MetadataBoolValue):
            error_messages.append(f"Error! Input type `{type(v)}` is not `MetadataBoolValue`")
        else:
            match += 1
        if match > 1:
            # more than 1 match
            raise ValueError(
                "Multiple matches found when setting `actual_instance` in MetadataValue with oneOf schemas: MetadataBoolValue, MetadataDoubleValue, MetadataIntValue, MetadataProtoValue, MetadataStringValue, MetadataStructValue. Details: "
                + ", ".join(error_messages)
            )
        if match == 0:
            # no match
            raise ValueError(
                "No match found when setting `actual_instance` in MetadataValue with oneOf schemas: MetadataBoolValue, MetadataDoubleValue, MetadataIntValue, MetadataProtoValue, MetadataStringValue, MetadataStructValue. 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

        # use oneOf discriminator to lookup the data type
        _data_type = json.loads(json_str).get("metadataType")
        if not _data_type:
            msg = "Failed to lookup data type from the field `metadataType` in the input."
            raise ValueError(msg)

        # check if data type is `MetadataBoolValue`
        if _data_type == "MetadataBoolValue":
            instance.actual_instance = MetadataBoolValue.from_json(json_str)
            return instance

        # check if data type is `MetadataDoubleValue`
        if _data_type == "MetadataDoubleValue":
            instance.actual_instance = MetadataDoubleValue.from_json(json_str)
            return instance

        # check if data type is `MetadataIntValue`
        if _data_type == "MetadataIntValue":
            instance.actual_instance = MetadataIntValue.from_json(json_str)
            return instance

        # check if data type is `MetadataProtoValue`
        if _data_type == "MetadataProtoValue":
            instance.actual_instance = MetadataProtoValue.from_json(json_str)
            return instance

        # check if data type is `MetadataStringValue`
        if _data_type == "MetadataStringValue":
            instance.actual_instance = MetadataStringValue.from_json(json_str)
            return instance

        # check if data type is `MetadataStructValue`
        if _data_type == "MetadataStructValue":
            instance.actual_instance = MetadataStructValue.from_json(json_str)
            return instance

        # deserialize data into MetadataIntValue
        try:
            instance.actual_instance = MetadataIntValue.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into MetadataDoubleValue
        try:
            instance.actual_instance = MetadataDoubleValue.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into MetadataStringValue
        try:
            instance.actual_instance = MetadataStringValue.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into MetadataStructValue
        try:
            instance.actual_instance = MetadataStructValue.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into MetadataProtoValue
        try:
            instance.actual_instance = MetadataProtoValue.from_json(json_str)
            match += 1
        except (ValidationError, ValueError) as e:
            error_messages.append(str(e))
        # deserialize data into MetadataBoolValue
        try:
            instance.actual_instance = MetadataBoolValue.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 MetadataValue with oneOf schemas: MetadataBoolValue, MetadataDoubleValue, MetadataIntValue, MetadataProtoValue, MetadataStringValue, MetadataStructValue. Details: "
                + ", ".join(error_messages)
            )
        if match == 0:
            # no match
            raise ValueError(
                "No match found when deserializing the JSON string into MetadataValue with oneOf schemas: MetadataBoolValue, MetadataDoubleValue, MetadataIntValue, MetadataProtoValue, MetadataStringValue, MetadataStructValue. 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]
        | MetadataBoolValue
        | MetadataDoubleValue
        | MetadataIntValue
        | MetadataProtoValue
        | MetadataStringValue
        | MetadataStructValue
        | 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())
