"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 ManageCustomVariablesHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageCustomVariablesHandler = void 0;
const common_1 = require("@nestjs/common");
const custom_variables_service_1 = require("../../custom-variables/custom-variables.service");
let ManageCustomVariablesHandler = ManageCustomVariablesHandler_1 = class ManageCustomVariablesHandler {
    constructor(customVariablesService) {
        this.customVariablesService = customVariablesService;
        this.toolName = 'manage_custom_variables';
        this.logger = new common_1.Logger(ManageCustomVariablesHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg custom variables — key-value pairs available in context templates via it.variables.KEY.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|create|update|delete',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the variable (required for update/delete)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: key (required for create, unique identifier), value (required for create), enabled (boolean), is_freq_used (boolean), order_number (number).',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_custom_variables

Manage RepoBurg custom variables — key-value pairs available in context templates via \`it.variables.KEY\`. Use for frequently-changing values like API endpoints, author names, project names, etc.

### Actions:

- **list** — List all custom variables (returns id, key, value, enabled, order_number)
- **create** — Create a new variable. Provide \`data\` with: key (required, unique), value (required), enabled (default true), is_freq_used (default false), order_number (default 0)
- **update** — Update a variable. Provide \`id\` and \`data\` with fields to change
- **delete** — Delete a variable by ID

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

### Examples:

List all variables:
\`\`\`typescript
tool: manage_custom_variables
args: { action: "list" }
\`\`\`

Create a variable:
\`\`\`typescript
tool: manage_custom_variables
args: { action: "create", data: { key: "project_name", value: "MyApp", enabled: true } }
\`\`\`

Update a variable:
\`\`\`typescript
tool: manage_custom_variables
args: { action: "update", id: "uuid-here", data: { value: "NewValue", enabled: 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.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, 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_custom_variables error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} custom variable: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const variables = await this.customVariablesService.findAll();
        const summary = variables.map((v) => ({
            id: v.id,
            key: v.key,
            value: v.value,
            enabled: v.enabled,
            is_freq_used: v.is_freq_used,
            order_number: v.order_number,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${variables.length} custom variable(s).`,
            execution_log: {
                output: JSON.stringify(summary, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.key || data.value === undefined || data.value === null) {
            return {
                status: 'FAILURE',
                summary: 'data.key and data.value are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const variable = await this.customVariablesService.create({
            key: data.key,
            value: String(data.value),
            enabled: data.enabled ?? true,
            is_freq_used: data.is_freq_used ?? false,
            order_number: data.order_number ?? 0,
        });
        const result = {
            id: variable.id,
            key: variable.key,
            value: variable.value,
        };
        return {
            status: 'SUCCESS',
            summary: `Custom variable "${variable.key}" created with ID ${variable.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 updateData = {};
        if (data.key !== undefined)
            updateData.key = data.key;
        if (data.value !== undefined)
            updateData.value = String(data.value);
        if (data.enabled !== undefined)
            updateData.enabled = data.enabled;
        if (data.is_freq_used !== undefined)
            updateData.is_freq_used = data.is_freq_used;
        if (data.order_number !== undefined)
            updateData.order_number = data.order_number;
        const variable = await this.customVariablesService.update(id, updateData);
        return {
            status: 'SUCCESS',
            summary: `Custom variable "${variable.key}" updated`,
            execution_log: {
                output: JSON.stringify({ id: variable.id, key: variable.key, value: variable.value }, 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.customVariablesService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Custom variable ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageCustomVariablesHandler = ManageCustomVariablesHandler;
exports.ManageCustomVariablesHandler = ManageCustomVariablesHandler = ManageCustomVariablesHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [custom_variables_service_1.CustomVariablesService])
], ManageCustomVariablesHandler);
//# sourceMappingURL=manage-custom-variables.handler.js.map