"use strict";
/**
 * Migration: Update .gitignore to exclude Claude Code files
 *
 * Adds .claude/* directory to .gitignore to prevent Claude Code files from being committed,
 * while preserving the skills directory (!.claudes/skills).
 */
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 exclude Claude Code files...');
    const gitignorePath = '.gitignore';
    // Step 1: Create file if it doesn't exist
    if (!tree.exists(gitignorePath)) {
        devkit_1.logger.warn('⚠️ .gitignore file not found, creating one');
        tree.write(gitignorePath, '');
    }
    try {
        // Step 2: Read current content
        const currentContent = tree.read(gitignorePath, 'utf-8') || '';
        let updatedContent = currentContent;
        let hasChanges = false;
        // Step 3: Add section comment if needed
        if (!updatedContent.includes('# Claude Code files')) {
            updatedContent = updatedContent.trim() + '\n\n# Claude Code files\n';
            hasChanges = true;
        }
        // Step 4: Check and add .claude/* entry
        const claudePatternRegex = /^\.claude\/\*\s*$/gm;
        if (!claudePatternRegex.test(updatedContent)) {
            if (!updatedContent.includes('.claude/*')) {
                updatedContent += '.claude/*\n';
                devkit_1.logger.info('📝 Added .claude/* to .gitignore');
                hasChanges = true;
            }
        }
        else {
            devkit_1.logger.info('ℹ️ .claude/* already exists in .gitignore');
        }
        // Step 5: Check and add !.claudes/skills entry
        const claudesSkillsRegex = /^!\.claudes\/skills\s*$/gm;
        if (!claudesSkillsRegex.test(updatedContent)) {
            if (!updatedContent.includes('!.claudes/skills')) {
                updatedContent += '!.claudes/skills\n';
                devkit_1.logger.info('📝 Added !.claudes/skills to .gitignore');
                hasChanges = true;
            }
        }
        else {
            devkit_1.logger.info('ℹ️ !.claudes/skills already exists in .gitignore');
        }
        // Step 6: Write back if there are changes
        if (hasChanges) {
            tree.write(gitignorePath, updatedContent);
            devkit_1.logger.info('✅ Successfully updated .gitignore');
        }
        else {
            devkit_1.logger.info('ℹ️ .gitignore already up to date');
        }
        await (0, devkit_1.formatFiles)(tree);
    }
    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}`);
    }
}
