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

class ExplainStagePlan(BaseModel):
    """
    Stage-level execution plan details for retriever explain endpoint.  Provides detailed cost, performance, and optimization information for a single stage in the retriever pipeline. Use this to understand stage behavior, identify bottlenecks, and troubleshoot performance issues.  This is analogous to a single row in MongoDB's explain plan output, showing how documents flow through the stage and what resources are consumed.
    """ # noqa: E501
    stage_index: Annotated[int, Field(strict=True, ge=0)] = Field(description="Zero-based position of this stage in the execution pipeline. Stages execute sequentially in this order. REQUIRED.")
    stage_name: StrictStr = Field(description="Human-readable name of this stage instance. Corresponds to the 'stage_name' field in your retriever configuration. Use this to map explain plan output back to your pipeline definition. REQUIRED.")
    stage_type: StrictStr = Field(description="Stage type identifier indicating the category of operation. Common types: 'filter' (reduce documents), 'sort' (reorder), 'reduce' (aggregate), 'apply' (transform/enrich). REQUIRED.")
    estimated_input: Annotated[int, Field(strict=True, ge=0)] = Field(description="Estimated number of documents entering this stage. This is the output count from the previous stage (or initial collection size). Used to project document flow through the pipeline. REQUIRED.")
    estimated_output: Annotated[int, Field(strict=True, ge=0)] = Field(description="Estimated number of documents leaving this stage. For filter stages, this is typically less than estimated_input. For sort/reduce stages, this may be the same or less. REQUIRED.")
    estimated_efficiency: Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]] = Field(description="Stage selectivity ratio (estimated_output / estimated_input). Values closer to 0 indicate aggressive filtering. Values closer to 1 indicate most documents pass through. Use this to identify stages that might be too restrictive or too permissive. REQUIRED.")
    estimated_cost_credits: Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]] = Field(description="Estimated credit cost for executing this stage. Credits are consumed for inference (embeddings, LLM calls), vector searches, and other computational operations. Filter/sort stages typically have near-zero cost. REQUIRED.")
    estimated_duration_ms: Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]] = Field(description="Estimated latency contribution of this stage in milliseconds. High values indicate potential bottlenecks. Sum across stages gives total estimated execution time. REQUIRED.")
    cache_likely: StrictBool = Field(description="Whether this stage is likely to hit cache based on recent execution history. True = cache hit likely (near-zero actual latency/cost). False = cache miss likely (full cost incurred). Use this to understand when queries will be fast vs slow. REQUIRED.")
    optimization_notes: Optional[List[StrictStr]] = Field(default=None, description="Human-readable notes about optimizations applied to this stage. Examples: 'Pushed down from stage 2', 'Merged with previous filter', 'Grouping pushed to database layer'. Empty if no optimizations were applied. OPTIONAL.")
    warnings: Optional[List[StrictStr]] = Field(default=None, description="Performance warnings or potential issues with this stage. Examples: 'High cost stage - consider reducing limit', 'Very low efficiency - may need filter tuning', 'LLM stage without prior filtering - expensive'. Empty if no warnings. OPTIONAL.")
    __properties: ClassVar[List[str]] = ["stage_index", "stage_name", "stage_type", "estimated_input", "estimated_output", "estimated_efficiency", "estimated_cost_credits", "estimated_duration_ms", "cache_likely", "optimization_notes", "warnings"]

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

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

        _obj = cls.model_validate({
            "stage_index": obj.get("stage_index"),
            "stage_name": obj.get("stage_name"),
            "stage_type": obj.get("stage_type"),
            "estimated_input": obj.get("estimated_input"),
            "estimated_output": obj.get("estimated_output"),
            "estimated_efficiency": obj.get("estimated_efficiency"),
            "estimated_cost_credits": obj.get("estimated_cost_credits"),
            "estimated_duration_ms": obj.get("estimated_duration_ms"),
            "cache_likely": obj.get("cache_likely"),
            "optimization_notes": obj.get("optimization_notes"),
            "warnings": obj.get("warnings")
        })
        return _obj


