"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 ManageToolHooksHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageToolHooksHandler = void 0;
const common_1 = require("@nestjs/common");
const tool_hooks_service_1 = require("../../tool-hooks/tool-hooks.service");
let ManageToolHooksHandler = ManageToolHooksHandler_1 = class ManageToolHooksHandler {
    constructor(toolHooksService) {
        this.toolHooksService = toolHooksService;
        this.toolName = 'manage_tool_hooks';
        this.logger = new common_1.Logger(ManageToolHooksHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg tool hooks — custom scripts that run before or after tool execution to validate, modify, or log actions.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|create|update|delete|list_scripts|create_script|test',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the tool hook (required for update/delete)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: tool_name (required for create, e.g. "create_file"), timing ("before"|"after", required for create), script_filename (required for create), is_active (boolean).',
                    required: false,
                },
                {
                    name: 'filename',
                    type: 'string',
                    description: 'For create_script/test: the script filename (e.g. "my-hook.ts")',
                    required: false,
                },
                {
                    name: 'content',
                    type: 'string',
                    description: 'For create_script: the script content (TypeScript)',
                    required: false,
                },
                {
                    name: 'payload',
                    type: 'object',
                    description: 'For test: the test payload to pass to the hook script',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_tool_hooks

Manage RepoBurg tool hooks — custom TypeScript scripts that run before or after tool execution. Hooks allow extending RepoBurg's behavior without modifying core code. Use hooks for validation, logging, or post-processing.

### Actions:

- **list** — List all tool hook configurations
- **create** — Create a new hook configuration. Provide \`data\` with: tool_name (required), timing ("before"|"after", required), script_filename (required), is_active (default true)
- **update** — Update a hook configuration. Provide \`id\` and \`data\` with fields to change
- **delete** — Delete a hook configuration by ID
- **list_scripts** — List available hook script files in .repoburg/hooks/
- **create_script** — Create a new hook script file. Provide \`filename\` and \`content\` (TypeScript code)
- **test** — Test a hook script with a sample payload. Provide \`filename\` and \`payload\`

### Parameters:
- **action** (required): Operation to perform
- **id** (optional): UUID of the hook configuration
- **data** (optional): Object with hook fields
- **filename** (optional): Script filename for create_script/test
- **content** (optional): Script content for create_script
- **payload** (optional): Test payload for test action

### Examples:

List all hooks:
\`\`\`typescript
tool: manage_tool_hooks
args: { action: "list" }
\`\`\`

Create a hook configuration:
\`\`\`typescript
tool: manage_tool_hooks
args: { action: "create", data: { tool_name: "create_file", timing: "before", script_filename: "my-validator.ts", is_active: true } }
\`\`\`

Create a hook script:
\`\`\`typescript
tool: manage_tool_hooks
args: { action: "create_script", filename: "my-validator.ts", content: "export default async function(context) { return { should_halt_plan: 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;
                case 'list_scripts':
                    result = await this.handleListScripts();
                    break;
                case 'create_script':
                    result = await this.handleCreateScript(args.filename, args.content);
                    break;
                case 'test':
                    result = await this.handleTest(args.filename, args.payload);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, create, update, delete, list_scripts, create_script, test`,
                        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_tool_hooks error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} tool hook: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const hooks = await this.toolHooksService.findAll();
        const summary = hooks.map((h) => ({
            id: h.id,
            tool_name: h.tool_name,
            timing: h.timing,
            script_filename: h.script_filename,
            is_active: h.is_active,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${hooks.length} tool hook(s).`,
            execution_log: {
                output: JSON.stringify(summary, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.tool_name || !data.timing || !data.script_filename) {
            return {
                status: 'FAILURE',
                summary: 'data.tool_name, data.timing, and data.script_filename are required for create',
                error_message: 'Missing required fields',
                execution_log: { output: '', error_message: 'Missing required fields' },
            };
        }
        const hook = await this.toolHooksService.create({
            tool_name: data.tool_name,
            timing: data.timing,
            script_filename: data.script_filename,
            is_active: data.is_active ?? true,
        });
        const result = {
            id: hook.id,
            tool_name: hook.tool_name,
            timing: hook.timing,
            script_filename: hook.script_filename,
        };
        return {
            status: 'SUCCESS',
            summary: `Tool hook created for "${hook.tool_name}" (${hook.timing})`,
            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.tool_name !== undefined)
            updateData.tool_name = data.tool_name;
        if (data.timing !== undefined)
            updateData.timing = data.timing;
        if (data.script_filename !== undefined)
            updateData.script_filename = data.script_filename;
        if (data.is_active !== undefined)
            updateData.is_active = data.is_active;
        const hook = await this.toolHooksService.update(id, updateData);
        return {
            status: 'SUCCESS',
            summary: `Tool hook ${id} updated`,
            execution_log: {
                output: JSON.stringify({
                    id: hook.id,
                    tool_name: hook.tool_name,
                    timing: hook.timing,
                    is_active: hook.is_active,
                }, 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.toolHooksService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Tool hook ${id} deleted`,
            execution_log: {
                output: JSON.stringify({ deleted: true, id }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleListScripts() {
        const scripts = await this.toolHooksService.listScripts();
        return {
            status: 'SUCCESS',
            summary: `Found ${scripts.length} hook script(s) in .repoburg/hooks/`,
            execution_log: {
                output: JSON.stringify(scripts, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreateScript(filename, content) {
        if (!filename || !content) {
            return {
                status: 'FAILURE',
                summary: 'filename and content are required for create_script action',
                error_message: 'Missing parameters',
                execution_log: { output: '', error_message: 'Missing parameters' },
            };
        }
        await this.toolHooksService.createScript(filename, content);
        return {
            status: 'SUCCESS',
            summary: `Hook script "${filename}" created in .repoburg/hooks/`,
            execution_log: {
                output: JSON.stringify({ created: true, filename }),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleTest(filename, payload) {
        if (!filename) {
            return {
                status: 'FAILURE',
                summary: 'filename is required for test action',
                error_message: 'Missing filename',
                execution_log: { output: '', error_message: 'Missing filename' },
            };
        }
        const testPayload = payload ||
            this.toolHooksService.generateSamplePayload('create_file', 'before');
        const result = await this.toolHooksService.testHook(filename, testPayload);
        return {
            status: 'SUCCESS',
            summary: `Hook script "${filename}" test completed`,
            execution_log: {
                output: JSON.stringify(result, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageToolHooksHandler = ManageToolHooksHandler;
exports.ManageToolHooksHandler = ManageToolHooksHandler = ManageToolHooksHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [tool_hooks_service_1.ToolHooksService])
], ManageToolHooksHandler);
//# sourceMappingURL=manage-tool-hooks.handler.js.map