# coding: utf-8

"""
    Kubernetes

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

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

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


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from collections.abc import Mapping as _Mapping
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.client.models.v1alpha3_partition_type_status import V1alpha3PartitionTypeStatus
from kubernetes.client.models.v1alpha3_shareable_summary_status import V1alpha3ShareableSummaryStatus
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python


_OPENAPI_GENERATOR_TO_DICT = "_openapi_generator_to_dict"


def _get_openapi_to_dict(value: Any) -> Any:
    # Reciprocal function references preserve inherited generated methods
    # without reserving model member names. Checking both directions also
    # rejects overrides whose decorators copy function attributes.
    to_dict = getattr(value, "to_dict", None)
    type_to_dict = getattr(type(value), "to_dict", None)
    if (
        not callable(to_dict)
        or getattr(to_dict, "__func__", None) is not type_to_dict
    ):
        return None

    openapi_to_dict = getattr(
        type_to_dict, _OPENAPI_GENERATOR_TO_DICT, None
    )
    if (
        not callable(openapi_to_dict)
        or getattr(
            openapi_to_dict,
            _OPENAPI_GENERATOR_TO_DICT,
            None,
        ) is not type_to_dict
    ):
        return None
    return openapi_to_dict


def _to_legacy_item(value: Any, serialize: bool) -> Any:
    to_dict = getattr(value, "to_dict", None)
    if _get_openapi_to_dict(value) is not None and callable(to_dict):
        return to_dict(serialize=serialize)
    if callable(to_dict):
        return to_dict()
    return value


def _to_legacy_value(value: Any, serialize: bool) -> Any:
    # python-legacy converted only immediate list elements or dictionary values:
    # https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb49b45c940c2f694/modules/openapi-generator/src/main/resources/python-legacy/model.mustache#L203-L231
    if isinstance(value, list):
        return [_to_legacy_item(item, serialize) for item in value]
    if isinstance(value, dict):
        return {
            key: _to_legacy_item(item, serialize)
            for key, item in value.items()
        }
    return _to_legacy_item(value, serialize)


def _to_openapi_value(value: Any) -> Any:
    if isinstance(value, list):
        return [_to_openapi_value(item) for item in value]
    if isinstance(value, dict):
        return {key: _to_openapi_value(item) for key, item in value.items()}

    to_openapi_dict = _get_openapi_to_dict(value)
    if to_openapi_dict is not None:
        return to_openapi_dict(value)

    to_dict = getattr(value, "to_dict", None)
    if callable(to_dict):
        return to_dict()
    return value


class V1alpha3PoolStatus(BaseModel):
    """
    PoolStatus contains status information for a single resource pool.

    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """ # noqa: E501
    allocated_devices: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("allocatedDevices", "allocated_devices"), serialization_alias="allocatedDevices", description="AllocatedDevices is the number of devices currently allocated to claims. A value of 0 means no devices are allocated. May be unset when validationError is set.")
    available_devices: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("availableDevices", "available_devices"), serialization_alias="availableDevices", description="AvailableDevices is the number of devices available for allocation. This equals TotalDevices - AllocatedDevices - UnavailableDevices. A value of 0 means no devices are currently available. May be unset when validationError is set.")
    driver: StrictStr = Field(description="Driver is the DRA driver name for this pool. Must be a DNS subdomain (e.g., \"gpu.example.com\").")
    generation: StrictInt = Field(description="Generation is the pool generation observed across all ResourceSlices in this pool. Only the latest generation is reported. During a generation rollout, if not all slices at the latest generation have been published, the pool is included with a validationError and device counts unset.")
    node_name: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("nodeName", "node_name"), serialization_alias="nodeName", description="NodeName is the node this pool is associated with. When omitted, the pool is not associated with a specific node. Must be a valid DNS subdomain name (RFC1123).")
    partition_summary: Optional[List[V1alpha3PartitionTypeStatus]] = Field(default=None, validation_alias=AliasChoices("partitionSummary", "partition_summary"), serialization_alias="partitionSummary", description="PartitionSummary reports allocatability per (attribute, partition type) for a partitionable pool that publishes SharedCounters. Each entry names the grouping attribute it was resolved from: the PartitionTypeAttribute declared by a device's own slice, or for devices whose slice declares none, the default named in the request. A pool that mixes partitions declared under different attributes reports each independently. When no slice declares an attribute and the request names no default, the pool reports no partition summary.")
    pool_name: StrictStr = Field(validation_alias=AliasChoices("poolName", "pool_name"), serialization_alias="poolName", description="PoolName is the name of the pool. Must be a valid resource pool name (DNS subdomains separated by \"/\").")
    resource_slice_count: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("resourceSliceCount", "resource_slice_count"), serialization_alias="resourceSliceCount", description="ResourceSliceCount is the number of ResourceSlices that make up this pool. May be unset when validationError is set.")
    shareable_summary: Optional[V1alpha3ShareableSummaryStatus] = Field(default=None, validation_alias=AliasChoices("shareableSummary", "shareable_summary"), serialization_alias="shareableSummary")
    total_devices: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("totalDevices", "total_devices"), serialization_alias="totalDevices", description="TotalDevices is the total number of devices in the pool across all slices. A value of 0 means the pool has no devices. May be unset when validationError is set.")
    unavailable_devices: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("unavailableDevices", "unavailable_devices"), serialization_alias="unavailableDevices", description="UnavailableDevices is the number of devices that are not available due to taints or other conditions, but are not allocated. A value of 0 means all unallocated devices are available. May be unset when validationError is set.")
    validation_error: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("validationError", "validation_error"), serialization_alias="validationError", description="ValidationError is set when the pool's data could not be fully validated (e.g., incomplete slice publication). When set, device count fields and ResourceSliceCount may be unset.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "allocated_devices": "int",
        "available_devices": "int",
        "driver": "str",
        "generation": "int",
        "node_name": "str",
        "partition_summary": "List[V1alpha3PartitionTypeStatus]",
        "pool_name": "str",
        "resource_slice_count": "int",
        "shareable_summary": "V1alpha3ShareableSummaryStatus",
        "total_devices": "int",
        "unavailable_devices": "int",
        "validation_error": "str"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "allocated_devices": "allocatedDevices",
        "available_devices": "availableDevices",
        "driver": "driver",
        "generation": "generation",
        "node_name": "nodeName",
        "partition_summary": "partitionSummary",
        "pool_name": "poolName",
        "resource_slice_count": "resourceSliceCount",
        "shareable_summary": "shareableSummary",
        "total_devices": "totalDevices",
        "unavailable_devices": "unavailableDevices",
        "validation_error": "validationError"
    }
    __properties: ClassVar[List[str]] = ["allocatedDevices", "availableDevices", "driver", "generation", "nodeName", "partitionSummary", "poolName", "resourceSliceCount", "shareableSummary", "totalDevices", "unavailableDevices", "validationError"]

    @classmethod
    def __preprocess_input_names(
        cls,
        obj: Any,
        remove_hidden_storage_names: bool = True,
    ) -> Any:
        if not isinstance(obj, _Mapping):
            return obj
        obj = dict(obj)
        if "allocatedDevices" not in obj and "allocated_devices" in obj:
            obj["allocatedDevices"] = obj["allocated_devices"]
        obj.pop("allocated_devices", None)
        if "availableDevices" not in obj and "available_devices" in obj:
            obj["availableDevices"] = obj["available_devices"]
        obj.pop("available_devices", None)
        if "nodeName" not in obj and "node_name" in obj:
            obj["nodeName"] = obj["node_name"]
        obj.pop("node_name", None)
        if "partitionSummary" not in obj and "partition_summary" in obj:
            obj["partitionSummary"] = obj["partition_summary"]
        obj.pop("partition_summary", None)
        if "poolName" not in obj and "pool_name" in obj:
            obj["poolName"] = obj["pool_name"]
        obj.pop("pool_name", None)
        if "resourceSliceCount" not in obj and "resource_slice_count" in obj:
            obj["resourceSliceCount"] = obj["resource_slice_count"]
        obj.pop("resource_slice_count", None)
        if "shareableSummary" not in obj and "shareable_summary" in obj:
            obj["shareableSummary"] = obj["shareable_summary"]
        obj.pop("shareable_summary", None)
        if "totalDevices" not in obj and "total_devices" in obj:
            obj["totalDevices"] = obj["total_devices"]
        obj.pop("total_devices", None)
        if "unavailableDevices" not in obj and "unavailable_devices" in obj:
            obj["unavailableDevices"] = obj["unavailable_devices"]
        obj.pop("unavailable_devices", None)
        if "validationError" not in obj and "validation_error" in obj:
            obj["validationError"] = obj["validation_error"]
        obj.pop("validation_error", None)
        return obj

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self) -> str:
        """For print and pprint"""
        return self.to_str()

    def __eq__(self, other: object) -> bool:
        """Returns true if both objects are equal"""
        if not isinstance(other, V1alpha3PoolStatus):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other: object) -> bool:
        """Returns true if both objects are not equal"""
        if not isinstance(other, V1alpha3PoolStatus):
            return True

        return not (self == other)


    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        to_openapi_dict = _get_openapi_to_dict(self)
        if to_openapi_dict is not None:
            return json.dumps(to_jsonable_python(to_openapi_dict(self)))
        return json.dumps(to_jsonable_python(self.to_dict()))

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

    def to_dict(self, serialize: bool = False) -> Dict[str, Any]:
        """Return all declared model fields using public or wire names."""
        return {
            ("allocatedDevices" if serialize else "allocated_devices"): _to_legacy_value(getattr(self, "allocated_devices", None), serialize),
            ("availableDevices" if serialize else "available_devices"): _to_legacy_value(getattr(self, "available_devices", None), serialize),
            ("driver" if serialize else "driver"): _to_legacy_value(getattr(self, "driver", None), serialize),
            ("generation" if serialize else "generation"): _to_legacy_value(getattr(self, "generation", None), serialize),
            ("nodeName" if serialize else "node_name"): _to_legacy_value(getattr(self, "node_name", None), serialize),
            ("partitionSummary" if serialize else "partition_summary"): _to_legacy_value(getattr(self, "partition_summary", None), serialize),
            ("poolName" if serialize else "pool_name"): _to_legacy_value(getattr(self, "pool_name", None), serialize),
            ("resourceSliceCount" if serialize else "resource_slice_count"): _to_legacy_value(getattr(self, "resource_slice_count", None), serialize),
            ("shareableSummary" if serialize else "shareable_summary"): _to_legacy_value(getattr(self, "shareable_summary", None), serialize),
            ("totalDevices" if serialize else "total_devices"): _to_legacy_value(getattr(self, "total_devices", None), serialize),
            ("unavailableDevices" if serialize else "unavailable_devices"): _to_legacy_value(getattr(self, "unavailable_devices", None), serialize),
            ("validationError" if serialize else "validation_error"): _to_legacy_value(getattr(self, "validation_error", None), serialize),
        }

    def __openapi_generator_modern_projection(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 each item in partition_summary (list)
        _items = []
        if self.partition_summary:
            for _item_partition_summary in self.partition_summary:
                _items.append(_to_openapi_value(_item_partition_summary) if _item_partition_summary is not None else None)
            _dict['partitionSummary'] = _items
        # override the default output from pydantic by calling `to_dict()` of shareable_summary
        if self.shareable_summary:
            _dict['shareableSummary'] = _to_openapi_value(self.shareable_summary)
        return _dict

    setattr(
        to_dict,
        _OPENAPI_GENERATOR_TO_DICT,
        __openapi_generator_modern_projection,
    )
    setattr(
        __openapi_generator_modern_projection,
        _OPENAPI_GENERATOR_TO_DICT,
        to_dict,
    )
    del __openapi_generator_modern_projection

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

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

        obj = _cast(
            Dict[str, Any],
            cls.__preprocess_input_names(
                obj,
                remove_hidden_storage_names=True,
            ),
        )

        _obj = cls.model_validate({
            "allocatedDevices": obj.get("allocatedDevices"),
            "availableDevices": obj.get("availableDevices"),
            "driver": obj.get("driver"),
            "generation": obj.get("generation"),
            "nodeName": obj.get("nodeName"),
            "partitionSummary": [V1alpha3PartitionTypeStatus.from_dict(_item) for _item in obj["partitionSummary"]] if obj.get("partitionSummary") is not None else None,
            "poolName": obj.get("poolName"),
            "resourceSliceCount": obj.get("resourceSliceCount"),
            "shareableSummary": V1alpha3ShareableSummaryStatus.from_dict(obj["shareableSummary"]) if obj.get("shareableSummary") is not None else None,
            "totalDevices": obj.get("totalDevices"),
            "unavailableDevices": obj.get("unavailableDevices"),
            "validationError": obj.get("validationError")
        })
        return _obj
