# 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, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.aio.client.models.v1beta1_capacity_requirements import V1beta1CapacityRequirements
from kubernetes.aio.client.models.v1beta1_device_derived_attribute import V1beta1DeviceDerivedAttribute
from kubernetes.aio.client.models.v1beta1_device_selector import V1beta1DeviceSelector
from kubernetes.aio.client.models.v1beta1_device_sub_request import V1beta1DeviceSubRequest
from kubernetes.aio.client.models.v1beta1_device_toleration import V1beta1DeviceToleration
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 V1beta1DeviceRequest(BaseModel):
    """
    DeviceRequest is a request for devices required for a claim. This is typically a request for a single resource like a device, but can also ask for several identical devices.

    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
    admin_access: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("adminAccess", "admin_access"), serialization_alias="adminAccess", description="AdminAccess indicates that this is a claim for administrative access to the device(s). Claims with AdminAccess are expected to be used for monitoring or other management services for a device.  They ignore all ordinary claims to the device with respect to access modes and any resource allocations.  This field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.  This is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled.")
    allocation_mode: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("allocationMode", "allocation_mode"), serialization_alias="allocationMode", description="AllocationMode and its related fields define how devices are allocated to satisfy this request. Supported values are:  - ExactCount: This request is for a specific number of devices.   This is the default. The exact number is provided in the   count field.  - All: This request is for all of the matching devices in a pool.   At least one device must exist on the node for the allocation to succeed.   Allocation will fail if some devices are already allocated,   unless adminAccess is requested.  If AllocationMode is not specified, the default mode is ExactCount. If the mode is ExactCount and count is not specified, the default count is one. Any other requests must specify this field.  This field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.  More modes may get added in the future. Clients must refuse to handle requests with unknown modes.")
    capacity: Optional[V1beta1CapacityRequirements] = None
    count: Optional[StrictInt] = Field(default=None, description="Count is used only when the count mode is \"ExactCount\". Must be greater than zero. If AllocationMode is ExactCount and this field is not specified, the default is one.  This field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.")
    derived_attributes: Optional[List[V1beta1DeviceDerivedAttribute]] = Field(default=None, validation_alias=AliasChoices("derivedAttributes", "derived_attributes"), serialization_alias="derivedAttributes", description="DerivedAttributes defines a set of virtual attributes computed via CEL expressions for each candidate device. These virtual attributes can be referenced in `.devices.constraints` to align and match different devices (e.g., co-allocating a GPU and a NIC on the same NUMA node) even if their drivers publish different attributes. Derived attributes are not available via `device.attributes` in the CEL environment when evaluating selector expressions.  Derived attributes allow you to extract, transform, or normalize topology information (such as extracting a NUMA index from a complex topology string or renaming a vendor-specific attribute) into a common virtual attribute name at scheduling time. The scheduler then evaluates these virtual attributes exactly like static attributes when matching constraints.  Every derived attribute defined in this list must be referenced by at least one MatchAttribute or DistinctAttribute constraint in the `.devices.constraints` list.  The maximum number of derived attributes is 32.  This is an alpha field and requires enabling the DRADerivedAttributes feature gate.")
    device_class_name: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("deviceClassName", "device_class_name"), serialization_alias="deviceClassName", description="DeviceClassName references a specific DeviceClass, which can define additional configuration and selectors to be inherited by this request.  A class is required if no subrequests are specified in the firstAvailable list and no class can be set if subrequests are specified in the firstAvailable list. Which classes are available depends on the cluster.  Administrators may use this to restrict which devices may get requested by only installing classes with selectors for permitted devices. If users are free to request anything without restrictions, then administrators can create an empty DeviceClass for users to reference.")
    first_available: Optional[List[V1beta1DeviceSubRequest]] = Field(default=None, validation_alias=AliasChoices("firstAvailable", "first_available"), serialization_alias="firstAvailable", description="FirstAvailable contains subrequests, of which exactly one will be satisfied by the scheduler to satisfy this request. It tries to satisfy them in the order in which they are listed here. So if there are two entries in the list, the scheduler will only check the second one if it determines that the first one cannot be used.  This field may only be set in the entries of DeviceClaim.Requests.  DRA does not yet implement scoring, so the scheduler will select the first set of devices that satisfies all the requests in the claim. And if the requirements can be satisfied on more than one node, other scheduling features will determine which node is chosen. This means that the set of devices allocated to a claim might not be the optimal set available to the cluster. Scoring will be implemented later.")
    name: StrictStr = Field(description="Name can be used to reference this request in a pod.spec.containers[].resources.claims entry and in a constraint of the claim.  Must be a DNS label and unique among all DeviceRequests in a ResourceClaim.")
    selectors: Optional[List[V1beta1DeviceSelector]] = Field(default=None, description="Selectors define criteria which must be satisfied by a specific device in order for that device to be considered for this request. All selectors must be satisfied for a device to be considered.  This field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.")
    tolerations: Optional[List[V1beta1DeviceToleration]] = Field(default=None, description="If specified, the request's tolerations.  Tolerations for NoSchedule are required to allocate a device which has a taint with that effect. The same applies to NoExecute.  In addition, should any of the allocated devices get tainted with NoExecute after allocation and that effect is not tolerated, then all pods consuming the ResourceClaim get deleted to evict them. The scheduler will not let new pods reserve the claim while it has these tainted devices. Once all pods are evicted, the claim will get deallocated.  The maximum number of tolerations is 16.  This field can only be set when deviceClassName is set and no subrequests are specified in the firstAvailable list.  This is a beta field and requires enabling the DRADeviceTaints feature gate.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "admin_access": "bool",
        "allocation_mode": "str",
        "capacity": "V1beta1CapacityRequirements",
        "count": "int",
        "derived_attributes": "List[V1beta1DeviceDerivedAttribute]",
        "device_class_name": "str",
        "first_available": "List[V1beta1DeviceSubRequest]",
        "name": "str",
        "selectors": "List[V1beta1DeviceSelector]",
        "tolerations": "List[V1beta1DeviceToleration]"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "admin_access": "adminAccess",
        "allocation_mode": "allocationMode",
        "capacity": "capacity",
        "count": "count",
        "derived_attributes": "derivedAttributes",
        "device_class_name": "deviceClassName",
        "first_available": "firstAvailable",
        "name": "name",
        "selectors": "selectors",
        "tolerations": "tolerations"
    }
    __properties: ClassVar[List[str]] = ["adminAccess", "allocationMode", "capacity", "count", "derivedAttributes", "deviceClassName", "firstAvailable", "name", "selectors", "tolerations"]

    @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 "adminAccess" not in obj and "admin_access" in obj:
            obj["adminAccess"] = obj["admin_access"]
        obj.pop("admin_access", None)
        if "allocationMode" not in obj and "allocation_mode" in obj:
            obj["allocationMode"] = obj["allocation_mode"]
        obj.pop("allocation_mode", None)
        if "derivedAttributes" not in obj and "derived_attributes" in obj:
            obj["derivedAttributes"] = obj["derived_attributes"]
        obj.pop("derived_attributes", None)
        if "deviceClassName" not in obj and "device_class_name" in obj:
            obj["deviceClassName"] = obj["device_class_name"]
        obj.pop("device_class_name", None)
        if "firstAvailable" not in obj and "first_available" in obj:
            obj["firstAvailable"] = obj["first_available"]
        obj.pop("first_available", 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, V1beta1DeviceRequest):
            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, V1beta1DeviceRequest):
            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 V1beta1DeviceRequest 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 {
            ("adminAccess" if serialize else "admin_access"): _to_legacy_value(getattr(self, "admin_access", None), serialize),
            ("allocationMode" if serialize else "allocation_mode"): _to_legacy_value(getattr(self, "allocation_mode", None), serialize),
            ("capacity" if serialize else "capacity"): _to_legacy_value(getattr(self, "capacity", None), serialize),
            ("count" if serialize else "count"): _to_legacy_value(getattr(self, "count", None), serialize),
            ("derivedAttributes" if serialize else "derived_attributes"): _to_legacy_value(getattr(self, "derived_attributes", None), serialize),
            ("deviceClassName" if serialize else "device_class_name"): _to_legacy_value(getattr(self, "device_class_name", None), serialize),
            ("firstAvailable" if serialize else "first_available"): _to_legacy_value(getattr(self, "first_available", None), serialize),
            ("name" if serialize else "name"): _to_legacy_value(getattr(self, "name", None), serialize),
            ("selectors" if serialize else "selectors"): _to_legacy_value(getattr(self, "selectors", None), serialize),
            ("tolerations" if serialize else "tolerations"): _to_legacy_value(getattr(self, "tolerations", 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 capacity
        if self.capacity:
            _dict['capacity'] = _to_openapi_value(self.capacity)
        # override the default output from pydantic by calling `to_dict()` of each item in derived_attributes (list)
        _items = []
        if self.derived_attributes:
            for _item_derived_attributes in self.derived_attributes:
                _items.append(_to_openapi_value(_item_derived_attributes) if _item_derived_attributes is not None else None)
            _dict['derivedAttributes'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in first_available (list)
        _items = []
        if self.first_available:
            for _item_first_available in self.first_available:
                _items.append(_to_openapi_value(_item_first_available) if _item_first_available is not None else None)
            _dict['firstAvailable'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in selectors (list)
        _items = []
        if self.selectors:
            for _item_selectors in self.selectors:
                _items.append(_to_openapi_value(_item_selectors) if _item_selectors is not None else None)
            _dict['selectors'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in tolerations (list)
        _items = []
        if self.tolerations:
            for _item_tolerations in self.tolerations:
                _items.append(_to_openapi_value(_item_tolerations) if _item_tolerations is not None else None)
            _dict['tolerations'] = _items
        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 V1beta1DeviceRequest 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({
            "adminAccess": obj.get("adminAccess"),
            "allocationMode": obj.get("allocationMode"),
            "capacity": V1beta1CapacityRequirements.from_dict(obj["capacity"]) if obj.get("capacity") is not None else None,
            "count": obj.get("count"),
            "derivedAttributes": [V1beta1DeviceDerivedAttribute.from_dict(_item) for _item in obj["derivedAttributes"]] if obj.get("derivedAttributes") is not None else None,
            "deviceClassName": obj.get("deviceClassName"),
            "firstAvailable": [V1beta1DeviceSubRequest.from_dict(_item) for _item in obj["firstAvailable"]] if obj.get("firstAvailable") is not None else None,
            "name": obj.get("name"),
            "selectors": [V1beta1DeviceSelector.from_dict(_item) for _item in obj["selectors"]] if obj.get("selectors") is not None else None,
            "tolerations": [V1beta1DeviceToleration.from_dict(_item) for _item in obj["tolerations"]] if obj.get("tolerations") is not None else None
        })
        return _obj
