"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); }
};
var AgentsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const core_entities_1 = require("../core-entities");
let AgentsService = AgentsService_1 = class AgentsService {
    constructor(agentsRepository, dataSource) {
        this.agentsRepository = agentsRepository;
        this.dataSource = dataSource;
        this.logger = new common_1.Logger(AgentsService_1.name);
    }
    async create(createAgentDto) {
        const agent = this.agentsRepository.create(createAgentDto);
        if (agent.is_default) {
            await this.clearDefault();
        }
        return this.agentsRepository.save(agent);
    }
    async findAll(activeOnly = false) {
        const query = this.agentsRepository
            .createQueryBuilder('agent')
            .leftJoinAndSelect('agent.systemPrompt', 'systemPrompt')
            .leftJoinAndSelect('agent.contextTemplate', 'contextTemplate')
            .leftJoinAndSelect('agent.followupContextTemplate', 'followupContextTemplate')
            .orderBy('agent.name', 'ASC');
        if (activeOnly) {
            query.where('agent.is_active = :isActive', { isActive: true });
        }
        return query.getMany();
    }
    async findOne(id) {
        const agent = await this.agentsRepository.findOne({
            where: { id },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
        if (!agent) {
            throw new common_1.NotFoundException(`Agent with ID "${id}" not found`);
        }
        return agent;
    }
    async update(id, updateAgentDto) {
        const agent = await this.findOne(id);
        if (agent.is_builtin) {
            const allowedKeys = [
                'is_active',
                'model_id',
                'reasoning_effort',
            ];
            const modifiedFields = Object.keys(updateAgentDto).filter((key) => !allowedKeys.includes(key));
            if (modifiedFields.length > 0) {
                throw new common_1.ForbiddenException(`Cannot modify built-in agent "${agent.name}". Only active status, model, and reasoning effort can be changed. Duplicate it to create your own version.`);
            }
        }
        if (updateAgentDto.is_default === true) {
            await this.clearDefault();
        }
        const updateData = {};
        for (const [key, value] of Object.entries(updateAgentDto)) {
            if (value !== undefined) {
                updateData[key] = value;
            }
        }
        await this.agentsRepository.update(id, updateData);
        return this.findOne(id);
    }
    async remove(id) {
        const agent = await this.findOne(id);
        if (agent.is_builtin) {
            throw new common_1.ForbiddenException(`Cannot delete built-in agent "${agent.name}".`);
        }
        await this.agentsRepository.remove(agent);
    }
    async setDefault(id) {
        const agent = await this.findOne(id);
        await this.clearDefault();
        agent.is_default = true;
        await this.agentsRepository.save(agent);
        return this.findOne(id);
    }
    async clearDefault() {
        await this.agentsRepository.update({ is_default: true }, { is_default: false });
    }
    async findDefault() {
        return this.agentsRepository.findOne({
            where: { is_default: true },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
    }
    async findByBuiltinKey(builtinKey) {
        return this.agentsRepository.findOne({
            where: { builtin_key: builtinKey },
            relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
        });
    }
    async duplicate(id) {
        const original = await this.findOne(id);
        let newName = `${original.name} (Copy)`;
        let suffix = 2;
        while (await this.agentsRepository.findOne({ where: { name: newName } })) {
            newName = `${original.name} (Copy ${suffix})`;
            suffix++;
        }
        const duplicate = this.agentsRepository.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,
            model_id: original.model_id,
            reasoning_effort: original.reasoning_effort,
            is_default: false,
            is_active: true,
            is_builtin: false,
            builtin_key: null,
        });
        return this.agentsRepository.save(duplicate);
    }
};
exports.AgentsService = AgentsService;
exports.AgentsService = AgentsService = AgentsService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(core_entities_1.Agent)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.DataSource])
], AgentsService);
//# sourceMappingURL=agents.service.js.map