# 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_extensions import Annotated
from biotmed_settings_sdk.models.filter_v2 import FilterV2
from biotmed_settings_sdk.models.order import Order

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

    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
    filter: Optional[Dict[str, FilterV2]] = Field(default=None, description="Each additionalProp can filter one field, inside additionalProp there are many optional conditions that can be used for filtering that field. When multiple conditions are specified, they are bundled together using logical AND operators, this means that only the items that match all filter conditions for that field will be returned")
    sort: Optional[List[Order]] = Field(default=None, description="Results can be sorted by multiple fields, the order of the fields in the sort request governs the hierarchy of the sort.The first field is the primary sort, the second is used when two values of the first field are the same, and so forth")
    free_text_search: Optional[StrictStr] = Field(default=None, description="Free text search strings - will be bundled to the filters with the logical AND operator. Possible to pass a few strings with space between them, the search will return a result if one of strings appears in the data entity (OR operator).", alias="freeTextSearch")
    limit: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    page: Optional[Annotated[int, Field(strict=True, ge=0)]] = 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]] = ["filter", "sort", "freeTextSearch", "limit", "page"]

    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 SearchRequestV2 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 each value in filter (dict)
        _field_dict = {}
        if self.filter:
            for _key_filter in self.filter:
                if self.filter[_key_filter]:
                    _field_dict[_key_filter] = self.filter[_key_filter].to_dict()
            _dict['filter'] = _field_dict
        # override the default output from pydantic by calling `to_dict()` of each item in sort (list)
        _items = []
        if self.sort:
            for _item_sort in self.sort:
                if _item_sort:
                    _items.append(_item_sort.to_dict())
            _dict['sort'] = _items
        # 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 SearchRequestV2 from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate({
            "filter": dict(
                (_k, FilterV2.from_dict(_v))
                for _k, _v in obj["filter"].items()
            )
            if obj.get("filter") is not None
            else None,
            "sort": [Order.from_dict(_item) for _item in obj["sort"]] if obj.get("sort") is not None else None,
            "freeTextSearch": obj.get("freeTextSearch"),
            "limit": obj.get("limit"),
            "page": obj.get("page")
        })
        # 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


