# 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, 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 StageParamsSample(BaseModel):
    """
    Configuration for document sampling.  **Stage Category**: REDUCE  **Transformation**: N documents → M documents (where M ≤ N)  **Purpose**: Sample a subset of documents using random or stratified sampling. Operates on in-memory results from previous stages.  **When to Use**:     - A/B testing different pipeline configurations     - Reducing result set for expensive downstream stages     - Exploration and discovery features     - Ensuring proportional representation across categories     - Creating reproducible experiments with seeded sampling  **When NOT to Use**:     - When you need all results (just use previous stage output)     - For ranking/reordering (use SORT stages)     - For filtering by criteria (use FILTER stages)  **Sampling Strategies**:     - `random`: Uniform random sampling     - `stratified`: Proportional sampling across a field's values     - `reservoir`: Reservoir sampling (for streaming scenarios)  **Common Pipeline Position**: feature_search → (expensive stages) → sample  Examples:     Basic random sampling:         ```json         {             \"count\": 10,             \"strategy\": \"random\"         }         ```      Stratified sampling by category:         ```json         {             \"count\": 20,             \"strategy\": \"stratified\",             \"stratify_by\": \"metadata.category\"         }         ```      Reproducible sampling with seed:         ```json         {             \"count\": 50,             \"strategy\": \"random\",             \"seed\": 42         }         ```      Preserve top results, sample rest:         ```json         {             \"count\": 10,             \"strategy\": \"random\",             \"preserve_top_k\": 3         }         ```
    """ # noqa: E501
    count: Optional[Annotated[int, Field(le=1000, strict=True, ge=1)]] = Field(default=10, description="REQUIRED. Number of documents to sample. If count > available documents, returns all documents.")
    strategy: Optional[StrictStr] = Field(default='random', description="OPTIONAL. Sampling strategy: - 'random': Uniform random sampling (default) - 'stratified': Proportional sampling across stratify_by field values - 'reservoir': Reservoir sampling (memory-efficient for large sets)")
    stratify_by: Optional[StrictStr] = Field(default='null', description="OPTIONAL. Field to stratify on (required when strategy='stratified'). Samples proportionally from each unique value of this field. Supports dot notation for nested fields.")
    min_per_stratum: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=1, description="OPTIONAL. Minimum documents per stratum (stratified mode). Ensures each category gets at least this many documents.")
    seed: Optional[StrictInt] = Field(default=null, description="OPTIONAL. Random seed for reproducible sampling. Same seed + same input = same output. Leave None for non-deterministic sampling.")
    preserve_top_k: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="OPTIONAL. Always keep the top K documents by score, sample from remainder. Useful when you want to guarantee top results are included. Default: 0 (no preservation, sample from all).")
    __properties: ClassVar[List[str]] = ["count", "strategy", "stratify_by", "min_per_stratum", "seed", "preserve_top_k"]

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

        if value not in set(['random', 'stratified', 'reservoir']):
            raise ValueError("must be one of enum values ('random', 'stratified', 'reservoir')")
        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 StageParamsSample 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 StageParamsSample from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate({
            "count": obj.get("count") if obj.get("count") is not None else 10,
            "strategy": obj.get("strategy") if obj.get("strategy") is not None else 'random',
            "stratify_by": obj.get("stratify_by") if obj.get("stratify_by") is not None else 'null',
            "min_per_stratum": obj.get("min_per_stratum") if obj.get("min_per_stratum") is not None else 1,
            "seed": obj.get("seed") if obj.get("seed") is not None else null,
            "preserve_top_k": obj.get("preserve_top_k") if obj.get("preserve_top_k") is not None else 0
        })
        return _obj


