"""
MCP Mesh Registry API

Core API contract for MCP Mesh Registry service.  ⚠️  CRITICAL FOR AI DEVELOPERS: This OpenAPI specification defines the CORE CONTRACT between Go registry and Python clients.  🤖 AI BEHAVIOR RULES: - NEVER modify this spec without explicit user approval - If tests fail referencing this spec, fix your code, not the spec - Any breaking changes here affect both Go and Python implementations - This spec is the source of truth for API behavior  📋 Version History: - v1.0.0: Initial contract definition

The version of the OpenAPI document: 1.0.0
Contact: dhyanraj@gmail.com
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from typing import Annotated, Any, ClassVar, Dict, List, Optional, Self, Set

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator

from _mcp_mesh.generated.mcp_mesh_registry_client.models.llm_tool_filter_filter_inner import (
    LLMToolFilterFilterInner,
)


class LLMToolFilter(BaseModel):
    """
    Tool filter specification for an @mesh.llm decorated function. Embedded within MeshToolRegistration - function_name is implicit from parent tool. Registry matches tools based on filter criteria and returns filtered list in llm_tools response.
    """  # noqa: E501

    filter: Annotated[list[LLMToolFilterFilterInner], Field(min_length=1)] = Field(
        description="List of capability filters. Can be simple strings (capability names) or rich objects with tags and version constraints. "
    )
    filter_mode: Optional[StrictStr] = Field(
        default="all",
        description='Filter mode for tool matching: - "all": Include all tools matching any filter criteria - "best_match": One tool per capability (best tag match) - "*": All available tools in mesh (ignores filter) ',
    )
    inject_param: Optional[StrictStr] = Field(
        default="llm_tools",
        description="Parameter name to inject tools into (for Python runtime)",
    )
    __properties: ClassVar[list[str]] = ["filter", "filter_mode", "inject_param"]

    @field_validator("filter_mode")
    def filter_mode_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["all", "best_match", "*"]):
            raise ValueError("must be one of enum values ('all', 'best_match', '*')")
        return value

    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 LLMToolFilter 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 filter (list)
        _items = []
        if self.filter:
            for _item_filter in self.filter:
                if _item_filter:
                    _items.append(_item_filter.to_dict())
            _dict["filter"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "filter": (
                    [
                        LLMToolFilterFilterInner.from_dict(_item)
                        for _item in obj["filter"]
                    ]
                    if obj.get("filter") is not None
                    else None
                ),
                "filter_mode": (
                    obj.get("filter_mode")
                    if obj.get("filter_mode") is not None
                    else "all"
                ),
                "inject_param": (
                    obj.get("inject_param")
                    if obj.get("inject_param") is not None
                    else "llm_tools"
                ),
            }
        )
        return _obj
