"""
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 datetime import datetime
from typing import Annotated, Any, ClassVar, Dict, List, Optional, Self, Set

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

from _mcp_mesh.generated.mcp_mesh_registry_client.models.mesh_tool_registration import (
    MeshToolRegistration,
)


class MeshAgentRegistration(BaseModel):
    """
    Service registration request with flattened structure. Used by both /agents/register and /heartbeat endpoints. Supports both agents (agent_type=mcp_agent) and API services (agent_type=api).
    """  # noqa: E501

    agent_id: Annotated[str, Field(min_length=1, strict=True, max_length=64)] = Field(
        description="Unique identifier for the agent"
    )
    agent_type: Optional[StrictStr] = Field(
        default="mcp_agent",
        description="Type of service - mcp_agent provides capabilities, api consumes them",
    )
    name: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=64)]] = (
        Field(
            default=None, description="Human-readable agent name (defaults to agent_id)"
        )
    )
    version: Optional[StrictStr] = Field(default="1.0.0", description="Agent version")
    http_host: Optional[StrictStr] = Field(
        default="0.0.0.0", description="HTTP host for agent endpoint"
    )
    http_port: Optional[StrictInt] = Field(
        default=0, description="HTTP port for agent endpoint (0 for stdio)"
    )
    timestamp: Optional[datetime] = Field(
        default=None, description="Registration/heartbeat timestamp"
    )
    namespace: Optional[StrictStr] = Field(
        default="default", description="Agent namespace for organization"
    )
    tools: Annotated[list[MeshToolRegistration], Field(min_length=1)] = Field(
        description="Array of tools provided by this agent (@mesh.tool functions). Tools can optionally include llm_filter if decorated with @mesh.llm. "
    )
    __properties: ClassVar[list[str]] = [
        "agent_id",
        "agent_type",
        "name",
        "version",
        "http_host",
        "http_port",
        "timestamp",
        "namespace",
        "tools",
    ]

    @field_validator("agent_id")
    def agent_id_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if not re.match(r"^[a-zA-Z0-9_-]+$", value):
            raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9_-]+$/")
        return value

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

        if value not in set(["mcp_agent", "api"]):
            raise ValueError("must be one of enum values ('mcp_agent', 'api')")
        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 MeshAgentRegistration 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 tools (list)
        _items = []
        if self.tools:
            for _item_tools in self.tools:
                if _item_tools:
                    _items.append(_item_tools.to_dict())
            _dict["tools"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "agent_id": obj.get("agent_id"),
                "agent_type": (
                    obj.get("agent_type")
                    if obj.get("agent_type") is not None
                    else "mcp_agent"
                ),
                "name": obj.get("name"),
                "version": (
                    obj.get("version") if obj.get("version") is not None else "1.0.0"
                ),
                "http_host": (
                    obj.get("http_host")
                    if obj.get("http_host") is not None
                    else "0.0.0.0"
                ),
                "http_port": (
                    obj.get("http_port") if obj.get("http_port") is not None else 0
                ),
                "timestamp": obj.get("timestamp"),
                "namespace": (
                    obj.get("namespace")
                    if obj.get("namespace") is not None
                    else "default"
                ),
                "tools": (
                    [MeshToolRegistration.from_dict(_item) for _item in obj["tools"]]
                    if obj.get("tools") is not None
                    else None
                ),
            }
        )
        return _obj
