"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 ContextTemplateSeedingService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextTemplateSeedingService = void 0;
const common_1 = require("@nestjs/common");
const context_templates_service_1 = require("../context-templates/context-templates.service");
const path = require("path");
const glob_1 = require("glob");
let ContextTemplateSeedingService = ContextTemplateSeedingService_1 = class ContextTemplateSeedingService {
    constructor(contextTemplatesService) {
        this.contextTemplatesService = contextTemplatesService;
        this.logger = new common_1.Logger(ContextTemplateSeedingService_1.name);
    }
    async seed() {
        const deprecatedBuiltinKeys = [
            'config-manager-initial-context',
            'config-manager-followup-context',
        ];
        for (const deprecatedKey of deprecatedBuiltinKeys) {
            const deprecatedTemplate = await this.contextTemplatesService.findByBuiltinKey(deprecatedKey);
            if (deprecatedTemplate && deprecatedTemplate.is_builtin) {
                await this.contextTemplatesService.remove(deprecatedTemplate.id);
                this.logger.log(`Removed deprecated builtin template "${deprecatedTemplate.template_name}" (builtin_key: ${deprecatedKey}).`);
            }
        }
        const existingTemplates = await this.contextTemplatesService.findAll();
        const existingTemplatesMap = new Map();
        existingTemplates.forEach((t) => existingTemplatesMap.set(t.template_name, t));
        this.logger.log('Syncing context templates from files...');
        const seedFiles = await (0, glob_1.glob)(path.join(__dirname, 'data', 'context-templates', '*.{ts,js}'));
        if (seedFiles.length === 0) {
            this.logger.warn('No context template seed files found.');
            return;
        }
        for (const filePath of seedFiles) {
            try {
                const templateModule = await Promise.resolve(`${filePath}`).then(s => require(s));
                const templateName = templateModule.template_name;
                const templateContent = templateModule.template_content;
                const fileName = path.basename(filePath);
                if (!templateName || !templateContent || templateContent.length === 0) {
                    this.logger.warn(`Skipping malformed seed file: ${fileName}`);
                    continue;
                }
                const builtinKey = fileName
                    .replace(/\.(ts|js)$/, '')
                    .replace(/_/g, '-');
                const existingTemplate = await this.contextTemplatesService.findByBuiltinKey(builtinKey);
                if (existingTemplate && existingTemplate.is_builtin) {
                    await this.contextTemplatesService.updateBuiltinContent(existingTemplate.id, templateContent);
                    this.logger.log(`Built-in template "${templateName}" updated (version upgrade).`);
                }
                else if (existingTemplate) {
                    this.logger.warn(`Template with builtin_key "${builtinKey}" exists but is not built-in. Skipping.`);
                }
                else {
                    const legacyTemplate = existingTemplatesMap.get(templateName);
                    if (legacyTemplate) {
                        this.logger.log(`Legacy template "${templateName}" exists without builtin_key. Skipping seed.`);
                    }
                    else {
                        const newTemplate = await this.contextTemplatesService.create({
                            template_name: templateName,
                            template_content: templateContent,
                            is_builtin: true,
                            builtin_key: builtinKey,
                        });
                        if (fileName.startsWith('default-initial_condensed')) {
                            await this.contextTemplatesService.setDefaultCondensed(newTemplate.id);
                            this.logger.log(`Built-in template "${templateName}" seeded and set as default condensed.`);
                        }
                        else if (fileName.startsWith('default-initial_')) {
                            await this.contextTemplatesService.setDefaultInitial(newTemplate.id);
                            this.logger.log(`Built-in template "${templateName}" seeded and set as default initial.`);
                        }
                        else if (fileName.startsWith('default-followup_')) {
                            await this.contextTemplatesService.setDefaultFollowup(newTemplate.id);
                            this.logger.log(`Built-in template "${templateName}" seeded and set as default follow-up.`);
                        }
                        else {
                            this.logger.log(`Built-in template "${templateName}" seeded.`);
                        }
                    }
                }
            }
            catch (error) {
                this.logger.error(`Failed to seed context template from ${filePath}`, error.stack);
            }
        }
    }
};
exports.ContextTemplateSeedingService = ContextTemplateSeedingService;
exports.ContextTemplateSeedingService = ContextTemplateSeedingService = ContextTemplateSeedingService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [context_templates_service_1.ContextTemplatesService])
], ContextTemplateSeedingService);
//# sourceMappingURL=context-template-seeding.service.js.map