<?php
namespace boru\ai\Mcp;

class NativeTcpMcpConnector implements TcpMcpConnectorInterface
{
    public function connect(McpServerConfig $serverConfig)
    {
        $host = $serverConfig->host();
        $port = $serverConfig->port();

        if (!$host) {
            throw new \RuntimeException('MCP TCP host not configured for server "' . $serverConfig->name() . '"');
        }
        if (!$port) {
            throw new \RuntimeException('MCP TCP port not configured for server "' . $serverConfig->name() . '"');
        }

        $errno = 0;
        $errstr = '';
        $stream = @fsockopen($host, (int)$port, $errno, $errstr, $serverConfig->connectTimeout());
        if (!is_resource($stream)) {
            throw new \RuntimeException('Failed to connect to MCP TCP server ' . $host . ':' . $port . ' - ' . $errstr . ' (' . $errno . ')');
        }

        stream_set_blocking($stream, true);
        stream_set_timeout($stream, (int)$serverConfig->readTimeout());

        return new NativeTcpMcpConnection($stream);
    }
}
