# 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, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.budget_limits import BudgetLimits
from mixpeek.models.feature_address import FeatureAddress
from mixpeek.models.retriever_input_schema_field_output import RetrieverInputSchemaFieldOutput
from mixpeek.models.stage_config import StageConfig
from typing import Optional, Set
from typing_extensions import Self

class RetrieverConfig(BaseModel):
    """
    Full retriever definition persisted in MongoDB.
    """ # noqa: E501
    retriever_id: Optional[StrictStr] = Field(default=None, description="Stable retriever identifier (REQUIRED).")
    retriever_name: Annotated[str, Field(min_length=1, strict=True)] = Field(description="Unique retriever name within namespace (REQUIRED).")
    description: Optional[StrictStr] = Field(default=None, description="Detailed description of retriever behaviour (OPTIONAL).")
    collection_ids: Optional[List[StrictStr]] = Field(default=None, description="Collections queried by the retriever. Can be empty for query-only inference mode.")
    stages: Annotated[List[StageConfig], Field(min_length=1)] = Field(description="Ordered list of stage configurations (REQUIRED).")
    input_schema: Optional[Dict[str, RetrieverInputSchemaFieldOutput]] = Field(default=None, description="JSON Schema describing expected user inputs (REQUIRED). Properties must use RetrieverInputSchemaField which supports all bucket types plus document_reference.")
    budget_limits: Optional[BudgetLimits] = Field(default=None, description="Execution budget limits for the retriever (OPTIONAL).")
    feature_dependencies: Optional[List[FeatureAddress]] = Field(default=None, description="Feature addresses required by stages (OPTIONAL, aids validation).")
    tags: Optional[List[StrictStr]] = Field(default=None, description="Arbitrary tags to help organise retrievers (OPTIONAL).")
    display_config: Optional[Dict[str, Any]] = Field(default=None, description="Display configuration for public retriever UI rendering (OPTIONAL). Defines how the search interface should appear when the retriever is published, including input fields, theme, layout, exposed result fields, and field formatting. This configuration is used as the default when publishing the retriever.")
    version: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=1, description="Version number that increments on each update (REQUIRED).")
    created_at: Optional[datetime] = Field(default=None, description="Creation timestamp in UTC (REQUIRED).")
    updated_at: Optional[datetime] = Field(default=None, description="Last update timestamp in UTC (REQUIRED).")
    created_by: Optional[StrictStr] = Field(default=None, description="Identifier of the user who created the retriever (OPTIONAL).")
    updated_by: Optional[StrictStr] = Field(default=None, description="Identifier of the user who last updated the retriever (OPTIONAL).")
    __properties: ClassVar[List[str]] = ["retriever_id", "retriever_name", "description", "collection_ids", "stages", "input_schema", "budget_limits", "feature_dependencies", "tags", "display_config", "version", "created_at", "updated_at", "created_by", "updated_by"]

    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 RetrieverConfig 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 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 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 budget_limits
        if self.budget_limits:
            _dict['budget_limits'] = self.budget_limits.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in feature_dependencies (list)
        _items = []
        if self.feature_dependencies:
            for _item_feature_dependencies in self.feature_dependencies:
                if _item_feature_dependencies:
                    _items.append(_item_feature_dependencies.to_dict())
            _dict['feature_dependencies'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "retriever_id": obj.get("retriever_id"),
            "retriever_name": obj.get("retriever_name"),
            "description": obj.get("description"),
            "collection_ids": obj.get("collection_ids"),
            "stages": [StageConfig.from_dict(_item) for _item in obj["stages"]] if obj.get("stages") is not None else None,
            "input_schema": dict(
                (_k, RetrieverInputSchemaFieldOutput.from_dict(_v))
                for _k, _v in obj["input_schema"].items()
            )
            if obj.get("input_schema") is not None
            else None,
            "budget_limits": BudgetLimits.from_dict(obj["budget_limits"]) if obj.get("budget_limits") is not None else None,
            "feature_dependencies": [FeatureAddress.from_dict(_item) for _item in obj["feature_dependencies"]] if obj.get("feature_dependencies") is not None else None,
            "tags": obj.get("tags"),
            "display_config": obj.get("display_config"),
            "version": obj.get("version") if obj.get("version") is not None else 1,
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at"),
            "created_by": obj.get("created_by"),
            "updated_by": obj.get("updated_by")
        })
        return _obj


