"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 __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubAgentsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const sub_agent_entity_1 = require("./sub-agent.entity");
const mcp_service_1 = require("../mcp/mcp.service");
let SubAgentsService = class SubAgentsService {
    constructor(subAgentsRepository, mcpService) {
        this.subAgentsRepository = subAgentsRepository;
        this.mcpService = mcpService;
    }
    async create(createSubAgentDto) {
        const { enabled_mcp_tools, ...rest } = createSubAgentDto;
        const subAgent = this.subAgentsRepository.create({
            ...rest,
            enabled_mcp_tools: enabled_mcp_tools !== undefined
                ? this.mcpService.serializeEnabledMcpTools(enabled_mcp_tools)
                : null,
        });
        return this.subAgentsRepository.save(subAgent);
    }
    async findAll(activeOnly = false) {
        const query = this.subAgentsRepository.createQueryBuilder('sub_agent');
        if (activeOnly) {
            query.where('sub_agent.is_active = :isActive', { isActive: true });
        }
        return query
            .leftJoinAndSelect('sub_agent.systemPrompt', 'systemPrompt')
            .leftJoinAndSelect('sub_agent.contextTemplate', 'contextTemplate')
            .leftJoinAndSelect('sub_agent.followupContextTemplate', 'followupContextTemplate')
            .orderBy('sub_agent.name', 'ASC')
            .getMany();
    }
    async findOne(id) {
        const subAgent = await this.subAgentsRepository.findOne({
            where: { id },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
        if (!subAgent) {
            throw new common_1.NotFoundException(`SubAgent with ID "${id}" not found`);
        }
        return subAgent;
    }
    async findByBuiltinKey(builtinKey) {
        return this.subAgentsRepository.findOne({
            where: { builtin_key: builtinKey },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
    }
    async update(id, updateSubAgentDto) {
        const subAgent = await this.findOne(id);
        if (subAgent.is_builtin) {
            const allowedKeys = ['is_active', 'model_id'];
            const modifiedFields = Object.keys(updateSubAgentDto).filter((key) => !allowedKeys.includes(key));
            if (modifiedFields.length > 0) {
                throw new common_1.ForbiddenException(`Cannot modify built-in sub-agent "${subAgent.name}". Only the active status and model can be changed. Duplicate it to create your own version.`);
            }
        }
        const { enabled_mcp_tools, ...rest } = updateSubAgentDto;
        const updateData = {};
        for (const [key, value] of Object.entries(rest)) {
            if (value !== undefined) {
                updateData[key] = value;
            }
        }
        if (enabled_mcp_tools !== undefined) {
            updateData.enabled_mcp_tools =
                this.mcpService.serializeEnabledMcpTools(enabled_mcp_tools);
        }
        await this.subAgentsRepository.update(id, updateData);
        return this.findOne(id);
    }
    async remove(id) {
        const subAgent = await this.findOne(id);
        await this.subAgentsRepository.remove(subAgent);
    }
    async findActive() {
        return this.findAll(true);
    }
    async getAgentByName(name) {
        return this.subAgentsRepository.findOne({
            where: { name, is_active: true },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
    }
    async duplicate(id) {
        const original = await this.findOne(id);
        let newName = `${original.name} (Copy)`;
        let suffix = 2;
        while (await this.subAgentsRepository.findOne({ where: { name: newName } })) {
            newName = `${original.name} (Copy ${suffix})`;
            suffix++;
        }
        const duplicate = this.subAgentsRepository.create({
            name: newName,
            description: original.description,
            system_prompt_id: original.system_prompt_id,
            context_template_id: original.context_template_id,
            followup_context_template_id: original.followup_context_template_id,
            enabled_tools: original.enabled_tools,
            enabled_mcp_tools: original.enabled_mcp_tools,
            is_active: true,
            model_id: original.model_id,
            is_builtin: false,
            builtin_key: null,
        });
        return this.subAgentsRepository.save(duplicate);
    }
};
exports.SubAgentsService = SubAgentsService;
exports.SubAgentsService = SubAgentsService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(sub_agent_entity_1.SubAgent)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        mcp_service_1.McpService])
], SubAgentsService);
//# sourceMappingURL=sub-agents.service.js.map