# 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.

"""LangChain → UAP Tool parser.

Assumes a simplified YAML/JSON representation of a LangChain `@tool` or `StructuredTool`
metadata, **not** live python objects – keeping this SDK pure-data.

Expected input format::

    {
        "name": "get_weather",
        "description": "Fetch weather by city",
        "args_schema": {
            "city": {"type": "string", "description": "City name"},
            "unit": {"type": "string", "enum": ["C", "F"], "default": "C"}
        },
        "return_schema": {"type": "object", ...}
    }

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

from typing import Any, Dict, List

from unifiedagentprotocol.models.tool import Tool, ToolParam, OutputSchema
from unifiedagentprotocol.models.common import Trigger


def parse_langchain(data: Dict[str, Any]) -> Tool:
    """Convert dict representation of LangChain tool into UAP Tool."""

    name = data.get("name")
    if not name:
        raise ValueError("LangChain tool must have a 'name'")

    description = data.get("description", "")

    params: List[ToolParam] = []
    for arg_name, spec in data.get("args_schema", {}).items():
        params.append(
            ToolParam(
                name=arg_name,
                type=spec.get("type", "string"),
                description=spec.get("description"),
                required=spec.get("required", True),
                default=spec.get("default"),
                enum=spec.get("enum"),
            )
        )

    output = None
    if "return_schema" in data:
        output = OutputSchema(schema=data["return_schema"])

    return Tool(
        name=name,
        description=description,
        parameters=params,
        output=output,
        triggers=[Trigger(type="manual")],
        metadata={k: v for k, v in data.items() if k not in {"name", "description", "args_schema", "return_schema"}},
    )
