"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 ManageContextSnippetsHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageContextSnippetsHandler = void 0;
const common_1 = require("@nestjs/common");
const context_snippets_service_1 = require("../../context-snippets/context-snippets.service");
let ManageContextSnippetsHandler = ManageContextSnippetsHandler_1 = class ManageContextSnippetsHandler {
    constructor(contextSnippetsService) {
        this.contextSnippetsService = contextSnippetsService;
        this.toolName = 'manage_context_snippets';
        this.logger = new common_1.Logger(ManageContextSnippetsHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg context snippets — reusable Eta template blocks accessible via it.snippets.handle in context templates.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|create|update|delete',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the context snippet (required for get/update/delete)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: handle (required for create, unique), description, template_content (required for create, Eta syntax).',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_context_snippets

Manage RepoBurg context snippets — reusable Eta template blocks accessible via \`it.snippets.handle\` in context templates. Use snippets for frequently-needed context like git status, package info, etc.

### Actions:

- **list** — List all context snippets (returns id, handle, description)
- **get** — Get full details of a snippet by ID
- **create** — Create a new snippet. Provide \`data\` with: handle (required, unique identifier), description, template_content (required, Eta template)
- **update** — Update a snippet. Provide \`id\` and \`data\` with fields to change (handle, description, template_content)
- **delete** — Delete a snippet by ID

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

### Examples:

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

Create a snippet:
\`\`\`typescript
tool: manage_context_snippets
args: { action: "create", data: { handle: "git-status", description: "Current git branch and recent commits", template_content: "<%= await it.runCommand('git log --oneline -5') %>" } }
\`\`\``;
    }
    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;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, create, update, delete`,
                        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_context_snippets error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} context snippet: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const snippets = await this.contextSnippetsService.findAll();
        const summary = snippets.map((s) => ({
            id: s.id,
            handle: s.handle,
            description: s.description,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${snippets.length} context 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.contextSnippetsService.findOne(id);
        return {
            status: 'SUCCESS',
            summary: `Context snippet "${snippet.handle}"`,
            execution_log: {
                output: JSON.stringify(snippet, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.handle || !data.template_content) {
            return {
                status: 'FAILURE',
                summary: 'data.handle and data.template_content are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const snippet = await this.contextSnippetsService.create({
            handle: data.handle,
            description: data.description,
            template_content: data.template_content,
        });
        const result = { id: snippet.id, handle: snippet.handle };
        return {
            status: 'SUCCESS',
            summary: `Context snippet "${snippet.handle}" 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.contextSnippetsService.update(id, data);
        return {
            status: 'SUCCESS',
            summary: `Context snippet "${snippet.handle}" updated`,
            execution_log: {
                output: JSON.stringify({ id: snippet.id, handle: snippet.handle }, 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.contextSnippetsService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Context snippet ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageContextSnippetsHandler = ManageContextSnippetsHandler;
exports.ManageContextSnippetsHandler = ManageContextSnippetsHandler = ManageContextSnippetsHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [context_snippets_service_1.ContextSnippetsService])
], ManageContextSnippetsHandler);
//# sourceMappingURL=manage-context-snippets.handler.js.map