package org.dromara.ai.controller.app;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.ai.mcp.McpIntegrationService;
import org.dromara.ai.mcp.McpTool;
import org.dromara.ai.mcp.McpToolRegistry;
import org.dromara.common.core.domain.R;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * MCP工具控制器
 * 提供MCP（Model Context Protocol）工具的查询和调用接口
 *
 * @author pengles
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/ai/mcp")
@RequiredArgsConstructor
public class McpController {
    
    private final McpToolRegistry registry;
    private final McpIntegrationService mcpIntegrationService;

    /**
     * 获取所有已注册的MCP工具列表
     *
     * @return 工具列表
     */
    @GetMapping("/tools")
    @Operation(summary = "获取工具列表", description = "返回所有已注册的MCP工具及其信息")
    public R<Map<String, McpTool>> tools() {
        try {
            Map<String, McpTool> allTools = registry.all();
            log.debug("获取MCP工具列表，共{}个工具", allTools.size());
            return R.ok(allTools);
        } catch (Exception e) {
            log.error("获取MCP工具列表失败", e);
            return R.fail("获取工具列表失败: " + e.getMessage());
        }
    }

    /**
     * 调用指定的MCP工具
     *
     * @param name  工具名称
     * @param input 工具输入参数
     * @return 工具执行结果
     */
    @PostMapping("/invoke/{name}")
    @Operation(summary = "调用工具", description = "执行指定的MCP工具并返回结果")
    public R<Map<String, Object>> invoke(
            @Parameter(description = "工具名称", required = true)
            @PathVariable @NotBlank String name,
            @Parameter(description = "工具输入参数")
            @RequestBody(required = false) Map<String, Object> input) {
        try {
            log.info("调用MCP工具: {}, 输入参数: {}", name, input != null ? input.keySet() : "无");
            
            Map<String, Object> result = mcpIntegrationService.invokeTool(name, input != null ? input : Map.of());
            
            if (result.containsKey("error")) {
                log.warn("MCP工具调用失败: {}, 错误: {}", name, result.get("error"));
                return R.fail("工具调用失败: " + result.get("error"));
            }
            
            log.debug("MCP工具调用成功: {}", name);
            return R.ok(result);
        } catch (Exception e) {
            log.error("调用MCP工具失败: {}", name, e);
            return R.fail("工具调用失败: " + e.getMessage());
        }
    }
}
