# 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 StageParamsGroupBy(BaseModel):
    """
    Configuration for grouping documents by field value.  Stage Category: REDUCE  Transformation: N documents → M groups (where M ≤ N)  Purpose: Groups documents by a common field value, aggregating chunks back to parent objects. Essential for decompose/recompose workflows where chunks are searched individually then grouped to show context.  Performance: Runs in API layer (fast stage, ~10-50ms for 100-500 docs). Integrates with optimizer for filter push-down before grouping. Future optimization will push grouping into Qdrant for 10-100x speedup.  When to Use:     - After chunk-level search to group back to objects     - To deduplicate results by a field     - To aggregate related documents     - For decompose→search→recompose workflows     - Show top N results per category/author/parent  When NOT to Use:     - For initial document retrieval (use FILTER stages: hybrid_search)     - For ordering documents (use SORT stages: sort_relevance)     - For enriching documents (use APPLY stages: document_enrich)     - For expanding documents (use APPLY 1-N stages: taxonomy_enrich)  Operational Behavior:     - Fast stage: runs in API layer (no Engine delegation)     - In-memory grouping: Python dict-based grouping     - Groups documents with same field value     - Sorts within groups by score (highest first)     - Limits documents per group (configurable)     - Reports metrics to ClickHouse for learned optimizations  Common Pipeline Position: FILTER → SORT → REDUCE (this stage)  Requirements:     - group_by_field: REQUIRED     - max_per_group: OPTIONAL, defaults to 10     - output_mode: OPTIONAL, defaults to \"all\"  Use Cases:     - Decompose/recompose: Search 50 scenes, group to 10 videos     - Deduplication: Group by unique_id, keep top match     - Analytics: Group by category, show top docs per category     - Multi-tier results: Show top 3 products per brand  Examples:     - Group video scenes back to parent videos     - Deduplicate search results by product_id     - Show top 3 articles per author     - Display best match per category
    """ # noqa: E501
    group_by_field: Optional[StrictStr] = Field(default='source_object_id', description="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), 'root_object_id' (top-level ancestor in hierarchy), 'metadata.category' (nested categorical field), 'video_id' (media grouping), 'product_id' (e-commerce). Use dot notation for nested fields: 'metadata.user_id', 'lineage.source_id'. Performance: Indexed fields are faster for future Qdrant native grouping optimization. Template support: Use {{inputs.group_field}} for dynamic grouping.")
    max_per_group: Optional[Annotated[int, Field(le=1000, strict=True, ge=1)]] = Field(default=10, description="OPTIONAL. Maximum number of documents to keep per group. Documents are sorted by score (highest first) before limiting. Default: 10. Use 1 for deduplication (keeps only highest scoring doc per group). Use 3-5 for preview results (show top chunks per parent). Use 50+ for comprehensive results (show many chunks per parent). Performance: Lower values reduce response size and improve latency. Typical values: 1 (dedup), 5 (preview), 10 (default), 20 (detailed), 50 (comprehensive).")
    output_mode: Optional[StrictStr] = Field(default='all', description="OPTIONAL. Controls what documents are returned per group. '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'. Performance: 'first' is fastest (smallest response), 'all' preserves grouping, 'flatten' is lightest (no group metadata).")
    __properties: ClassVar[List[str]] = ["group_by_field", "max_per_group", "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 StageParamsGroupBy 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 StageParamsGroupBy 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_field": obj.get("group_by_field") if obj.get("group_by_field") is not None else 'source_object_id',
            "max_per_group": obj.get("max_per_group") if obj.get("max_per_group") is not None else 10,
            "output_mode": obj.get("output_mode") if obj.get("output_mode") is not None else 'all'
        })
        return _obj


