# coding: utf-8

"""
    BioT Settings Service

    APIs document description for Settings service

    The version of the OpenAPI document: 2.44.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 pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional

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 ErrorResponse(BaseModel):
    """
    ErrorResponse

    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
    code: Optional[StrictStr] = None
    message: Optional[StrictStr] = None
    service_name: Optional[StrictStr] = Field(default=None, alias="serviceName")
    trace_id: Optional[StrictStr] = Field(default=None, alias="traceId")
    environment: Optional[StrictStr] = None
    details: Optional[Dict[str, Any]] = None
    # 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]] = ["code", "message", "serviceName", "traceId", "environment", "details"]

    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 ErrorResponse 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,
        )
        # 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 ErrorResponse from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate({
            "code": obj.get("code"),
            "message": obj.get("message"),
            "serviceName": obj.get("serviceName"),
            "traceId": obj.get("traceId"),
            "environment": obj.get("environment"),
            "details": obj.get("details")
        })
        # 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


