"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 AgentSeedingService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentSeedingService = 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");
const system_prompts_service_1 = require("../system-prompts/system-prompts.service");
const context_templates_service_1 = require("../context-templates/context-templates.service");
const path = require("path");
const glob_1 = require("glob");
let AgentSeedingService = AgentSeedingService_1 = class AgentSeedingService {
    constructor(agentRepository, systemPromptsService, contextTemplatesService) {
        this.agentRepository = agentRepository;
        this.systemPromptsService = systemPromptsService;
        this.contextTemplatesService = contextTemplatesService;
        this.logger = new common_1.Logger(AgentSeedingService_1.name);
    }
    async seed() {
        const deprecatedBuiltinKeys = ['config-manager'];
        for (const deprecatedKey of deprecatedBuiltinKeys) {
            const deprecatedAgent = await this.agentRepository.findOne({
                where: { builtin_key: deprecatedKey, is_builtin: true },
            });
            if (deprecatedAgent) {
                await this.agentRepository.remove(deprecatedAgent);
                this.logger.log(`Removed deprecated builtin agent "${deprecatedAgent.name}" (builtin_key: ${deprecatedKey}).`);
            }
        }
        this.logger.log('Syncing agents from files...');
        const seedFiles = await (0, glob_1.glob)(path.join(__dirname, 'data', 'agents', '*.{ts,js}'));
        if (seedFiles.length === 0) {
            this.logger.warn('No agent seed files found.');
            return;
        }
        for (const filePath of seedFiles) {
            try {
                const agentModule = await Promise.resolve(`${filePath}`).then(s => require(s));
                const { name, description, system_prompt_name, context_template_name, followup_context_template_name, model_id, reasoning_effort, is_active, } = agentModule;
                const fileName = path.basename(filePath);
                const builtinKey = fileName
                    .replace(/\.(ts|js)$/, '')
                    .replace(/_/g, '-');
                if (!name) {
                    this.logger.warn(`Skipping malformed seed file: ${fileName} (missing name)`);
                    continue;
                }
                const existingAgent = await this.agentRepository.findOne({
                    where: { builtin_key: builtinKey },
                });
                if (existingAgent && existingAgent.is_builtin) {
                    let system_prompt_id = existingAgent.system_prompt_id;
                    if (system_prompt_name) {
                        const systemPrompt = await this.systemPromptsService.findByBuiltinKey(system_prompt_name.replace(/_/g, '-'));
                        system_prompt_id = systemPrompt?.id || null;
                    }
                    let context_template_id = existingAgent.context_template_id;
                    if (context_template_name) {
                        const contextTemplate = await this.contextTemplatesService.findByBuiltinKey(context_template_name.replace(/_/g, '-'));
                        context_template_id = contextTemplate?.id || null;
                    }
                    let followup_context_template_id = existingAgent.followup_context_template_id;
                    if (followup_context_template_name) {
                        const followupContextTemplate = await this.contextTemplatesService.findByBuiltinKey(followup_context_template_name.replace(/_/g, '-'));
                        followup_context_template_id = followupContextTemplate?.id || null;
                    }
                    existingAgent.description = description || existingAgent.description;
                    existingAgent.system_prompt_id = system_prompt_id;
                    existingAgent.context_template_id = context_template_id;
                    existingAgent.followup_context_template_id =
                        followup_context_template_id;
                    existingAgent.model_id = model_id || existingAgent.model_id;
                    existingAgent.reasoning_effort =
                        reasoning_effort || existingAgent.reasoning_effort;
                    existingAgent.is_active = is_active !== false;
                    await this.agentRepository.save(existingAgent);
                    this.logger.log(`Built-in agent "${name}" updated (version upgrade).`);
                }
                else if (existingAgent) {
                    this.logger.warn(`Agent with builtin_key "${builtinKey}" exists but is not built-in. Skipping.`);
                }
                else {
                    let system_prompt_id = null;
                    if (system_prompt_name) {
                        const systemPrompt = await this.systemPromptsService.findByBuiltinKey(system_prompt_name.replace(/_/g, '-'));
                        if (!systemPrompt) {
                            this.logger.warn(`System prompt with builtin_key "${system_prompt_name.replace(/_/g, '-')}" not found for agent "${name}"`);
                        }
                        else {
                            system_prompt_id = systemPrompt.id;
                        }
                    }
                    let context_template_id = null;
                    if (context_template_name) {
                        const contextTemplate = await this.contextTemplatesService.findByBuiltinKey(context_template_name.replace(/_/g, '-'));
                        if (!contextTemplate) {
                            this.logger.warn(`Context template with builtin_key "${context_template_name.replace(/_/g, '-')}" not found for agent "${name}"`);
                        }
                        else {
                            context_template_id = contextTemplate.id;
                        }
                    }
                    let followup_context_template_id = null;
                    if (followup_context_template_name) {
                        const followupContextTemplate = await this.contextTemplatesService.findByBuiltinKey(followup_context_template_name.replace(/_/g, '-'));
                        if (!followupContextTemplate) {
                            this.logger.warn(`Followup context template with builtin_key "${followup_context_template_name.replace(/_/g, '-')}" not found for agent "${name}"`);
                        }
                        else {
                            followup_context_template_id = followupContextTemplate.id;
                        }
                    }
                    const newAgent = this.agentRepository.create({
                        name,
                        description: description || null,
                        system_prompt_id,
                        context_template_id,
                        followup_context_template_id,
                        model_id: model_id || null,
                        reasoning_effort: reasoning_effort || null,
                        is_default: builtinKey === 'default-agent',
                        is_active: is_active !== false,
                        is_builtin: true,
                        builtin_key: builtinKey,
                    });
                    await this.agentRepository.save(newAgent);
                    this.logger.log(`Built-in agent "${name}" seeded.`);
                }
            }
            catch (error) {
                this.logger.error(`Failed to seed agent from ${filePath}`, error.stack);
            }
        }
    }
};
exports.AgentSeedingService = AgentSeedingService;
exports.AgentSeedingService = AgentSeedingService = AgentSeedingService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(core_entities_1.Agent)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        system_prompts_service_1.SystemPromptsService,
        context_templates_service_1.ContextTemplatesService])
], AgentSeedingService);
//# sourceMappingURL=agent-seeding.service.js.map