# 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: 0.81.1
    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, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from mixpeek.models.stage_defs_aggregation_function import StageDefsAggregationFunction
from typing import Optional, Set
from typing_extensions import Self

class StageDefsAggregationOperation(BaseModel):
    """
    Configuration for a single aggregation operation.  Defines what function to apply and on which field(s).  Examples:     Count documents:         ```json         {\"function\": \"count\", \"alias\": \"total\"}         ```      Sum a numeric field:         ```json         {\"function\": \"sum\", \"field\": \"metadata.views\", \"alias\": \"total_views\"}         ```      Count distinct values:         ```json         {\"function\": \"count_distinct\", \"field\": \"metadata.author\", \"alias\": \"unique_authors\"}         ```
    """ # noqa: E501
    function: StageDefsAggregationFunction = Field(description="REQUIRED. Aggregation function to apply. count/count_distinct: Count documents or unique values. sum/avg/min/max: Numeric aggregations on a field. first/last: Get first or last value (by score order). collect/collect_distinct: Gather values into a list.")
    var_field: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Field path to aggregate (dot notation supported). Required for: sum, avg, min, max, count_distinct, first, last, collect, collect_distinct. Not needed for: count (counts documents). Examples: 'score', 'metadata.views', 'payload.price'.", alias="field")
    alias: StrictStr = Field(description="REQUIRED. Name for this aggregation result in the output. Must be unique within the stage configuration. Used as the key in the aggregation results.")
    __properties: ClassVar[List[str]] = ["function", "field", "alias"]

    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 StageDefsAggregationOperation 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,
        )
        return _dict

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

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

        _obj = cls.model_validate({
            "function": obj.get("function"),
            "field": obj.get("field"),
            "alias": obj.get("alias")
        })
        return _obj


