# 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
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.join_mode import JoinMode
from mixpeek.models.logical_operator_input import LogicalOperatorInput
from mixpeek.models.retriever_model_input import RetrieverModelInput
from mixpeek.models.taxonomy_model_input import TaxonomyModelInput
from typing import Optional, Set
from typing_extensions import Self

class ExecuteTaxonomyRequest(BaseModel):
    """
    Request model for on-demand taxonomy validation and testing ONLY.  ⚠️ IMPORTANT: This endpoint is ONLY for testing taxonomy configuration with sample documents.  DO NOT USE THIS FOR BATCH ENRICHMENT: ❌ Do NOT use this to enrich an entire collection ❌ Do NOT use source_collection_id expecting batch processing ❌ Do NOT use target_collection_id expecting persistence  HOW TAXONOMY ENRICHMENT ACTUALLY WORKS: ✅ Automatic during ingestion: Attach taxonomies to collections via `taxonomy_applications` ✅ On-the-fly in retrieval: Add `taxonomy_join` stage to retriever pipelines  This endpoint validates: - Taxonomy configuration is correct - Retriever can find matching taxonomy nodes - Enrichment fields are properly applied  For production enrichment, see: - Collections API: attach taxonomies via `taxonomy_applications` field - Retrievers API: add `taxonomy_join` stage for on-the-fly enrichment
    """ # noqa: E501
    taxonomy: TaxonomyModelInput = Field(description="Full taxonomy model with configuration (fetched from DB by controller)")
    retriever: Optional[RetrieverModelInput] = Field(default=None, description="Optional retriever configuration override for testing. If omitted, uses the retriever configured in the taxonomy.")
    source_documents: Optional[List[Dict[str, Any]]] = Field(default=None, description="Sample documents to test enrichment (typically 1-5 docs). Results are returned immediately, not persisted. ⚠️ Do NOT pass collection_id expecting batch processing!")
    source_collection_id: Optional[StrictStr] = Field(default=None, description="⚠️ IGNORED IN ON_DEMAND MODE. This field exists for legacy compatibility only. To enrich collections, use taxonomy_applications on the collection.")
    target_collection_id: Optional[StrictStr] = Field(default=None, description="⚠️ IGNORED IN ON_DEMAND MODE. This field exists for legacy compatibility only. Results are never persisted via this endpoint.")
    join_mode: Optional[JoinMode] = Field(default=None, description="Must be 'on_demand'. BATCH mode is NOT supported via API. Batch enrichment is automatic (triggered by engine during ingestion).")
    batch_size: Optional[Annotated[int, Field(le=10000, strict=True, ge=1)]] = Field(default=1000, description="Batch size for the scroll iterator")
    scroll_filters: Optional[LogicalOperatorInput] = Field(default=None, description="Additional filters applied to the source collection prior to enrichment.")
    __properties: ClassVar[List[str]] = ["taxonomy", "retriever", "source_documents", "source_collection_id", "target_collection_id", "join_mode", "batch_size", "scroll_filters"]

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

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

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

        _obj = cls.model_validate({
            "taxonomy": TaxonomyModelInput.from_dict(obj["taxonomy"]) if obj.get("taxonomy") is not None else None,
            "retriever": RetrieverModelInput.from_dict(obj["retriever"]) if obj.get("retriever") is not None else None,
            "source_documents": obj.get("source_documents"),
            "source_collection_id": obj.get("source_collection_id"),
            "target_collection_id": obj.get("target_collection_id"),
            "join_mode": obj.get("join_mode"),
            "batch_size": obj.get("batch_size") if obj.get("batch_size") is not None else 1000,
            "scroll_filters": LogicalOperatorInput.from_dict(obj["scroll_filters"]) if obj.get("scroll_filters") is not None else None
        })
        return _obj


