package tech.easyflow.ai.mcp;

import org.junit.Assert;
import org.junit.Test;
import tech.easyflow.ai.service.impl.McpServiceImpl;
import tech.easyflow.common.web.exceptions.BusinessException;

/**
 * {@link McpTransportType} 单元测试。
 */
public class McpTransportTypeTest {

    /**
     * 应兼容解析 MCP 配置中常见的连接方式文本。
     */
    @Test
    public void fromShouldParseSupportedTransportTypes() {
        Assert.assertEquals(McpTransportType.STDIO, McpTransportType.from("stdio"));
        Assert.assertEquals(McpTransportType.SSE, McpTransportType.from("sse"));
        Assert.assertEquals(McpTransportType.SSE, McpTransportType.from("http-sse"));
        Assert.assertEquals(McpTransportType.HTTP, McpTransportType.from("http"));
        Assert.assertEquals(McpTransportType.HTTP, McpTransportType.from("http-stream"));
        Assert.assertEquals(McpTransportType.HTTP, McpTransportType.from("streamable-http"));
        Assert.assertEquals(McpTransportType.STDIO, McpTransportType.from(null));
        Assert.assertEquals(McpTransportType.STDIO, McpTransportType.from(" "));
    }

    /**
     * 应从 MCP 配置 JSON 中推断首个 server 的连接方式。
     */
    @Test
    public void getFirstMcpTransportTypeShouldInferFromConfigJson() {
        Assert.assertEquals("stdio", McpServiceImpl.getFirstMcpTransportType("""
                {"mcpServers":{"everything":{"command":"npx","args":["-y","@modelcontextprotocol/server-everything"]}}}
                """));
        Assert.assertEquals("http-sse", McpServiceImpl.getFirstMcpTransportType("""
                {"mcpServers":{"remote":{"transport":"http-sse","url":"http://127.0.0.1:3000/sse"}}}
                """));
        Assert.assertEquals("http-stream", McpServiceImpl.getFirstMcpTransportType("""
                {"mcpServers":{"remote":{"transport":"http-stream","url":"http://127.0.0.1:3000/mcp"}}}
                """));
    }

    /**
     * 不支持的连接方式应直接失败，避免保存无法启动的 MCP 配置。
     */
    @Test
    public void getFirstMcpTransportTypeShouldRejectUnsupportedTransportType() {
        try {
            McpServiceImpl.getFirstMcpTransportType("""
                    {"mcpServers":{"remote":{"transport":"websocket","url":"ws://127.0.0.1:3000/mcp"}}}
                    """);
            Assert.fail("expected BusinessException");
        } catch (BusinessException exception) {
            Assert.assertTrue(exception.getMessage().contains("不支持的 MCP 连接方式"));
        }
    }
}
