# 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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.retriever_execution_statistics import RetrieverExecutionStatistics
from typing import Optional, Set
from typing_extensions import Self

class ExecutionDetail(BaseModel):
    """
    Alias wrapper for execution detail documentation.
    """ # noqa: E501
    execution_id: StrictStr = Field(description="REQUIRED. Unique identifier for this execution run. Use this ID to track execution status, retrieve execution details, or query execution history. Format: 'exec_' prefix followed by alphanumeric token.")
    status: StrictStr = Field(description="REQUIRED. Execution status indicating current state. Common values: 'completed', 'failed', 'processing', 'pending'. Check this field to determine if execution succeeded or requires retry.")
    documents: Optional[List[Dict[str, Any]]] = Field(default=None, description="REQUIRED. Final document results after retriever completion. Contains documents that passed through all retriever stages. Each document may include: document_id, payload (full document data), score (relevance score), metadata (collection-specific fields), and any fields added by enrichment/join stages. Empty array indicates no documents matched the query criteria. Note: Legacy format may use 'final_results' instead of 'documents'.")
    pagination: Optional[Dict[str, Any]] = Field(default=None, description="REQUIRED. Pagination metadata structure. Format varies by pagination method: Offset pagination: {total, limit, offset, has_next, has_previous}, Cursor pagination: {cursor, has_next, page_size}, Keyset pagination: {next_cursor, has_next}. Use this to navigate through result pages.")
    stage_statistics: Optional[RetrieverExecutionStatistics] = Field(default=None, description="REQUIRED. Per-stage execution statistics including timing, document counts, cache hit rates, and stage-specific metrics. Use this to understand retriever performance and identify bottlenecks.")
    budget: Optional[Dict[str, Any]] = Field(default=None, description="REQUIRED. Budget usage snapshot for this execution. Contains: credits_used (credits consumed), credits_remaining (remaining budget), time_used_ms (execution time), and budget limits. Use this to track resource consumption and enforce budget limits.")
    error: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Retriever-level error message if execution failed. Only present when status='failed'. Contains human-readable error description to help diagnose the failure. Check stage_statistics for stage-specific errors.")
    optimization_applied: Optional[StrictBool] = Field(default=False, description="OPTIONAL. Whether automatic pipeline optimizations were applied before execution. Mixpeek automatically optimizes retrieval pipelines for performance by reordering stages, merging operations, and pushing work to the database layer. Optimizations preserve logical equivalence - you get the same results, just faster. When true, see optimization_summary for details about what changed.")
    optimization_summary: Optional[Dict[str, Any]] = Field(default=None, description="OPTIONAL. Summary of pipeline optimizations applied before execution. Only present when optimization_applied=true. Contains: - original_stage_count: Number of stages in your original pipeline - optimized_stage_count: Number of stages after optimization - optimization_time_ms: Time spent optimizing (typically <100ms) - rules_applied: List of optimization rules that fired - stage_reduction_pct: Percentage reduction in stage count Use this to understand how the optimizer improved your pipeline. See OptimizationRuleType enum for detailed rule descriptions.")
    created_at: Optional[datetime] = Field(default=None, description="Timestamp when execution began")
    completed_at: Optional[datetime] = Field(default=None, description="Timestamp when execution finished")
    current_stage: Optional[StrictStr] = Field(default=None, description="Stage currently running when execution in-flight")
    stages_completed: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="Number of stages finished so far")
    total_stages: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="Total stages configured")
    __properties: ClassVar[List[str]] = ["execution_id", "status", "documents", "pagination", "stage_statistics", "budget", "error", "optimization_applied", "optimization_summary", "created_at", "completed_at", "current_stage", "stages_completed", "total_stages"]

    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 ExecutionDetail 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,
        )
        # override the default output from pydantic by calling `to_dict()` of stage_statistics
        if self.stage_statistics:
            _dict['stage_statistics'] = self.stage_statistics.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "execution_id": obj.get("execution_id"),
            "status": obj.get("status"),
            "documents": obj.get("documents"),
            "pagination": obj.get("pagination"),
            "stage_statistics": RetrieverExecutionStatistics.from_dict(obj["stage_statistics"]) if obj.get("stage_statistics") is not None else None,
            "budget": obj.get("budget"),
            "error": obj.get("error"),
            "optimization_applied": obj.get("optimization_applied") if obj.get("optimization_applied") is not None else False,
            "optimization_summary": obj.get("optimization_summary"),
            "created_at": obj.get("created_at"),
            "completed_at": obj.get("completed_at"),
            "current_stage": obj.get("current_stage"),
            "stages_completed": obj.get("stages_completed") if obj.get("stages_completed") is not None else 0,
            "total_stages": obj.get("total_stages") if obj.get("total_stages") is not None else 0
        })
        return _obj


