"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 ManageAgentsHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManageAgentsHandler = void 0;
const common_1 = require("@nestjs/common");
const agents_service_1 = require("../../agents/agents.service");
let ManageAgentsHandler = ManageAgentsHandler_1 = class ManageAgentsHandler {
    constructor(agentsService) {
        this.agentsService = agentsService;
        this.toolName = 'manage_agents';
        this.logger = new common_1.Logger(ManageAgentsHandler_1.name);
    }
    getMetadata() {
        return {
            name: this.toolName,
            description: 'Manage RepoBurg agents — presets that group system prompt, context templates, model, and reasoning effort together.',
            arguments: [
                {
                    name: 'action',
                    type: 'string',
                    description: 'Operation: list|get|create|update|delete|duplicate|set_default',
                    required: true,
                },
                {
                    name: 'id',
                    type: 'string',
                    description: 'UUID of the agent (required for get/update/delete/duplicate/set_default)',
                    required: false,
                },
                {
                    name: 'data',
                    type: 'object',
                    description: 'Fields for create/update. Keys: name (required for create), description, system_prompt_id, context_template_id, followup_context_template_id, model_id, reasoning_effort ("low"|"medium"|"high"), is_default, is_active.',
                    required: false,
                },
            ],
        };
    }
    getDefinition() {
        return `## manage_agents

Manage RepoBurg agents — presets that group system prompt, context templates, model, and reasoning effort together. Selecting an agent applies all its settings to a session at once.

### Actions:

- **list** — List all agents (returns id, name, description, is_default, is_active, is_builtin, model_id, reasoning_effort, system_prompt_id, context_template_id, followup_context_template_id)
- **get** — Get full details of an agent by ID
- **create** — Create a new agent. Provide \`data\` with: name (required), description, system_prompt_id, context_template_id, followup_context_template_id, model_id, reasoning_effort, is_default (default false), is_active (default true)
- **update** — Update an agent. Provide \`id\` and \`data\` with fields to change. Built-in agents can only change is_active, model_id, and reasoning_effort.
- **delete** — Delete an agent by ID (cannot delete built-in agents)
- **duplicate** — Duplicate an agent by ID (works for built-in too). Returns the new copy.
- **set_default** — Set an agent as the default for new sessions. Provide \`id\`.

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

### Examples:

List all agents:
\`\`\`typescript
tool: manage_agents
args: { action: "list" }
\`\`\`

Create an agent:
\`\`\`typescript
tool: manage_agents
args: { action: "create", data: { name: "Code Reviewer", description: "Specialized in reviewing code", model_id: "ollama/glm-5.1:cloud", reasoning_effort: "high" } }
\`\`\`

Set an agent as default:
\`\`\`typescript
tool: manage_agents
args: { action: "set_default", id: "uuid-here" }
\`\`\``;
    }
    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;
                case 'set_default':
                    result = await this.handleSetDefault(args.id);
                    break;
                default:
                    result = {
                        status: 'FAILURE',
                        summary: `Unknown action "${action}". Valid actions: list, get, create, update, delete, duplicate, set_default`,
                        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_agents error: ${error.message}`, error.stack);
            return {
                status: 'FAILURE',
                summary: `Failed to ${action} agent: ${error.message}`,
                error_message: error.message,
                execution_log: { output: '', error_message: error.message },
            };
        }
    }
    async handleList() {
        const agents = await this.agentsService.findAll();
        const summary = agents.map((a) => ({
            id: a.id,
            name: a.name,
            description: a.description,
            is_default: a.is_default,
            is_active: a.is_active,
            is_builtin: a.is_builtin,
            model_id: a.model_id,
            reasoning_effort: a.reasoning_effort,
            system_prompt_id: a.system_prompt_id,
            context_template_id: a.context_template_id,
            followup_context_template_id: a.followup_context_template_id,
        }));
        return {
            status: 'SUCCESS',
            summary: `Found ${agents.length} agent(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 agent = await this.agentsService.findOne(id);
        return {
            status: 'SUCCESS',
            summary: `Agent "${agent.name}"`,
            execution_log: {
                output: JSON.stringify(agent, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleCreate(data) {
        if (!data || !data.name) {
            return {
                status: 'FAILURE',
                summary: 'data.name is required for create',
                error_message: 'Missing required field: name',
                execution_log: {
                    output: '',
                    error_message: 'Missing required field: name',
                },
            };
        }
        const createDto = {
            name: data.name,
            description: data.description ?? null,
            system_prompt_id: data.system_prompt_id ?? null,
            context_template_id: data.context_template_id ?? null,
            followup_context_template_id: data.followup_context_template_id ?? null,
            model_id: data.model_id ?? null,
            reasoning_effort: data.reasoning_effort ?? null,
            is_default: data.is_default ?? false,
            is_active: data.is_active ?? true,
        };
        const agent = await this.agentsService.create(createDto);
        const result = {
            id: agent.id,
            name: agent.name,
            is_default: agent.is_default,
            is_active: agent.is_active,
        };
        return {
            status: 'SUCCESS',
            summary: `Agent "${agent.name}" created with ID ${agent.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 updateDto = {};
        const allowedFields = [
            'name',
            'description',
            'system_prompt_id',
            'context_template_id',
            'followup_context_template_id',
            'model_id',
            'reasoning_effort',
            'is_default',
            'is_active',
        ];
        for (const key of allowedFields) {
            if (data[key] !== undefined) {
                updateDto[key] = data[key];
            }
        }
        const agent = await this.agentsService.update(id, updateDto);
        return {
            status: 'SUCCESS',
            summary: `Agent "${agent.name}" updated`,
            execution_log: {
                output: JSON.stringify({
                    id: agent.id,
                    name: agent.name,
                    is_active: agent.is_active,
                    is_default: agent.is_default,
                }, 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.agentsService.remove(id);
        return {
            status: 'SUCCESS',
            summary: `Agent ${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 agent = await this.agentsService.duplicate(id);
        return {
            status: 'SUCCESS',
            summary: `Agent duplicated as "${agent.name}"`,
            execution_log: {
                output: JSON.stringify({ id: agent.id, name: agent.name }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
    async handleSetDefault(id) {
        if (!id) {
            return {
                status: 'FAILURE',
                summary: 'id is required for set_default action',
                error_message: 'Missing id',
                execution_log: { output: '', error_message: 'Missing id' },
            };
        }
        const agent = await this.agentsService.setDefault(id);
        return {
            status: 'SUCCESS',
            summary: `Agent "${agent.name}" set as default`,
            execution_log: {
                output: JSON.stringify({ id: agent.id, name: agent.name, is_default: true }, null, 2),
                error_message: '',
            },
            persisted_args: {},
        };
    }
};
exports.ManageAgentsHandler = ManageAgentsHandler;
exports.ManageAgentsHandler = ManageAgentsHandler = ManageAgentsHandler_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [agents_service_1.AgentsService])
], ManageAgentsHandler);
//# sourceMappingURL=manage-agents.handler.js.map