"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 ManageSystemPromptsHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageSystemPromptsHandler = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const system_prompts_service_1 = require("../../system-prompts/system-prompts.service");
let ManageSystemPromptsHandler = ManageSystemPromptsHandler_1 = class ManageSystemPromptsHandler {
    constructor(moduleRef) {
        this.moduleRef = moduleRef;
        this.toolName = 'manage_system_prompts';
        this.logger = new common_1.Logger(ManageSystemPromptsHandler_1.name);
    }
    getSystemPromptsService() {
        return this.moduleRef.get(system_prompts_service_1.SystemPromptsService, { strict: false });
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg system prompts — the AI behavior configurations that define how agents operate.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|get_raw|create|update|delete|duplicate|set_default|set_enabled_tools|set_enabled_mcp_tools|toggle_tool|toggle_mcp_tool|preview',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the system prompt (required for get/get_raw/update/delete/duplicate/set_default/toggle_tool/toggle_mcp_tool/preview)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: prompt_name, prompt_content (Eta template), is_default, url, followup_token_limit, enabledTools (array of tool names or "all"), enabledMcpTools (array of serverName__toolName identifiers or "all"). For create, prompt_name and prompt_content are required. ALWAYS specify enabledTools and enabledMcpTools — use "all" if unsure.',
                    required: false,
                },
                {
                    name: 'enabled_tools',
                    type: 'array',
                    description: 'For set_enabled_tools: array of tool names or "all". Example: ["create_file","overwrite_file"] or "all"',
                    required: false,
                },
                {
                    name: 'enabled_mcp_tools',
                    type: 'array',
                    description: 'For set_enabled_mcp_tools: array of serverName__toolName identifiers or "all". Example: ["playwright__browser_navigate"] or "all"',
                    required: false,
                },
                {
                    name: 'tool_name',
                    type: 'string',
                    description: 'For toggle_tool/toggle_mcp_tool: the single tool name to toggle on/off',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_system_prompts

Manage RepoBurg system prompts — the AI behavior configurations that define how agents operate. Each prompt is an Eta template that gets rendered with tool definitions and variables before being sent to the LLM.

### Actions:

- **list** — List all system prompts (returns id, name, is_default, is_builtin, url)
- **get** — Get full details of a prompt by ID (rendered content with tools injected)
- **get_raw** — Get raw unrendered prompt content by ID
- **create** — Create a new system prompt. Provide \`data\` with fields: prompt_name (required), prompt_content (required), is_default, url, followup_token_limit, enabledTools (array of tool names or "all", default "all"), enabledMcpTools (array of serverName__toolName or "all", default "all"). **Always specify enabledTools and enabledMcpTools when creating a system prompt.**
- **update** — Update an existing prompt. Provide \`id\` and \`data\` with fields to change. Built-in prompts cannot be updated.
- **delete** — Delete a prompt by ID. Built-in prompts cannot be deleted.
- **duplicate** — Duplicate a prompt by ID (works for built-in too). Returns the new copy.
- **set_default** — Set a prompt as the default for new sessions
- **set_enabled_tools** — Set which native tools a prompt allows. Provide \`id\` and \`enabled_tools\` (array of tool names or "all")
- **set_enabled_mcp_tools** — Set which MCP tools a prompt allows. Provide \`id\` and \`enabled_mcp_tools\` (array or "all")
- **toggle_tool** — Toggle a single native tool on/off for a prompt. Provide \`id\` and \`tool_name\`
- **toggle_mcp_tool** — Toggle a single MCP tool on/off for a prompt. Provide \`id\` and \`tool_name\`
- **preview** — Render a prompt content string with tools injected (no ID needed, provide \`data.prompt_content\`)

### Parameters:
- **action** (required): Operation to perform
- **id** (optional): UUID of the system prompt
- **data** (optional): Object with prompt fields for create/update. **When creating, always include enabledTools and enabledMcpTools.**
- **enabled_tools** (optional): Tool names array or "all" for set_enabled_tools
- **enabled_mcp_tools** (optional): MCP tool identifiers or "all" for set_enabled_mcp_tools
- **tool_name** (optional): Single tool name for toggle operations

### Examples:

List all prompts:
\`\`\`typescript
tool: manage_system_prompts
args: { action: "list" }
\`\`\`

Create a new prompt with specific tools:
\`\`\`typescript
tool: manage_system_prompts
args: { action: "create", data: { prompt_name: "Code Reviewer", prompt_content: "You are a code reviewer...", enabledTools: ["request_context", "run_command", "final"], enabledMcpTools: "all" } }
\`\`\`

Enable specific tools:
\`\`\`typescript
tool: manage_system_prompts
args: { action: "set_enabled_tools", id: "uuid-here", enabled_tools: ["create_file", "overwrite_file", "delete_file", "request_context"] }
\`\`\``;
    }
    async execute(args, _context) {
        const { action } = args;
        const systemPromptsService = this.getSystemPromptsService();
        try {
            let result;
            switch (action) {
                case 'list':
                    result = await this.handleList(systemPromptsService);
                    break;
                case 'get':
                    result = await this.handleGet(systemPromptsService, args.id);
                    break;
                case 'get_raw':
                    result = await this.handleGetRaw(systemPromptsService, args.id);
                    break;
                case 'create':
                    result = await this.handleCreate(systemPromptsService, args.data);
                    break;
                case 'update':
                    result = await this.handleUpdate(systemPromptsService, args.id, args.data);
                    break;
                case 'delete':
                    result = await this.handleDelete(systemPromptsService, args.id);
                    break;
                case 'duplicate':
                    result = await this.handleDuplicate(systemPromptsService, args.id);
                    break;
                case 'set_default':
                    result = await this.handleSetDefault(systemPromptsService, args.id);
                    break;
                case 'set_enabled_tools':
                    result = await this.handleSetEnabledTools(systemPromptsService, args.id, args.enabled_tools);
                    break;
                case 'set_enabled_mcp_tools':
                    result = await this.handleSetEnabledMcpTools(systemPromptsService, args.id, args.enabled_mcp_tools);
                    break;
                case 'toggle_tool':
                    result = await this.handleToggleTool(systemPromptsService, args.id, args.tool_name);
                    break;
                case 'toggle_mcp_tool':
                    result = await this.handleToggleMcpTool(systemPromptsService, args.id, args.tool_name);
                    break;
                case 'preview':
                    result = await this.handlePreview(systemPromptsService, args.data);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, get_raw, create, update, delete, duplicate, set_default, set_enabled_tools, set_enabled_mcp_tools, toggle_tool, toggle_mcp_tool, preview`,
                        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_system_prompts error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} system prompt: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList(service) {
        const prompts = await service.findAll();
        const summary = prompts.map((p) => ({
            id: p.id,
            prompt_name: p.prompt_name,
            is_default: p.is_default,
            is_builtin: p.is_builtin,
            builtin_key: p.builtin_key,
            url: p.url,
            followup_token_limit: p.followup_token_limit,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${prompts.length} system prompt(s).`,
            execution_log: {
                output: JSON.stringify(summary, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: 'list',
                reason: `Found ${prompts.length} system prompt(s).`,
            },
        };
    }
    async handleGetRaw(service, id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for get_raw action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const prompt = await service.findOneRaw(id);
        const result = {
            id: prompt.id,
            prompt_name: prompt.prompt_name,
            prompt_content: prompt.prompt_content,
            is_default: prompt.is_default,
            is_builtin: prompt.is_builtin,
            builtin_key: prompt.builtin_key,
            url: prompt.url,
            enabledTools: prompt.enabledTools,
            enabledMcpTools: prompt.enabledMcpTools,
            followup_token_limit: prompt.followup_token_limit,
        };
        return {
            status: 'SUCCESS',
            summary: `System prompt "${prompt.prompt_name}" (raw)`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `get_raw "${prompt.prompt_name}"`,
                reason: `Got raw system prompt "${prompt.prompt_name}".`,
            },
        };
    }
    async handleGet(service, id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for get action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const prompt = await service.findOne(id);
        const result = {
            id: prompt.id,
            prompt_name: prompt.prompt_name,
            prompt_content: prompt.prompt_content,
            is_default: prompt.is_default,
            is_builtin: prompt.is_builtin,
            builtin_key: prompt.builtin_key,
            url: prompt.url,
            enabledTools: prompt.enabledTools,
            enabledMcpTools: prompt.enabledMcpTools,
            followup_token_limit: prompt.followup_token_limit,
        };
        return {
            status: 'SUCCESS',
            summary: `System prompt "${prompt.prompt_name}"`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `get "${prompt.prompt_name}"`,
                reason: `Got system prompt "${prompt.prompt_name}".`,
            },
        };
    }
    async handleCreate(service, data) {
        if (!data || !data.prompt_name || !data.prompt_content) {
            return {
                status: 'FAILURE',
                summary: 'data.prompt_name and data.prompt_content are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const createDto = {
            prompt_name: data.prompt_name,
            prompt_content: data.prompt_content,
            url: data.url,
            followup_token_limit: data.followup_token_limit,
            enabledTools: data.enabledTools,
            enabledMcpTools: data.enabledMcpTools,
        };
        Object.keys(createDto).forEach((k) => createDto[k] === undefined && delete createDto[k]);
        const prompt = await service.create(createDto);
        const result = {
            id: prompt.id,
            prompt_name: prompt.prompt_name,
            is_default: prompt.is_default,
        };
        return {
            status: 'SUCCESS',
            summary: `System prompt "${prompt.prompt_name}" created with ID ${prompt.id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `create "${prompt.prompt_name}"`,
                reason: `System prompt "${prompt.prompt_name}" created with ID ${prompt.id}`,
            },
        };
    }
    async handleUpdate(service, id, data) {
        if (!id || !data) {
            return {
                status: 'FAILURE',
                summary: 'id and data are required for update action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const prompt = await service.update(id, data);
        const result = {
            id: prompt.id,
            prompt_name: prompt.prompt_name,
            is_default: prompt.is_default,
        };
        return {
            status: 'SUCCESS',
            summary: `System prompt "${prompt.prompt_name}" updated`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `update "${prompt.prompt_name}"`,
                reason: `System prompt "${prompt.prompt_name}" updated.`,
            },
        };
    }
    async handleDelete(service, id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for delete action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        await service.remove(id);
        return {
            status: 'SUCCESS',
            summary: `System prompt ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {
                command_string: `delete ${id}`,
                reason: `System prompt ${id} deleted.`,
            },
        };
    }
    async handleDuplicate(service, id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for duplicate action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const prompt = await service.duplicate(id);
        const result = {
            id: prompt.id,
            prompt_name: prompt.prompt_name,
            is_default: prompt.is_default,
        };
        return {
            status: 'SUCCESS',
            summary: `System prompt duplicated as "${prompt.prompt_name}"`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `duplicate "${prompt.prompt_name}"`,
                reason: `System prompt duplicated as "${prompt.prompt_name}".`,
            },
        };
    }
    async handleSetDefault(service, id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for set_default action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const prompt = await service.setDefault(id);
        return {
            status: 'SUCCESS',
            summary: `System prompt "${prompt.prompt_name}" set as default`,
            execution_log: {
                output: JSON.stringify({
                    id: prompt.id,
                    prompt_name: prompt.prompt_name,
                    is_default: true,
                }),
                error_message: '',
            },
            persisted_args: {
                command_string: `set_default "${prompt.prompt_name}"`,
                reason: `System prompt "${prompt.prompt_name}" set as default.`,
            },
        };
    }
    async handleSetEnabledTools(service, id, enabledTools) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for set_enabled_tools action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const result = await service.setEnabledTools(id, enabledTools);
        return {
            status: 'SUCCESS',
            summary: `Enabled tools updated for system prompt ${id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `set_enabled_tools ${id}`,
                reason: `Enabled tools updated for system prompt.`,
            },
        };
    }
    async handleSetEnabledMcpTools(service, id, enabledMcpTools) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for set_enabled_mcp_tools action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const result = await service.setEnabledMcpTools(id, enabledMcpTools);
        return {
            status: 'SUCCESS',
            summary: `Enabled MCP tools updated for system prompt ${id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `set_enabled_mcp_tools ${id}`,
                reason: `Enabled MCP tools updated for system prompt.`,
            },
        };
    }
    async handleToggleTool(service, id, toolName) {
        if (!id || !toolName) {
            return {
                status: 'FAILURE',
                summary: 'id and tool_name are required for toggle_tool action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const result = await service.toggleTool(id, toolName);
        return {
            status: 'SUCCESS',
            summary: `Tool "${toolName}" toggled for system prompt ${id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `toggle_tool "${toolName}"`,
                reason: `Tool "${toolName}" toggled for system prompt.`,
            },
        };
    }
    async handleToggleMcpTool(service, id, mcpToolName) {
        if (!id || !mcpToolName) {
            return {
                status: 'FAILURE',
                summary: 'id and tool_name are required for toggle_mcp_tool action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        const result = await service.toggleMcpTool(id, mcpToolName);
        return {
            status: 'SUCCESS',
            summary: `MCP tool "${mcpToolName}" toggled for system prompt ${id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: `toggle_mcp_tool "${mcpToolName}"`,
                reason: `MCP tool "${mcpToolName}" toggled for system prompt.`,
            },
        };
    }
    async handlePreview(service, data) {
        if (!data || !data.prompt_content) {
            return {
                status: 'FAILURE',
                summary: 'data.prompt_content is required for preview action',
                error_message: 'Missing prompt_content',
                execution_log: { output: '', error_message: 'Missing prompt_content' },
            };
        }
        const result = await service.preview({
            prompt_content: data.prompt_content,
        });
        return {
            status: 'SUCCESS',
            summary: 'Preview rendered successfully',
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {
                command_string: 'preview',
                reason: 'Preview rendered successfully.',
            },
        };
    }
};
exports.ManageSystemPromptsHandler = ManageSystemPromptsHandler;
exports.ManageSystemPromptsHandler = ManageSystemPromptsHandler = ManageSystemPromptsHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [core_1.ModuleRef])
], ManageSystemPromptsHandler);
//# sourceMappingURL=manage-system-prompts.handler.js.map