"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 SubAgentSeedingService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubAgentSeedingService = 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-agents/sub-agent.entity");
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 SubAgentSeedingService = SubAgentSeedingService_1 = class SubAgentSeedingService {
    constructor(subAgentRepository, systemPromptsService, contextTemplatesService) {
        this.subAgentRepository = subAgentRepository;
        this.systemPromptsService = systemPromptsService;
        this.contextTemplatesService = contextTemplatesService;
        this.logger = new common_1.Logger(SubAgentSeedingService_1.name);
    }
    async seed() {
        const deprecatedBuiltinKeys = ['config-manager'];
        for (const deprecatedKey of deprecatedBuiltinKeys) {
            const deprecatedAgent = await this.subAgentRepository.findOne({
                where: { builtin_key: deprecatedKey, is_builtin: true },
            });
            if (deprecatedAgent) {
                await this.subAgentRepository.remove(deprecatedAgent);
                this.logger.log(`Removed deprecated builtin sub-agent "${deprecatedAgent.name}" (builtin_key: ${deprecatedKey}).`);
            }
        }
        const existingAgents = await this.subAgentRepository.find({
            where: { is_active: true },
        });
        const existingAgentMap = new Map();
        existingAgents.forEach((a) => existingAgentMap.set(a.name, a));
        this.logger.log('Syncing sub-agents from files...');
        const seedFiles = await (0, glob_1.glob)(path.join(__dirname, 'data', 'sub-agents', '*.{ts,js}'));
        if (seedFiles.length === 0) {
            this.logger.warn('No sub-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, enabled_tools, enabled_mcp_tools, model_id, 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.subAgentRepository.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.enabled_tools =
                        enabled_tools || existingAgent.enabled_tools;
                    existingAgent.enabled_mcp_tools =
                        enabled_mcp_tools !== undefined
                            ? enabled_mcp_tools === 'all'
                                ? 'all'
                                : enabled_mcp_tools
                                    ? JSON.stringify(enabled_mcp_tools)
                                    : null
                            : existingAgent.enabled_mcp_tools;
                    existingAgent.model_id = model_id || existingAgent.model_id;
                    existingAgent.is_active = is_active !== false;
                    await this.subAgentRepository.save(existingAgent);
                    this.logger.log(`Built-in sub-agent "${name}" updated (version upgrade).`);
                }
                else if (existingAgent) {
                    this.logger.warn(`Sub-agent with builtin_key "${builtinKey}" exists but is not built-in. Skipping.`);
                }
                else {
                    const legacyAgent = existingAgentMap.get(name);
                    if (legacyAgent) {
                        this.logger.log(`Legacy sub-agent "${name}" exists without builtin_key. Skipping seed.`);
                    }
                    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 sub-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 sub-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 sub-agent "${name}"`);
                            }
                            else {
                                followup_context_template_id = followupContextTemplate.id;
                            }
                        }
                        const newAgent = this.subAgentRepository.create({
                            name,
                            description: description || null,
                            system_prompt_id,
                            context_template_id,
                            followup_context_template_id,
                            enabled_tools: enabled_tools || null,
                            enabled_mcp_tools: enabled_mcp_tools === 'all'
                                ? 'all'
                                : enabled_mcp_tools
                                    ? JSON.stringify(enabled_mcp_tools)
                                    : null,
                            model_id: model_id || null,
                            is_active: is_active !== false,
                            is_builtin: true,
                            builtin_key: builtinKey,
                        });
                        await this.subAgentRepository.save(newAgent);
                        this.logger.log(`Built-in sub-agent "${name}" seeded.`);
                    }
                }
            }
            catch (error) {
                this.logger.error(`Failed to seed sub-agent from ${filePath}`, error.stack);
            }
        }
        await this.fixDoubleSerializedMcpTools();
    }
    async fixDoubleSerializedMcpTools() {
        const allAgents = await this.subAgentRepository.find();
        let fixedCount = 0;
        for (const agent of allAgents) {
            if (agent.enabled_mcp_tools && agent.enabled_mcp_tools !== 'all') {
                try {
                    let parsed = JSON.parse(agent.enabled_mcp_tools);
                    let isDoubleSerialized = false;
                    while (typeof parsed === 'string') {
                        try {
                            parsed = JSON.parse(parsed);
                            isDoubleSerialized = true;
                        }
                        catch {
                            break;
                        }
                    }
                    if (isDoubleSerialized && Array.isArray(parsed)) {
                        agent.enabled_mcp_tools = JSON.stringify(parsed);
                        await this.subAgentRepository.save(agent);
                        fixedCount++;
                        this.logger.log(`Fixed double-serialized enabled_mcp_tools for sub-agent "${agent.name}": "${agent.enabled_mcp_tools}"`);
                    }
                }
                catch {
                }
            }
        }
        if (fixedCount > 0) {
            this.logger.log(`Fixed ${fixedCount} sub-agent(s) with double-serialized enabled_mcp_tools.`);
        }
    }
};
exports.SubAgentSeedingService = SubAgentSeedingService;
exports.SubAgentSeedingService = SubAgentSeedingService = SubAgentSeedingService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(sub_agent_entity_1.SubAgent)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        system_prompts_service_1.SystemPromptsService,
        context_templates_service_1.ContextTemplatesService])
], SubAgentSeedingService);
//# sourceMappingURL=sub-agent-seeding.service.js.map