package org.dromara.ai.mcp;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.ai.domain.dto.AiChatRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * MCP集成服务
 * 提供MCP工具与AI聊天请求的集成功能
 *
 * @author pengles
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class McpIntegrationService {
    
    private final McpToolRegistry registry;

    /**
     * 增强消息，添加可用工具信息
     *
     * @param request 聊天请求
     */
    public void enrichMessages(AiChatRequest request) {
        if (!Boolean.TRUE.equals(request.getEnableTools())) {
            return;
        }
        
        try {
            List<String> names = request.getRequestedTools() != null 
                    ? request.getRequestedTools() 
                    : new ArrayList<>(registry.all().keySet());
            
            if (names.isEmpty()) {
                log.debug("未找到可用的MCP工具");
                return;
            }
            
            StringBuilder sb = new StringBuilder();
            sb.append("可用工具: ").append(String.join(",", names));
            AiChatRequest.AiMessage sys = new AiChatRequest.AiMessage()
                    .setRole("system")
                    .setContent(sb.toString());
            
            List<AiChatRequest.AiMessage> msgs = new ArrayList<>();
            msgs.add(sys);
            if (request.getMessages() != null) {
                msgs.addAll(request.getMessages());
            }
            request.setMessages(msgs);
            
            log.debug("MCP工具消息增强完成 - 工具数量: {}", names.size());
        } catch (Exception e) {
            log.error("MCP工具消息增强失败", e);
            // 增强失败不影响主流程，只记录日志
        }
    }

    /**
     * 调用MCP工具
     *
     * @param name  工具名称
     * @param input 工具输入参数
     * @return 工具执行结果
     */
    public Map<String, Object> invokeTool(String name, Map<String, Object> input) {
        try {
            log.debug("调用MCP工具: {}, 输入参数: {}", name, input != null ? input.keySet() : "无");
            
            McpTool tool = registry.get(name);
            if (tool == null) {
                log.warn("MCP工具不存在: {}", name);
                return Map.of("error", "tool_not_found", "toolName", name);
            }
            
            Map<String, Object> result = tool.invoke(input != null ? input : Map.of());
            
            if (result != null && result.containsKey("error")) {
                log.warn("MCP工具调用失败: {}, 错误: {}", name, result.get("error"));
            } else {
                log.debug("MCP工具调用成功: {}", name);
            }
            
            return result;
        } catch (Exception e) {
            log.error("MCP工具调用异常: {}", name, e);
            return Map.of("error", "tool_invocation_error", "message", e.getMessage(), "toolName", name);
        }
    }
}
