# coding: utf-8

"""
    BioT Device Service

    APIs document (version: 8.9.1)

    The version of the OpenAPI document: 8.9.1
    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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from biotmed_device_sdk.models.basic_referenced_entity_data_uuidid import BasicReferencedEntityDataUUIDId
from biotmed_device_sdk.models.basic_template_data import BasicTemplateData
from biotmed_device_sdk.models.device_status import DeviceStatus
from biotmed_device_sdk.models.referenced_side_attribute_information import ReferencedSideAttributeInformation

from typing import Optional, Set
from typing_extensions import Self

# BioT Code Start: extra/custom attributes support imports
from typing import Any, Dict, ClassVar, List
from pydantic import Field, model_validator
# BioT Code End

class DeviceResponse(BaseModel):
    """
    DeviceResponse

    Note: This model supports custom attributes. Recommended access:
      - Pass custom fields via dict unpacking: Model(..., **{"custom_field": "value"})
      - Read custom fields via model.get("custom_field") or model["custom_field"]
    """ # noqa: E501
    description: Optional[StrictStr] = Field(default=None, description="Device description", alias="_description")
    timezone: Optional[StrictStr] = Field(default=None, description="A java time zone supported by the java runtime environment", alias="_timezone")
    id: StrictStr = Field(description="The id of the device", alias="_id")
    owner_organization: BasicReferencedEntityDataUUIDId = Field(alias="_ownerOrganization")
    template: Optional[BasicTemplateData] = Field(default=None, alias="_template")
    referencers: Optional[Dict[str, ReferencedSideAttributeInformation]] = Field(default=None, description="An object that contains all the referencers of this entity. Each referencer is the RSAN and it's an object that contains the count of the referrers, and information of the referrer (in case count = 1)", alias="_referencers")
    configuration: Optional[Dict[str, Any]] = Field(default=None, description="An object that holds the entity configuration attributes", alias="_configuration")
    status: Optional[DeviceStatus] = Field(default=None, alias="_status")
    patient: Optional[BasicReferencedEntityDataUUIDId] = Field(default=None, alias="_patient")
    registration_code: Optional[BasicReferencedEntityDataUUIDId] = Field(default=None, alias="_registrationCode")
    creation_time: datetime = Field(description="A UTC date-time in the ISO-8601 format", alias="_creationTime")
    last_modified_time: datetime = Field(description="A UTC date-time in the ISO-8601 format", alias="_lastModifiedTime")
    caption: StrictStr = Field(description="The caption of the command instance", alias="_caption")
    # BioT Code Start: Store custom attributes in a dedicated dict (safe default)
    additional_properties: Dict[str, Any] = Field(default_factory=dict)
    # BioT Code End
    __properties: ClassVar[List[str]] = ["_description", "_timezone", "_id", "_ownerOrganization", "_template", "_referencers", "_configuration", "_status", "_patient", "_registrationCode", "_creationTime", "_lastModifiedTime", "_caption"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
        # BioT Code Start: Allow extra fields for custom attributes
        extra='allow',
        # BioT Code End
    )

    # BioT Code Start: Sync Pydantic v2 extras into additional_properties
    @model_validator(mode='after')
    def _sync_additional_properties(self):
        """
        Sync unknown fields from Pydantic v2 `model_extra` into additional_properties.

        - When `extra='allow'`, unknown fields are stored in `model_extra`.
        - We copy them into additional_properties for OpenAPI Generator compatibility.
        """
        if self.model_extra:
            self.additional_properties.update(self.model_extra)
        return self
    # BioT Code End

    # BioT Code Start: Make dot-access to custom attributes type-check as Any (pyright-friendly)
    def __getattr__(self, item: str) -> Any:
        """
        Fallback for dynamic/custom attributes.

        This makes `model.some_custom_attr` resolve to `Any` in static type checkers
        instead of raising `reportUnknownMemberType`.
        """
        if item in self.additional_properties:
            return self.additional_properties[item]
        # also check model_extra directly (in case sync didn't run yet)
        if self.model_extra and item in self.model_extra:
            return self.model_extra[item]
        raise AttributeError(f"'{self.__class__.__name__}' has no field or custom property '{item}'")
    # BioT Code End

    # BioT Code Start: Dict-style access for custom attributes (and fields)
    def __getitem__(self, key: str) -> Any:
        """
        Support dict-style access:
          - defined fields by python name (e.g. 'name')
          - defined fields by alias (e.g. '_name') via to_dict fallback
          - custom attributes stored in additional_properties
        """
        if key in self.additional_properties:
            return self.additional_properties[key]
        if self.model_extra and key in self.model_extra:
            return self.model_extra[key]

        # Try direct attribute (python field name)
        if hasattr(self, key):
            try:
                return getattr(self, key)
            except AttributeError:
                pass

        # Try alias / serialized keys through to_dict()
        d = self.to_dict()
        if key in d:
            return d[key]

        raise KeyError(f"'{self.__class__.__name__}' has no field or custom property '{key}'")

    def get(self, key: str, default: Any = None) -> Any:
        """dict.get() style safe access."""
        try:
            return self[key]
        except KeyError:
            return default
    # BioT Code End

    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())

    # BioT Code Start: Override model_dump_json to flatten custom attributes to top level
    def model_dump_json(self, *, indent: Optional[int] = None, by_alias: bool = True, **kwargs: Any) -> str:
        """Return JSON representation with custom attributes flattened to top level."""
        json_kwargs = {k: v for k, v in kwargs.items()
                      if k not in ['by_alias', 'exclude', 'exclude_none', 'exclude_unset',
                                   'exclude_defaults', 'include', 'mode', 'round_trip',
                                   'warnings', 'serialize_as_any']}
        return json.dumps(self.to_dict(), indent=indent, default=str, **json_kwargs)
    # BioT Code End

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of DeviceResponse 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.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of owner_organization
        if self.owner_organization:
            _dict['_ownerOrganization'] = self.owner_organization.to_dict()
        # override the default output from pydantic by calling `to_dict()` of template
        if self.template:
            _dict['_template'] = self.template.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each value in referencers (dict)
        _field_dict = {}
        if self.referencers:
            for _key_referencers in self.referencers:
                if self.referencers[_key_referencers]:
                    _field_dict[_key_referencers] = self.referencers[_key_referencers].to_dict()
            _dict['_referencers'] = _field_dict
        # override the default output from pydantic by calling `to_dict()` of status
        if self.status:
            _dict['_status'] = self.status.to_dict()
        # override the default output from pydantic by calling `to_dict()` of patient
        if self.patient:
            _dict['_patient'] = self.patient.to_dict()
        # override the default output from pydantic by calling `to_dict()` of registration_code
        if self.registration_code:
            _dict['_registrationCode'] = self.registration_code.to_dict()
        # BioT Code Start: puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value
        # BioT Code End
        return _dict

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

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

        _obj = cls.model_validate({
            "_description": obj.get("_description"),
            "_timezone": obj.get("_timezone"),
            "_id": obj.get("_id"),
            "_ownerOrganization": BasicReferencedEntityDataUUIDId.from_dict(obj["_ownerOrganization"]) if obj.get("_ownerOrganization") is not None else None,
            "_template": BasicTemplateData.from_dict(obj["_template"]) if obj.get("_template") is not None else None,
            "_referencers": dict(
                (_k, ReferencedSideAttributeInformation.from_dict(_v))
                for _k, _v in obj["_referencers"].items()
            )
            if obj.get("_referencers") is not None
            else None,
            "_configuration": obj.get("_configuration"),
            "_status": DeviceStatus.from_dict(obj["_status"]) if obj.get("_status") is not None else None,
            "_patient": BasicReferencedEntityDataUUIDId.from_dict(obj["_patient"]) if obj.get("_patient") is not None else None,
            "_registrationCode": BasicReferencedEntityDataUUIDId.from_dict(obj["_registrationCode"]) if obj.get("_registrationCode") is not None else None,
            "_creationTime": obj.get("_creationTime"),
            "_lastModifiedTime": obj.get("_lastModifiedTime"),
            "_caption": obj.get("_caption")
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj


