/**
 * MCP Command Extension for Clawx TUI.
 *
 * Provides /mcp command to manage MCP servers.
 * Similar to the SSH command extension.
 */
import { getMcpManager } from "../mcp/manager.js";
import { getMcpStatus } from "../mcp/tools.js";
export function createMcpCommandExtension(options) {
    return function mcpCommandExtension(pi) {
        // Initialize MCP manager with config if provided
        if (options?.config?.mcpServers) {
            const manager = getMcpManager();
            manager.initialize(options.config);
        }
        function tokenize(input) {
            const tokens = [];
            let current = '';
            let quote = null;
            let escape = false;
            for (const ch of input) {
                if (escape) {
                    current += ch;
                    escape = false;
                    continue;
                }
                if (ch === '\\') {
                    escape = true;
                    continue;
                }
                if (quote) {
                    if (ch === quote) {
                        quote = null;
                    }
                    else {
                        current += ch;
                    }
                    continue;
                }
                if (ch === '"' || ch === "'") {
                    quote = ch;
                    continue;
                }
                if (/\s/.test(ch)) {
                    if (current) {
                        tokens.push(current);
                        current = '';
                    }
                    continue;
                }
                current += ch;
            }
            if (current) {
                tokens.push(current);
            }
            return tokens;
        }
        // Register /mcp command
        pi.registerCommand("mcp", {
            description: "Manage MCP (Model Context Protocol) servers",
            handler: async (args, ctx) => {
                const tokens = tokenize(args.trim());
                const subcommand = (tokens.shift() || 'list').toLowerCase();
                const manager = getMcpManager();
                // Note: We don't have direct access to config here
                // In a real implementation, we'd need to get config from somewhere
                switch (subcommand) {
                    case 'list': {
                        const status = getMcpStatus();
                        if (status.length === 0) {
                            ctx.ui.notify("No MCP servers configured. Use /mcp add <name> <command> [args...] to add a server", "info");
                            return;
                        }
                        let message = "MCP Servers:\n";
                        for (const server of status) {
                            const statusIcon = server.status === 'connected' ? '✅' :
                                server.status === 'error' ? '❌' :
                                    server.status === 'disabled' ? '⏸️' : '🔄';
                            message += `  ${statusIcon} ${server.name}: ${server.status} (${server.tools} tools)\n`;
                            if (server.error) {
                                message += `    Error: ${server.error}\n`;
                            }
                        }
                        ctx.ui.notify(message.trim(), "info");
                        break;
                    }
                    case 'add': {
                        const name = tokens.shift();
                        const command = tokens.shift();
                        if (!name || !command) {
                            ctx.ui.notify("Usage: /mcp add <name> <command> [args...]", "error");
                            return;
                        }
                        ctx.ui.notify(`MCP server '${name}' added. Note: Config saving not implemented in this version.`, "warning");
                        ctx.ui.notify("Full MCP integration requires config file support.", "info");
                        break;
                    }
                    case 'remove': {
                        const name = tokens.shift();
                        if (!name) {
                            ctx.ui.notify("Usage: /mcp remove <name>", "error");
                            return;
                        }
                        try {
                            await manager.disconnectServer(name);
                            ctx.ui.notify(`Disconnected from MCP server '${name}'`, "info");
                        }
                        catch (error) {
                            ctx.ui.notify(`Failed to disconnect: ${error instanceof Error ? error.message : String(error)}`, "error");
                        }
                        break;
                    }
                    case 'connect': {
                        const name = tokens.shift();
                        if (!name) {
                            ctx.ui.notify("Usage: /mcp connect <name>", "error");
                            return;
                        }
                        ctx.ui.notify(`Connecting to '${name}'...`, "info");
                        try {
                            await manager.connectServer(name);
                            ctx.ui.notify(`Connected to '${name}'`, "info");
                        }
                        catch (error) {
                            ctx.ui.notify(`Failed to connect: ${error instanceof Error ? error.message : String(error)}`, "error");
                        }
                        break;
                    }
                    case 'disconnect': {
                        const name = tokens.shift();
                        if (!name) {
                            ctx.ui.notify("Usage: /mcp disconnect <name>", "error");
                            return;
                        }
                        ctx.ui.notify(`Disconnecting from '${name}'...`, "info");
                        try {
                            await manager.disconnectServer(name);
                            ctx.ui.notify(`Disconnected from '${name}'`, "info");
                        }
                        catch (error) {
                            ctx.ui.notify(`Failed to disconnect: ${error instanceof Error ? error.message : String(error)}`, "error");
                        }
                        break;
                    }
                    case 'help':
                    default: {
                        const helpText = `
MCP Commands:
  /mcp list                    - List MCP servers and their status
  /mcp add <name> <command>    - Add a new MCP server
  /mcp remove <name>           - Remove an MCP server
  /mcp connect <name>          - Connect to a server
  /mcp disconnect <name>       - Disconnect from a server
  /mcp enable <name>           - Enable a disabled server
  /mcp disable <name>          - Disable a server
  /mcp help                    - Show this help

Note: Full MCP configuration requires editing clawx.json config file.
            `.trim();
                        ctx.ui.notify(helpText, "info");
                        break;
                    }
                }
            },
        });
    };
}
//# sourceMappingURL=mcp-command.js.map