"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var ManageMcpServersHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageMcpServersHandler = void 0;
const common_1 = require("@nestjs/common");
const mcp_service_1 = require("../../mcp/mcp.service");
let ManageMcpServersHandler = ManageMcpServersHandler_1 = class ManageMcpServersHandler {
    constructor(mcpService) {
        this.mcpService = mcpService;
        this.toolName = 'manage_mcp_servers';
        this.logger = new common_1.Logger(ManageMcpServersHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg MCP (Model Context Protocol) servers — external tool servers that provide additional capabilities to the AI.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|create|toggle_active|delete|toggle_tools',
                    required: true,
                },
                {
                    name: 'server_name',
                    type: 'string',
                    description: 'Name of the MCP server (required for toggle_active, delete)',
                    required: false,
                },
                {
                    name: 'config_json',
                    type: 'string',
                    description: 'JSON configuration for create action. Format: {"serverName": {"command": "...", "args": [...], "env": {...}}}',
                    required: false,
                },
                {
                    name: 'is_active',
                    type: 'boolean',
                    description: 'For toggle_active: true to activate, false to deactivate',
                    required: false,
                },
                {
                    name: 'tool_ids',
                    type: 'array',
                    description: 'For toggle_tools: array of MCP tool UUIDs to toggle',
                    required: false,
                },
                {
                    name: 'tools_active',
                    type: 'boolean',
                    description: 'For toggle_tools: whether to activate (true) or deactivate (false) the specified tools',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_mcp_servers

Manage RepoBurg MCP (Model Context Protocol) servers — external tool servers that provide additional capabilities to the AI. Each MCP server exposes tools that become available as native tool definitions with the naming pattern \`serverName__toolName\`.

### Actions:

- **list** — List all MCP servers with their tools and status
- **create** — Add a new MCP server. Provide \`config_json\` with the server configuration. Format: \`{"serverName": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"], "env": {}}}\`
- **toggle_active** — Activate or deactivate an MCP server. Provide \`server_name\` and \`is_active\` (boolean). Deactivating disconnects the server.
- **delete** — Remove an MCP server configuration. Provide \`server_name\`. Disconnects and removes the server and all its tools.
- **toggle_tools** — Batch enable/disable specific MCP tools. Provide \`tool_ids\` (array of tool UUIDs) and \`tools_active\` (boolean).

### Parameters:
- **action** (required): Operation to perform
- **server_name** (optional): Name of the MCP server
- **config_json** (optional): JSON config string for create
- **is_active** (optional): Boolean for toggle_active
- **tool_ids** (optional): Array of tool UUIDs for toggle_tools
- **tools_active** (optional): Boolean for toggle_tools

### Examples:

List all servers:
\`\`\`typescript
tool: manage_mcp_servers
args: { action: "list" }
\`\`\`

Add a filesystem server:
\`\`\`typescript
tool: manage_mcp_servers
args: { action: "create", config_json: '{"filesystem": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"], "env": {}}}' }
\`\`\`

Deactivate a server:
\`\`\`typescript
tool: manage_mcp_servers
args: { action: "toggle_active", server_name: "filesystem", is_active: false }
\`\`\``;
    }
    async execute(args, _context) {
        const { action } = args;
        try {
            let result;
            switch (action) {
                case 'list':
                    result = await this.handleList();
                    break;
                case 'create':
                    result = await this.handleCreate(args.config_json);
                    break;
                case 'toggle_active':
                    result = await this.handleToggleActive(args.server_name, args.is_active);
                    break;
                case 'delete':
                    result = await this.handleDelete(args.server_name);
                    break;
                case 'toggle_tools':
                    result = await this.handleToggleTools(args.tool_ids, args.tools_active);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, create, toggle_active, delete, toggle_tools`,
                        error_message: `Unknown action: ${action}`,
                        execution_log: {
                            output: '',
                            error_message: `Unknown action: ${action}`,
                        },
                    };
            }
            if (!result.persisted_args)
                result.persisted_args = {};
            if (!result.persisted_args.command_string)
                result.persisted_args.command_string = `${action}`;
            if (!result.persisted_args.reason)
                result.persisted_args.reason = result.summary || '';
            return result;
        }
        catch (error) {
            this.logger.error(`manage_mcp_servers error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} MCP server: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const servers = await this.mcpService.getMcpServers();
        return {
            status: 'SUCCESS',
            summary: `Found ${servers.length} MCP server(s).`,
            execution_log: {
                output: JSON.stringify(servers, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(configJson) {
        if (!configJson) {
            return {
                status: 'FAILURE',
                summary: 'config_json is required for create action',
                error_message: 'Missing config_json',
                execution_log: { output: '', error_message: 'Missing config_json' },
            };
        }
        const config = await this.mcpService.createMcpConfig(configJson);
        const result = {
            server_name: config.server_name,
            command: config.command,
            is_active: config.is_active,
        };
        return {
            status: 'SUCCESS',
            summary: `MCP server "${config.server_name}" created and connected`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleToggleActive(serverName, isActive) {
        if (!serverName || isActive === undefined || isActive === null) {
            return {
                status: 'FAILURE',
                summary: 'server_name and is_active are required for toggle_active action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const config = await this.mcpService.updateMcpConfigStatus(serverName, isActive);
        return {
            status: 'SUCCESS',
            summary: `MCP server "${serverName}" ${isActive ? 'activated' : 'deactivated'}`,
            execution_log: {
                output: JSON.stringify({ server_name: config.server_name, is_active: config.is_active }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleDelete(serverName) {
        if (!serverName) {
            return {
                status: 'FAILURE',
                summary: 'server_name is required for delete action',
                error_message: 'Missing server_name',
                execution_log: { output: '', error_message: 'Missing server_name' },
            };
        }
        await this.mcpService.deleteMcpConfig(serverName);
        return {
            status: 'SUCCESS',
            summary: `MCP server "${serverName}" deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, server_name: serverName }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleToggleTools(toolIds, toolsActive) {
        if (!toolIds || !Array.isArray(toolIds) || toolIds.length === 0) {
            return {
                status: 'FAILURE',
                summary: 'tool_ids (non-empty array) and tools_active are required for toggle_tools action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const result = await this.mcpService.batchUpdateToolStatus(toolIds, toolsActive);
        return {
            status: 'SUCCESS',
            summary: `${toolsActive ? 'Activated' : 'Deactivated'} ${result.affected} MCP tool(s)`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageMcpServersHandler = ManageMcpServersHandler;
exports.ManageMcpServersHandler = ManageMcpServersHandler = ManageMcpServersHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [mcp_service_1.McpService])
], ManageMcpServersHandler);
//# sourceMappingURL=manage-mcp-servers.handler.js.map