# 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, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self

class FeatureSearchGroupBy(BaseModel):
    """
    Database-level grouping for feature search (uses Qdrant query_points_groups).  Enables efficient grouping at the database level rather than in-memory post-processing. Perfect for decompose/recompose patterns where you search chunks but want to return parent documents.  This mirrors the output_mode behavior of the group_by REDUCE stage for API consistency, but executes at the database level for better performance on large result sets.  Stage Category: FILTER (grouping is part of the Qdrant query)  Performance: Database-level grouping is significantly faster than fetching all results and grouping in memory. Qdrant handles the grouping natively.  Use Cases:     - Decompose/recompose: Search 500 text chunks, return top 25 unique documents     - Deduplication: One best result per product_id     - Scene → Video grouping: Search video frames, return parent videos  Examples:     Deduplication (one result per video):         ```json         {\"field\": \"video_id\", \"max_per_group\": 1, \"output_mode\": \"first\"}         ```      Top 3 chunks per document:         ```json         {\"field\": \"source_object_id\", \"max_per_group\": 3, \"output_mode\": \"all\"}         ```      Flatten grouped results:         ```json         {\"field\": \"category\", \"max_per_group\": 5, \"output_mode\": \"flatten\"}         ```
    """ # noqa: E501
    var_field: StrictStr = Field(description="REQUIRED. Field path to group documents by using dot notation. Documents with the same field value are grouped together. Common fields: 'source_object_id' (parent object from decomposition), 'video_id' (media grouping), 'product_id' (e-commerce), 'metadata.category' (nested categorical field). The field must exist in the document payload.", alias="field")
    max_per_group: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = Field(default=1, description="OPTIONAL. Maximum number of documents to keep per group (Qdrant's group_size). Documents are sorted by score (highest first) before limiting. Default: 1 (deduplication - keeps only highest scoring doc per group). Use 1 for deduplication, 3-5 for preview results, 10+ for comprehensive results. Note: This is a best-effort parameter in Qdrant.")
    limit: Optional[Annotated[int, Field(le=500, strict=True, ge=1)]] = Field(default=25, description="OPTIONAL. Maximum number of groups to return. This overrides final_top_k when grouping is enabled. Default: 25 groups.")
    output_mode: Optional[StrictStr] = Field(default='all', description="OPTIONAL. Controls what documents are returned per group. Mirrors the group_by REDUCE stage for API consistency. 'first': Return only the top document per group (deduplication, fastest).          Use for: unique results per group (e.g., one video per brand). 'all': Return all documents grouped by field (default, shows full context).        Use for: showing chunks within each parent object. 'flatten': Return all documents as flat list (loses group structure).            Use for: need all docs but don't care about grouping metadata. Default: 'all'.")
    __properties: ClassVar[List[str]] = ["field", "max_per_group", "limit", "output_mode"]

    @field_validator('output_mode')
    def output_mode_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['first', 'all', 'flatten']):
            raise ValueError("must be one of enum values ('first', 'all', 'flatten')")
        return value

    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 FeatureSearchGroupBy 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 FeatureSearchGroupBy from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate({
            "field": obj.get("field"),
            "max_per_group": obj.get("max_per_group") if obj.get("max_per_group") is not None else 1,
            "limit": obj.get("limit") if obj.get("limit") is not None else 25,
            "output_mode": obj.get("output_mode") if obj.get("output_mode") is not None else 'all'
        })
        return _obj


