from mcp_integration.client import MCPClient

mcp_client = MCPClient()

async def safe_invoke_tool(tool_name: str, args: dict):
    """Invoca una herramienta MCP de forma segura con logs coloridos."""
    # Colores ANSI
    BLUE = "\033[94m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    RED = "\033[91m"
    RESET = "\033[0m"
    BOLD = "\033[1m"

    try:
        print(f"{BLUE}{BOLD}📡 [MCP REQUEST]{RESET} Tool: {YELLOW}{tool_name}{RESET} | Args: {args}", flush=True)
        
        tools = await mcp_client.get_tools_async() 
        tools_map = {t.name: t for t in tools}
        
        if tool_name not in tools_map:
            print(f"{RED}⚠️ Tool '{tool_name}' no encontrada.{RESET}", flush=True)
            return None
            
        # Importante: Algunos servidores esperan 'prompt' en lugar de 'query' o viceversa.
        # En AgrotaMcpTools.java, los argumentos se mapean directamente o por nombre si no es un POJO.
        # Pero si es un POJO 'Request', el MCP adapter lo maneja.
        # AgrotaMcpTools usa (String prompt, String userName, ...)
        
        response = await tools_map[tool_name].ainvoke(args)
        
        # Limpiar respuesta para el log
        content = response.content if hasattr(response, 'content') else response
        resp_str = str(content)[:200] if len(str(content)) > 200 else str(content)
        print(f"{GREEN}{BOLD}📥 [MCP RESPONSE]{RESET} Tool: {YELLOW}{tool_name}{RESET} | Data: {resp_str}", flush=True)
        
        return content
    except Exception as e:
        print(f"{RED}❌ Error invocando {tool_name}: {e}{RESET}", flush=True)
        return f"Error: {str(e)}"
