"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
async function update(tree) {
    devkit_1.logger.info('🔄 Updating .gitignore to add migration-related entries...');
    const gitignorePath = '.gitignore';
    if (!tree.exists(gitignorePath)) {
        devkit_1.logger.warn('⚠️ .gitignore file not found, creating one');
        tree.write(gitignorePath, '');
    }
    try {
        const currentContent = tree.read(gitignorePath, 'utf-8') || '';
        let updatedContent = currentContent;
        let addedItems = 0;
        // Check if migrations.json is already in .gitignore
        const migrationsJsonRegex = /^migrations\.json\s*$/gm;
        if (!migrationsJsonRegex.test(updatedContent)) {
            // Add migrations.json entry
            if (!updatedContent.includes('# Migration files')) {
                updatedContent = updatedContent.trim() + '\n\n# Migration files\n';
            }
            if (!updatedContent.includes('migrations.json')) {
                updatedContent += 'migrations.json\n';
                addedItems++;
                devkit_1.logger.info('📝 Added migrations.json to .gitignore');
            }
        }
        // Check if ai-migrations is already in .gitignore
        const aiMigrationsRegex = /^ai-migrations\s*$/gm;
        if (!aiMigrationsRegex.test(updatedContent)) {
            // Add ai-migrations entry
            if (!updatedContent.includes('# Migration files')) {
                updatedContent = updatedContent.trim() + '\n\n# Migration files\n';
            }
            if (!updatedContent.includes('ai-migrations')) {
                updatedContent += 'ai-migrations\n';
                addedItems++;
                devkit_1.logger.info('📝 Added ai-migrations to .gitignore');
            }
        }
        if (addedItems > 0) {
            tree.write(gitignorePath, updatedContent);
            devkit_1.logger.info(`✅ Successfully updated .gitignore (added ${addedItems} entries)`);
        }
        else {
            devkit_1.logger.info('ℹ️ Migration-related entries already exist in .gitignore');
        }
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        devkit_1.logger.error(`❌ Failed to update .gitignore: ${errorMessage}`);
        throw new Error(`Failed to update .gitignore: ${errorMessage}`);
    }
}
