package com.easyagents.agent.runtime.mcp;

import com.easyagents.agent.runtime.AgentRuntimeException;
import io.agentscope.core.tool.mcp.McpClientBuilder;
import io.agentscope.core.tool.mcp.McpClientWrapper;

import java.time.Duration;

/**
 * 创建 AgentScope MCP client。
 */
public class McpClientFactory {

    /**
     * 根据 MCP 运行时声明创建 AgentScope MCP client。
     *
     * @param spec MCP 运行时声明
     * @return AgentScope MCP client
     */
    public McpClientWrapper create(McpSpec spec) {
        McpSpecValidator.validateConnection(spec);
        McpClientBuilder builder = McpClientBuilder.create(spec.getName())
                .timeout(timeout(spec.getTimeout(), Duration.ofSeconds(120)))
                .initializationTimeout(timeout(spec.getInitializationTimeout(), Duration.ofSeconds(30)));
        switch (spec.getTransportType()) {
            case STDIO -> builder.stdioTransport(spec.getCommand(), spec.getArgs(), spec.getEnv());
            case SSE -> builder.sseTransport(spec.getUrl())
                    .headers(spec.getHeaders())
                    .queryParams(spec.getQueryParams());
            case HTTP -> builder.streamableHttpTransport(spec.getUrl())
                    .headers(spec.getHeaders())
                    .queryParams(spec.getQueryParams());
            default -> throw new AgentRuntimeException("Unsupported MCP transport type: " + spec.getTransportType());
        }
        return builder.buildAsync().block();
    }

    private Duration timeout(Duration value, Duration defaultValue) {
        return value == null || value.isZero() || value.isNegative() ? defaultValue : value;
    }
}
