package com.easyagents.mcp.client;

import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Stdio MCP transport factory tests.
 */
public class StdioTransportFactoryTest {

    @Test
    public void createWithResolvedEnv() throws Exception {
        McpConfig.ServerSpec spec = new McpConfig.ServerSpec();
        spec.setCommand("npx");
        spec.setArgs(List.of("-y", "test-mcp-server"));

        CloseableTransport closeableTransport = new StdioTransportFactory()
            .create(spec, Map.of("API_KEY", "resolved-secret"));

        assertTrue(closeableTransport.getTransport() instanceof StdioClientTransport);
        StdioClientTransport transport = (StdioClientTransport) closeableTransport.getTransport();
        ServerParameters parameters = extractParameters(transport);

        assertEquals("npx", parameters.getCommand());
        assertEquals(List.of("-y", "test-mcp-server"), parameters.getArgs());
        assertEquals("resolved-secret", parameters.getEnv().get("API_KEY"));
    }

    @Test
    public void createWithNullArgsAndEnv() throws Exception {
        McpConfig.ServerSpec spec = new McpConfig.ServerSpec();
        spec.setCommand("python");
        spec.setArgs(null);

        CloseableTransport closeableTransport = new StdioTransportFactory().create(spec, null);

        assertTrue(closeableTransport.getTransport() instanceof StdioClientTransport);
        StdioClientTransport transport = (StdioClientTransport) closeableTransport.getTransport();
        ServerParameters parameters = extractParameters(transport);

        assertEquals("python", parameters.getCommand());
        assertEquals(List.of(), parameters.getArgs());
    }

    private ServerParameters extractParameters(StdioClientTransport transport) throws Exception {
        Field paramsField = StdioClientTransport.class.getDeclaredField("params");
        paramsField.setAccessible(true);
        return (ServerParameters) paramsField.get(transport);
    }
}
