# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 1.3.0
    Contact: info@mixpeek.com
    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, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.aggregation_operation import AggregationOperation
from mixpeek.models.group_by_field import GroupByField
from mixpeek.models.having_condition import HavingCondition
from mixpeek.models.range_bucket import RangeBucket
from typing import Optional, Set
from typing_extensions import Self

class ObjectAggregationRequest(BaseModel):
    """
    Aggregation request for bucket objects.  Extends the base AggregationRequest with object-specific context. Inherits all fields from AggregationRequest.  Requirements:     - group_by: REQUIRED, fields to group by     - aggregations: REQUIRED, aggregation operations to perform     - All other fields from AggregationRequest are available  Examples:     - Count objects by status     - Daily upload statistics     - Category-based analytics with filtering
    """ # noqa: E501
    group_by: Annotated[List[GroupByField], Field(min_length=1)] = Field(description="Fields to group results by. REQUIRED, at least one field. Can include field transformations (date_trunc, date_part). Results will have one row per unique combination of group_by values.")
    aggregations: Annotated[List[AggregationOperation], Field(min_length=1)] = Field(description="Aggregation operations to perform. REQUIRED, at least one operation. Each operation produces a calculated field in results. Can combine multiple functions (COUNT, SUM, AVG, etc.).")
    filters: Optional[Dict[str, Any]] = Field(default=None, description="Pre-aggregation filters to apply to source data. OPTIONAL, filters data before grouping. Uses same syntax as standard query filters. Applied before GROUP BY.")
    having: Optional[List[HavingCondition]] = Field(default=None, description="Post-aggregation filters to apply to results. OPTIONAL, filters groups after aggregation. Uses aggregation aliases as field names. Applied after GROUP BY and aggregation calculations.")
    unwind: Optional[StrictStr] = Field(default=None, description="Array field to unwind before aggregation. OPTIONAL, creates one document per array element. Useful for aggregating over array contents. Example: 'blobs' to analyze each blob separately.")
    range_buckets: Optional[List[RangeBucket]] = Field(default=None, description="Range-based bucketing for numeric fields. OPTIONAL, creates histogram-style buckets. Groups numeric values into defined ranges. Applied during grouping stage.")
    sort_by: Optional[StrictStr] = Field(default=None, description="Field to sort results by. OPTIONAL, can be group_by field or aggregation alias. Defaults to no specific order. Use with sort_direction to control order.")
    sort_direction: Optional[StrictStr] = Field(default='desc', description="Sort direction. OPTIONAL, defaults to 'desc' (descending). Valid values: 'asc' (ascending), 'desc' (descending). Used with sort_by field.")
    limit: Optional[StrictInt] = Field(default=None, description="Maximum number of results to return. OPTIONAL, no limit if not specified. Applied after sorting. Useful for 'top N' queries.")
    __properties: ClassVar[List[str]] = ["group_by", "aggregations", "filters", "having", "unwind", "range_buckets", "sort_by", "sort_direction", "limit"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


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

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of ObjectAggregationRequest 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.
        """
        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 group_by (list)
        _items = []
        if self.group_by:
            for _item_group_by in self.group_by:
                if _item_group_by:
                    _items.append(_item_group_by.to_dict())
            _dict['group_by'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in aggregations (list)
        _items = []
        if self.aggregations:
            for _item_aggregations in self.aggregations:
                if _item_aggregations:
                    _items.append(_item_aggregations.to_dict())
            _dict['aggregations'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in having (list)
        _items = []
        if self.having:
            for _item_having in self.having:
                if _item_having:
                    _items.append(_item_having.to_dict())
            _dict['having'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in range_buckets (list)
        _items = []
        if self.range_buckets:
            for _item_range_buckets in self.range_buckets:
                if _item_range_buckets:
                    _items.append(_item_range_buckets.to_dict())
            _dict['range_buckets'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "group_by": [GroupByField.from_dict(_item) for _item in obj["group_by"]] if obj.get("group_by") is not None else None,
            "aggregations": [AggregationOperation.from_dict(_item) for _item in obj["aggregations"]] if obj.get("aggregations") is not None else None,
            "filters": obj.get("filters"),
            "having": [HavingCondition.from_dict(_item) for _item in obj["having"]] if obj.get("having") is not None else None,
            "unwind": obj.get("unwind"),
            "range_buckets": [RangeBucket.from_dict(_item) for _item in obj["range_buckets"]] if obj.get("range_buckets") is not None else None,
            "sort_by": obj.get("sort_by"),
            "sort_direction": obj.get("sort_direction") if obj.get("sort_direction") is not None else 'desc',
            "limit": obj.get("limit")
        })
        return _obj


