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

"""Parser for OpenWebUI tool definitions → UAP Tool

This is a best-effort adapter – OpenWebUIʼs JSON schema is still evolving.

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

from typing import Any, Dict, List

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


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def parse_openwebui(data: Dict[str, Any]) -> Tool:
    """Convert an OpenWebUI JSON definition into a :class:`~uap.models.Tool`.

    Parameters
    ----------
    data:
        Loaded JSON object as produced by OpenWebUIʼs export.

    Returns
    -------
    Tool
        The equivalent UAP *Tool* instance.
    """

    name = data.get("name") or data.get("id")
    if not name:
        raise ValueError("OpenWebUI JSON must contain 'name' or 'id'")

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

    # ----------------------------- Parameters -----------------------------
    params: List[ToolParam] = []
    param_schema = data.get("parameters") or {}
    properties: Dict[str, Any] = param_schema.get("properties", {})
    required: List[str] = param_schema.get("required", [])

    for param_name, spec in properties.items():
        params.append(
            ToolParam(
                name=param_name,
                type=spec.get("type", "string"),
                description=spec.get("description"),
                required=param_name in required,
                default=spec.get("default"),
                enum=spec.get("enum"),
            )
        )

    # ----------------------------- Output -----------------------------
    output_schema_raw = data.get("returns") or {}
    output = None
    if output_schema_raw:
        output = OutputSchema(schema=output_schema_raw)

    # ----------------------------- Triggers & UI ----------------------
    triggers = [Trigger(type="manual")]  # default manual trigger
    if "trigger" in data:
        trig = data["trigger"]
        triggers = [Trigger(**trig)] if isinstance(trig, dict) else []

    ui_cfg = None
    if "ui" in data:
        ui_cfg = UIConfig(**data["ui"])

    return Tool(
        name=name,
        description=description,
        parameters=params,
        output=output,
        triggers=triggers,
        ui=ui_cfg,
        metadata={k: v for k, v in data.items() if k not in {"name", "id", "description", "parameters", "returns", "trigger", "ui"}},
    )
