"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 ManageContextTemplatesHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageContextTemplatesHandler = void 0;
const common_1 = require("@nestjs/common");
const context_templates_service_1 = require("../../context-templates/context-templates.service");
let ManageContextTemplatesHandler = ManageContextTemplatesHandler_1 = class ManageContextTemplatesHandler {
    constructor(contextTemplatesService) {
        this.contextTemplatesService = contextTemplatesService;
        this.toolName = 'manage_context_templates';
        this.logger = new common_1.Logger(ManageContextTemplatesHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg context templates — Eta templates that define how context (files, folders, tools) is assembled for LLM prompts.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|create|update|delete|duplicate|set_default_initial|set_default_followup|set_default_condensed',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the context template (required for most actions)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: template_name, template_content (Eta), context_definition (JSON string), template_type ("main"|"partial").',
                    required: false,
                },
                {
                    name: 'type',
                    type: 'string',
                    description: 'Filter for list action: "main" or "partial"',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_context_templates

Manage RepoBurg context templates — Eta templates that define how context (files, folders, tools) is assembled for LLM prompts. Templates use Eta syntax and have access to \`it.files\`, \`it.folders\`, \`it.tools\`, \`it.snippets\`, and \`it.variables\`.

### Actions:

- **list** — List all context templates. Optionally filter by type ("main" or "partial")
- **get** — Get full details of a template by ID
- **create** — Create a new template. Provide \`data\` with: template_name (required), template_content (required), context_definition, template_type ("main"|"partial")
- **update** — Update a template. Provide \`id\` and \`data\` with fields to change. Built-in templates cannot be updated.
- **delete** — Delete a template by ID. Built-in templates cannot be deleted.
- **duplicate** — Duplicate a template (works for built-in too)
- **set_default_initial** — Set as default for initial prompts
- **set_default_followup** — Set as default for follow-up prompts
- **set_default_condensed** — Set as default for condensed history

### Parameters:
- **action** (required): Operation to perform
- **id** (optional): UUID of the context template
- **data** (optional): Object with template fields
- **type** (optional): Filter type for list action

### Examples:

List all main templates:
\`\`\`typescript
tool: manage_context_templates
args: { action: "list", type: "main" }
\`\`\`

Create a new template:
\`\`\`typescript
tool: manage_context_templates
args: { action: "create", data: { template_name: "My Template", template_content: "<%= it.files %>", template_type: "main" } }
\`\`\``;
    }
    async execute(args, _context) {
        const { action } = args;
        try {
            let result;
            switch (action) {
                case 'list':
                    result = await this.handleList(args.type);
                    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;
                case 'set_default_initial':
                    result = await this.handleSetDefault(args.id, 'initial');
                    break;
                case 'set_default_followup':
                    result = await this.handleSetDefault(args.id, 'followup');
                    break;
                case 'set_default_condensed':
                    result = await this.handleSetDefault(args.id, 'condensed');
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, create, update, delete, duplicate, set_default_initial, set_default_followup, set_default_condensed`,
                        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_templates error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} context template: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList(type) {
        const templateType = type === 'main' || type === 'partial'
            ? type
            : undefined;
        const templates = await this.contextTemplatesService.findAll(templateType);
        const summary = templates.map((t) => ({
            id: t.id,
            template_name: t.template_name,
            template_type: t.template_type,
            is_default_initial: t.is_default_initial,
            is_default_followup: t.is_default_followup,
            is_default_condensed: t.is_default_condensed,
            is_builtin: t.is_builtin,
            builtin_key: t.builtin_key,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${templates.length} context template(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 template = await this.contextTemplatesService.findOne(id);
        return {
            status: 'SUCCESS',
            summary: `Context template "${template.template_name}"`,
            execution_log: {
                output: JSON.stringify(template, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.template_name || !data.template_content) {
            return {
                status: 'FAILURE',
                summary: 'data.template_name and data.template_content are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const template = await this.contextTemplatesService.create({
            template_name: data.template_name,
            template_content: data.template_content,
            context_definition: data.context_definition,
            template_type: data.template_type,
        });
        const result = {
            id: template.id,
            template_name: template.template_name,
            template_type: template.template_type,
        };
        return {
            status: 'SUCCESS',
            summary: `Context template "${template.template_name}" created with ID ${template.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 template = await this.contextTemplatesService.update(id, data);
        return {
            status: 'SUCCESS',
            summary: `Context template "${template.template_name}" updated`,
            execution_log: {
                output: JSON.stringify({ id: template.id, template_name: template.template_name }, 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.contextTemplatesService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Context template ${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 template = await this.contextTemplatesService.duplicate(id);
        return {
            status: 'SUCCESS',
            summary: `Context template duplicated as "${template.template_name}"`,
            execution_log: {
                output: JSON.stringify({ id: template.id, template_name: template.template_name }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleSetDefault(id, type) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for set_default action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        let template;
        if (type === 'initial') {
            template = await this.contextTemplatesService.setDefaultInitial(id);
        }
        else if (type === 'followup') {
            template = await this.contextTemplatesService.setDefaultFollowup(id);
        }
        else {
            template = await this.contextTemplatesService.setDefaultCondensed(id);
        }
        return {
            status: 'SUCCESS',
            summary: `Context template "${template.template_name}" set as default ${type}`,
            execution_log: {
                output: JSON.stringify({
                    id: template.id,
                    template_name: template.template_name,
                    default_type: type,
                }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageContextTemplatesHandler = ManageContextTemplatesHandler;
exports.ManageContextTemplatesHandler = ManageContextTemplatesHandler = ManageContextTemplatesHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [context_templates_service_1.ContextTemplatesService])
], ManageContextTemplatesHandler);
//# sourceMappingURL=manage-context-templates.handler.js.map