"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 SystemPromptSeedingService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SystemPromptSeedingService = void 0;
const common_1 = require("@nestjs/common");
const system_prompts_service_1 = require("../system-prompts/system-prompts.service");
const path = require("path");
const glob_1 = require("glob");
let SystemPromptSeedingService = SystemPromptSeedingService_1 = class SystemPromptSeedingService {
    constructor(systemPromptsService) {
        this.systemPromptsService = systemPromptsService;
        this.logger = new common_1.Logger(SystemPromptSeedingService_1.name);
    }
    async seed() {
        const existingPrompts = await this.systemPromptsService.findAllRaw();
        const existingPromptsMap = new Map();
        existingPrompts.forEach((p) => existingPromptsMap.set(p.prompt_name, p));
        const deprecatedBuiltinKeys = ['master-agent', 'config-manager-agent'];
        for (const deprecatedKey of deprecatedBuiltinKeys) {
            const deprecatedPrompt = await this.systemPromptsService.findByBuiltinKey(deprecatedKey);
            if (deprecatedPrompt && deprecatedPrompt.is_builtin) {
                await this.systemPromptsService.remove(deprecatedPrompt.id);
                this.logger.log(`Removed deprecated builtin prompt "${deprecatedPrompt.prompt_name}" (builtin_key: ${deprecatedKey}).`);
            }
        }
        this.logger.log('Syncing system prompts from files...');
        const seedFiles = await (0, glob_1.glob)(path.join(__dirname, 'data', 'system-prompts', '*.{ts,js}'));
        if (seedFiles.length === 0) {
            this.logger.warn('No system prompt seed files found.');
            return;
        }
        for (const filePath of seedFiles) {
            try {
                const promptModule = await Promise.resolve(`${filePath}`).then(s => require(s));
                const promptName = promptModule.name;
                const promptContent = promptModule.content;
                const enabledTools = promptModule.enabled_tools || 'all';
                const enabledMcpTools = promptModule.enabled_mcp_tools;
                const fileName = path.basename(filePath);
                if (!promptName || !promptContent || promptContent.length === 0) {
                    this.logger.warn(`Skipping malformed seed file: ${fileName}`);
                    continue;
                }
                const builtinKey = fileName
                    .replace(/\.(ts|js)$/, '')
                    .replace(/_/g, '-');
                const existingPrompt = await this.systemPromptsService.findByBuiltinKey(builtinKey);
                if (existingPrompt && existingPrompt.is_builtin) {
                    await this.systemPromptsService.updateBuiltinContent(existingPrompt.id, promptContent, enabledTools, enabledMcpTools !== undefined ? enabledMcpTools : undefined);
                    this.logger.log(`Built-in prompt "${promptName}" updated (version upgrade).`);
                }
                else if (existingPrompt) {
                    this.logger.warn(`Prompt with builtin_key "${builtinKey}" exists but is not built-in. Skipping.`);
                }
                else {
                    const legacyPrompt = existingPromptsMap.get(promptName);
                    if (legacyPrompt) {
                        this.logger.log(`Legacy prompt "${promptName}" exists without builtin_key. Skipping seed.`);
                    }
                    else {
                        const newPrompt = await this.systemPromptsService.create({
                            prompt_name: promptName,
                            prompt_content: promptContent,
                            enabledTools: enabledTools,
                            enabledMcpTools: enabledMcpTools !== undefined ? enabledMcpTools : 'all',
                            is_builtin: true,
                            builtin_key: builtinKey,
                        });
                        if (fileName.startsWith('default_')) {
                            await this.systemPromptsService.setDefault(newPrompt.id);
                            this.logger.log(`Built-in prompt "${promptName}" seeded and set as default.`);
                        }
                        else {
                            this.logger.log(`Built-in prompt "${promptName}" seeded.`);
                        }
                    }
                }
            }
            catch (error) {
                this.logger.error(`Failed to seed system prompt from ${filePath}`, error.stack);
            }
        }
    }
};
exports.SystemPromptSeedingService = SystemPromptSeedingService;
exports.SystemPromptSeedingService = SystemPromptSeedingService = SystemPromptSeedingService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [system_prompts_service_1.SystemPromptsService])
], SystemPromptSeedingService);
//# sourceMappingURL=system-prompt-seeding.service.js.map