"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 ManageCustomSnippetsHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageCustomSnippetsHandler = void 0;
const common_1 = require("@nestjs/common");
const custom_snippets_service_1 = require("../../custom-snippets/custom-snippets.service");
let ManageCustomSnippetsHandler = ManageCustomSnippetsHandler_1 = class ManageCustomSnippetsHandler {
    constructor(customSnippetsService) {
        this.customSnippetsService = customSnippetsService;
        this.toolName = 'manage_custom_snippets';
        this.logger = new common_1.Logger(ManageCustomSnippetsHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg custom snippets — text expansion templates triggered by a prefix. Similar to VS Code snippets.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|create|update|delete|duplicate',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the custom snippet (required for get/update/delete/duplicate)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: prefix (required for create, unique trigger), description, body (required for create, expanded content), scope.',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_custom_snippets

Manage RepoBurg custom snippets — text expansion templates triggered by a prefix. Similar to VS Code snippets. Type the prefix to expand into the body content. Useful for frequently-used code patterns, templates, or prompts.

### Actions:

- **list** — List all custom snippets (returns id, prefix, description, scope)
- **get** — Get full details of a snippet by ID
- **create** — Create a new snippet. Provide \`data\` with: prefix (required, unique trigger), description (required), body (required, expanded content), scope (optional)
- **update** — Update a snippet. Provide \`id\` and \`data\` with fields to change
- **delete** — Delete a snippet by ID
- **duplicate** — Duplicate a snippet by ID

### Parameters:
- **action** (required): Operation to perform
- **id** (optional): UUID of the custom snippet
- **data** (optional): Object with snippet fields

### Examples:

List all snippets:
\`\`\`typescript
tool: manage_custom_snippets
args: { action: "list" }
\`\`\`

Create a snippet:
\`\`\`typescript
tool: manage_custom_snippets
args: { action: "create", data: { prefix: "auth-module", description: "Creates a basic auth module template", body: "// auth module template code here", scope: "prompt" } }
\`\`\``;
    }
    async execute(args, _context) {
        const { action } = args;
        try {
            let result;
            switch (action) {
                case 'list':
                    result = await this.handleList();
                    break;
                case 'get':
                    result = await this.handleGet(args.id);
                    break;
                case 'create':
                    result = await this.handleCreate(args.data);
                    break;
                case 'update':
                    result = await this.handleUpdate(args.id, args.data);
                    break;
                case 'delete':
                    result = await this.handleDelete(args.id);
                    break;
                case 'duplicate':
                    result = await this.handleDuplicate(args.id);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, create, update, delete, duplicate`,
                        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_custom_snippets error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} custom snippet: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const snippets = await this.customSnippetsService.findAll();
        const summary = snippets.map((s) => ({
            id: s.id,
            prefix: s.prefix,
            description: s.description,
            scope: s.scope,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${snippets.length} custom snippet(s).`,
            execution_log: {
                output: JSON.stringify(summary, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleGet(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 snippet = await this.customSnippetsService.findOne(id);
        return {
            status: 'SUCCESS',
            summary: `Custom snippet "${snippet.prefix}"`,
            execution_log: {
                output: JSON.stringify(snippet, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.prefix || !data.description || !data.body) {
            return {
                status: 'FAILURE',
                summary: 'data.prefix, data.description, and data.body are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const snippet = await this.customSnippetsService.create({
            prefix: data.prefix,
            description: data.description,
            body: data.body,
            scope: data.scope,
        });
        const result = { id: snippet.id, prefix: snippet.prefix };
        return {
            status: 'SUCCESS',
            summary: `Custom snippet "${snippet.prefix}" created with ID ${snippet.id}`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleUpdate(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 snippet = await this.customSnippetsService.update(id, data);
        return {
            status: 'SUCCESS',
            summary: `Custom snippet "${snippet.prefix}" updated`,
            execution_log: {
                output: JSON.stringify({ id: snippet.id, prefix: snippet.prefix }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleDelete(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 this.customSnippetsService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Custom snippet ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleDuplicate(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 snippet = await this.customSnippetsService.duplicate(id);
        return {
            status: 'SUCCESS',
            summary: `Custom snippet duplicated as "${snippet.prefix}"`,
            execution_log: {
                output: JSON.stringify({ id: snippet.id, prefix: snippet.prefix }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageCustomSnippetsHandler = ManageCustomSnippetsHandler;
exports.ManageCustomSnippetsHandler = ManageCustomSnippetsHandler = ManageCustomSnippetsHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [custom_snippets_service_1.CustomSnippetsService])
], ManageCustomSnippetsHandler);
//# sourceMappingURL=manage-custom-snippets.handler.js.map