# Copyright 2025 WhoMeta Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tool models for UAP

Generated by WhoMeta Unified Agent Protocol SDK
"""
from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field, validator

from .common import Trigger, UIConfig


class ToolParam(BaseModel):
    """Definition of a single parameter accepted by a tool."""

    name: str
    type: str = Field(..., description="Primitive or complex type name (string, int, file …)")
    description: Optional[str] = None
    required: bool = True
    default: Optional[Any] = None
    enum: Optional[List[Any]] = None

    class Config:
        extra = "allow"


class OutputSchema(BaseModel):
    """Simple wrapper around JSON Schema objects for output validation."""

    schema: Dict[str, Any] = Field(..., description="JSON Schema describing the response")

    @validator("schema")
    def must_be_object(cls, v: Dict[str, Any]):  # noqa: N805
        schema_type = v.get("type")
        # If no explicit type is given, assume 'object' (common when using $ref)
        if schema_type is None:
            return v
        if schema_type not in {"object", "array"}:
            raise ValueError(
                "Output schema root must be 'object' or 'array' (got %r)" % schema_type
            )
        return v


class Tool(BaseModel):
    """Represents an executable capability exposed by an agent."""

    name: str
    description: str
    parameters: List[ToolParam] = Field(default_factory=list)
    output: Optional[OutputSchema] = None
    triggers: List[Trigger] = Field(default_factory=list)
    ui: Optional[UIConfig] = None
    metadata: Dict[str, Any] = Field(default_factory=dict)

    class Config:
        extra = "allow"
        schema_extra = {
            "example": {
                "name": "get_weather",
                "description": "Fetch current weather by city name",
                "parameters": [
                    {
                        "name": "city",
                        "type": "string",
                        "description": "Target city",
                        "required": True,
                    }
                ],
            }
        }
