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

"""Export helpers: UAP Agent/Tool → OpenAPI v3 spec (stub).

This minimal exporter converts each `Tool` into a single `POST` operation under
`/tools/{tool_name}` accepting JSON body and returning 200 with example schema.

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

from typing import Dict

from unifiedagentprotocol.models.agent import Agent
from unifiedagentprotocol.models.tool import Tool


def agent_to_openapi(agent: Agent) -> Dict:  # noqa: D401 ANN401
    """Return a very basic OpenAPI spec representing the agent's tools."""

    paths: Dict[str, Dict] = {}
    for tool in agent.tools:
        paths[f"/tools/{tool.name}"] = {
            "post": _tool_to_operation(tool)
        }

    return {
        "openapi": "3.0.3",
        "info": {"title": agent.name, "version": agent.version, "description": agent.description},
        "paths": paths,
        "components": {},
    }


def _tool_to_operation(tool: Tool) -> Dict:  # noqa: ANN401
    req_schema_props = {param.name: {"type": param.type} for param in tool.parameters}
    required = [p.name for p in tool.parameters if p.required]

    operation = {
        "summary": tool.description,
        "operationId": tool.name,
        "requestBody": {
            "required": True,
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": req_schema_props,
                        "required": required,
                    }
                }
            },
        },
        "responses": {
            "200": {
                "description": "Successful Response",
                "content": {
                    "application/json": {
                        "schema": tool.output.schema if tool.output else {"type": "object"}
                    }
                },
            }
        },
    }
    return operation
