/**
 * MCP slash command for Pi Agent version.
 * Simple command to list and manage MCP servers.
 */
import { getMcpManager } from '../../../mcp/manager.js';
import { getMcpStatus } from '../../../mcp/tools.js';
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;
}
function showUsage(ctx) {
    ctx.addStatus('MCP commands:', 'yellow');
    ctx.addStatus('  /mcp list                    - List MCP servers and their status');
    ctx.addStatus('  /mcp add <name> <command>    - Add a new MCP server');
    ctx.addStatus('  /mcp remove <name>           - Remove an MCP server');
    ctx.addStatus('  /mcp connect <name>          - Connect to a server');
    ctx.addStatus('  /mcp disconnect <name>       - Disconnect from a server');
    ctx.addStatus('  /mcp enable <name>           - Enable a disabled server');
    ctx.addStatus('  /mcp disable <name>          - Disable a server');
}
export const mcpCommand = {
    name: 'mcp',
    description: 'Manage MCP (Model Context Protocol) servers',
    argumentHint: 'list | add | remove | connect | disconnect | enable | disable',
    async execute(args, ctx) {
        const tokens = tokenize(args.trim());
        const subcommand = (tokens.shift() || 'list').toLowerCase();
        const manager = getMcpManager();
        const config = ctx.config;
        switch (subcommand) {
            case 'list': {
                const status = getMcpStatus();
                if (status.length === 0) {
                    ctx.addStatus('No MCP servers configured.', 'yellow');
                    ctx.addStatus('Use /mcp add <name> <command> [args...] to add a server', 'yellow');
                    return;
                }
                ctx.addStatus('MCP Servers:', 'yellow');
                for (const server of status) {
                    const statusColor = server.status === 'connected' ? 'green' :
                        server.status === 'error' ? 'red' :
                            server.status === 'disabled' ? 'gray' : 'yellow';
                    ctx.addStatus(`  ${server.name}: ${server.status} (${server.tools} tools)`, statusColor);
                    if (server.error) {
                        ctx.addStatus(`    Error: ${server.error}`, 'red');
                    }
                }
                break;
            }
            case 'add': {
                const name = tokens.shift();
                const command = tokens.shift();
                if (!name || !command) {
                    ctx.addStatus('Usage: /mcp add <name> <command> [args...]', 'red');
                    return;
                }
                // Update config
                const mcpServers = { ...(config.mcpServers || {}) };
                mcpServers[name] = {
                    command,
                    args: tokens.length > 0 ? tokens : undefined,
                };
                // Update config (simplified - in real implementation, save to config file)
                ctx.updateConfig({ mcpServers });
                // Initialize manager with new config
                manager.initialize({ ...config, mcpServers });
                ctx.addStatus(`Added MCP server '${name}'`, 'green');
                ctx.addStatus('Attempting to connect...', 'yellow');
                // Try to connect
                try {
                    await manager.connectServer(name);
                    ctx.addStatus(`Connected to '${name}'`, 'green');
                }
                catch (error) {
                    ctx.addStatus(`Failed to connect: ${error instanceof Error ? error.message : String(error)}`, 'red');
                }
                break;
            }
            case 'remove': {
                const name = tokens.shift();
                if (!name) {
                    ctx.addStatus('Usage: /mcp remove <name>', 'red');
                    return;
                }
                const mcpServers = { ...(config.mcpServers || {}) };
                if (!mcpServers[name]) {
                    ctx.addStatus(`MCP server '${name}' not found`, 'red');
                    return;
                }
                // Disconnect first
                try {
                    await manager.disconnectServer(name);
                }
                catch (error) {
                    // Ignore disconnect errors
                }
                // Remove from config
                delete mcpServers[name];
                ctx.updateConfig({ mcpServers });
                // Reinitialize manager
                manager.initialize({ ...config, mcpServers });
                ctx.addStatus(`Removed MCP server '${name}'`, 'green');
                break;
            }
            case 'connect': {
                const name = tokens.shift();
                if (!name) {
                    ctx.addStatus('Usage: /mcp connect <name>', 'red');
                    return;
                }
                const mcpServers = config.mcpServers || {};
                if (!mcpServers[name]) {
                    ctx.addStatus(`MCP server '${name}' not found`, 'red');
                    return;
                }
                ctx.addStatus(`Connecting to '${name}'...`, 'yellow');
                try {
                    await manager.connectServer(name);
                    ctx.addStatus(`Connected to '${name}'`, 'green');
                }
                catch (error) {
                    ctx.addStatus(`Failed to connect: ${error instanceof Error ? error.message : String(error)}`, 'red');
                }
                break;
            }
            case 'disconnect': {
                const name = tokens.shift();
                if (!name) {
                    ctx.addStatus('Usage: /mcp disconnect <name>', 'red');
                    return;
                }
                ctx.addStatus(`Disconnecting from '${name}'...`, 'yellow');
                try {
                    await manager.disconnectServer(name);
                    ctx.addStatus(`Disconnected from '${name}'`, 'green');
                }
                catch (error) {
                    ctx.addStatus(`Failed to disconnect: ${error instanceof Error ? error.message : String(error)}`, 'red');
                }
                break;
            }
            case 'enable': {
                const name = tokens.shift();
                if (!name) {
                    ctx.addStatus('Usage: /mcp enable <name>', 'red');
                    return;
                }
                const mcpServers = { ...(config.mcpServers || {}) };
                if (!mcpServers[name]) {
                    ctx.addStatus(`MCP server '${name}' not found`, 'red');
                    return;
                }
                mcpServers[name] = { ...mcpServers[name], disabled: false };
                ctx.updateConfig({ mcpServers });
                manager.initialize({ ...config, mcpServers });
                ctx.addStatus(`Enabled MCP server '${name}'`, 'green');
                break;
            }
            case 'disable': {
                const name = tokens.shift();
                if (!name) {
                    ctx.addStatus('Usage: /mcp disable <name>', 'red');
                    return;
                }
                const mcpServers = { ...(config.mcpServers || {}) };
                if (!mcpServers[name]) {
                    ctx.addStatus(`MCP server '${name}' not found`, 'red');
                    return;
                }
                mcpServers[name] = { ...mcpServers[name], disabled: true };
                ctx.updateConfig({ mcpServers });
                manager.initialize({ ...config, mcpServers });
                ctx.addStatus(`Disabled MCP server '${name}'`, 'green');
                break;
            }
            default:
                showUsage(ctx);
                break;
        }
    },
};
//# sourceMappingURL=mcp.js.map