# 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
from typing_extensions import Annotated
from mixpeek.models.budget_limits import BudgetLimits
from mixpeek.models.retriever_input_schema_field_input import RetrieverInputSchemaFieldInput
from mixpeek.models.stage_config import StageConfig
from typing import Optional, Set
from typing_extensions import Self

class AdhocExecuteRequest(BaseModel):
    """
    Request to execute a retriever ad-hoc without persistence.  This combines retriever creation parameters with execution inputs to allow one-time retrieval without saving the retriever configuration.  Use Cases:     - One-time queries without polluting retriever registry     - Testing retriever configurations before persisting     - Dynamic retrieval with varying stage configurations     - Temporary search operations  Behavior:     - Retriever is NOT saved to database     - Execution history is logged but marked as ad-hoc     - Response includes X-Execution-Mode: adhoc header     - execution_metadata.retriever_persisted = False  Streaming Execution (stream=True):     When streaming is enabled, the response uses Server-Sent Events (SSE) format     with Content-Type: text/event-stream. Each stage emits events as it executes:      Event Types:     - stage_start: Emitted when a stage begins execution     - stage_complete: Emitted when a stage finishes with results     - stage_error: Emitted if a stage encounters an error     - execution_complete: Emitted after all stages finish successfully     - execution_error: Emitted if the entire execution fails      Each event is a StreamStageEvent containing:     - event_type: The type of event     - execution_id: Unique execution identifier     - stage_name: Human-readable stage name     - stage_index: Zero-based stage position     - total_stages: Total number of stages     - documents: Intermediate results (for stage_complete)     - statistics: Stage metrics (duration_ms, input_count, output_count, etc.)     - budget_used: Cumulative resource consumption (credits, time, tokens)      Response Headers (streaming):     - Content-Type: text/event-stream     - Cache-Control: no-cache     - Connection: keep-alive     - X-Execution-Mode: adhoc      Example streaming request:     ```python     response = requests.post(         '/v1/retrievers/execute',         json={             'collection_identifiers': ['my_collection'],             'input_schema': {'query': {'type': 'text', 'required': True}},             'stages': [...],             'inputs': {'query': 'machine learning'},             'stream': True         },         stream=True     )     for line in response.iter_lines():         if line.startswith(b'data: '):             event = json.loads(line[6:])             print(f\"{event['event_type']}: {event.get('stage_name')}\")     ```  Standard Execution (stream=False, default):     Returns a single ExecuteRetrieverResponse with final documents,     pagination, and aggregate statistics after all stages complete.  Examples:     Simple ad-hoc search:         {             \"collection_identifiers\": [\"col_123\"],             \"input_schema\": {\"query\": {\"type\": \"text\", \"required\": True}},             \"stages\": [{                 \"stage_name\": \"search\",                 \"stage_type\": \"filter\",                 \"config\": {                     \"stage_id\": \"feature_search\",                     \"parameters\": {                         \"searches\": [{                             \"feature_uri\": \"mixpeek://text_extractor@v1/embedding\",                             \"query\": {                                 \"input_mode\": \"text\",                                 \"text\": \"{{INPUT.query}}\"                             },                             \"top_k\": 100                         }],                         \"final_top_k\": 10                     }                 }             }],             \"inputs\": {\"query\": \"machine learning\"},             \"stream\": false         }
    """ # noqa: E501
    collection_identifiers: Optional[List[StrictStr]] = Field(default=None, description="Collection identifiers (names or IDs) to query. Can be collection names or IDs. Names are automatically resolved. Can be empty for query-only inference mode (e.g., LLM query analysis without documents).")
    input_schema: Dict[str, RetrieverInputSchemaFieldInput] = Field(description="REQUIRED. Input schema defining expected inputs. Each key is an input name, value is a RetrieverInputSchemaField.")
    stages: Annotated[List[StageConfig], Field(min_length=1)] = Field(description="REQUIRED. Ordered list of stage configurations. At least one stage is required for execution.")
    inputs: Dict[str, Any] = Field(description="REQUIRED. Input values matching the input_schema. These values are passed to stages for parameterization.")
    budget_limits: Optional[BudgetLimits] = Field(default=None, description="OPTIONAL. Budget limits for execution.")
    stream: Optional[StrictBool] = Field(default=False, description="Enable streaming execution to receive real-time stage updates via Server-Sent Events (SSE). NOT REQUIRED - defaults to False for standard execution.   When stream=True: - Response Content-Type: text/event-stream - Events emitted: stage_start, stage_complete, stage_error, execution_complete, execution_error - Each event is formatted as: data: {json}\\n\\n - StreamStageEvent contains: event_type, execution_id, stage_name, stage_index, total_stages, documents (intermediate), statistics, budget_used   When to use streaming: - Progress tracking for multi-stage pipelines - Displaying intermediate results as stages complete - Real-time budget and performance monitoring - Debugging pipeline execution   When to skip streaming: - Single-stage or fast pipelines (<100ms) - No need for intermediate results - Minimizing overhead is critical")
    __properties: ClassVar[List[str]] = ["collection_identifiers", "input_schema", "stages", "inputs", "budget_limits", "stream"]

    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 AdhocExecuteRequest 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 each value in input_schema (dict)
        _field_dict = {}
        if self.input_schema:
            for _key_input_schema in self.input_schema:
                if self.input_schema[_key_input_schema]:
                    _field_dict[_key_input_schema] = self.input_schema[_key_input_schema].to_dict()
            _dict['input_schema'] = _field_dict
        # override the default output from pydantic by calling `to_dict()` of each item in stages (list)
        _items = []
        if self.stages:
            for _item_stages in self.stages:
                if _item_stages:
                    _items.append(_item_stages.to_dict())
            _dict['stages'] = _items
        # override the default output from pydantic by calling `to_dict()` of budget_limits
        if self.budget_limits:
            _dict['budget_limits'] = self.budget_limits.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "collection_identifiers": obj.get("collection_identifiers"),
            "input_schema": dict(
                (_k, RetrieverInputSchemaFieldInput.from_dict(_v))
                for _k, _v in obj["input_schema"].items()
            )
            if obj.get("input_schema") is not None
            else None,
            "stages": [StageConfig.from_dict(_item) for _item in obj["stages"]] if obj.get("stages") is not None else None,
            "inputs": obj.get("inputs"),
            "budget_limits": BudgetLimits.from_dict(obj["budget_limits"]) if obj.get("budget_limits") is not None else None,
            "stream": obj.get("stream") if obj.get("stream") is not None else False
        })
        return _obj


