"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.selfRemoveCommand = selfRemoveCommand;
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
async function selfRemoveCommand(options = {}) {
    try {
        console.log(chalk_1.default.red('\n⚠️  Augment Extensions Self-Removal\n'));
        const augmentDir = path.join(process.cwd(), '.augment');
        if (!fs.existsSync(augmentDir)) {
            console.log(chalk_1.default.yellow('Augment Extensions not found in this project.'));
            return;
        }
        // Collect files to be removed
        const filesToRemove = collectFilesToRemove(augmentDir);
        if (options.dryRun) {
            console.log(chalk_1.default.blue('Dry-run mode: The following files would be removed:\n'));
            filesToRemove.forEach(file => {
                console.log(chalk_1.default.gray(`  - ${file}`));
            });
            console.log(chalk_1.default.blue(`\nTotal: ${filesToRemove.length} file(s)`));
            return;
        }
        // Display what will be removed
        console.log(chalk_1.default.yellow('The following will be removed:\n'));
        console.log(chalk_1.default.gray(`  - .augment/ directory (${filesToRemove.length} files)`));
        console.log(chalk_1.default.gray(`  - VS Code extensions.json entries (if any)`));
        console.log(chalk_1.default.gray(`  - augx CLI tool (if installed globally)`));
        // Confirmation prompt
        if (!options.force) {
            const { confirm } = await inquirer_1.default.prompt([
                {
                    type: 'confirm',
                    name: 'confirm',
                    message: chalk_1.default.red('Are you sure you want to remove all Augment Extensions?'),
                    default: false
                }
            ]);
            if (!confirm) {
                console.log(chalk_1.default.yellow('Cancelled.'));
                return;
            }
            // Double confirmation
            const { doubleConfirm } = await inquirer_1.default.prompt([
                {
                    type: 'input',
                    name: 'doubleConfirm',
                    message: 'Type "REMOVE" to confirm:',
                    validate: (input) => input === 'REMOVE' || 'You must type "REMOVE" to confirm'
                }
            ]);
            if (doubleConfirm !== 'REMOVE') {
                console.log(chalk_1.default.yellow('Cancelled.'));
                return;
            }
        }
        // Calculate checksums before removal
        console.log(chalk_1.default.blue('\nCalculating checksums...'));
        const checksums = calculateChecksums(filesToRemove);
        // Perform removal
        console.log(chalk_1.default.blue('Removing Augment Extensions...\n'));
        // Remove .augment directory
        if (fs.existsSync(augmentDir)) {
            fs.rmSync(augmentDir, { recursive: true, force: true });
            console.log(chalk_1.default.green('✓ Removed .augment/ directory'));
        }
        // Clean up VS Code extensions.json
        const vscodeDir = path.join(process.cwd(), '.vscode');
        const extensionsJsonPath = path.join(vscodeDir, 'extensions.json');
        if (fs.existsSync(extensionsJsonPath)) {
            try {
                const extensionsJson = JSON.parse(fs.readFileSync(extensionsJsonPath, 'utf-8'));
                // Remove Augment-related recommendations
                if (extensionsJson.recommendations) {
                    const originalLength = extensionsJson.recommendations.length;
                    extensionsJson.recommendations = extensionsJson.recommendations.filter((ext) => !ext.includes('augment'));
                    if (extensionsJson.recommendations.length < originalLength) {
                        fs.writeFileSync(extensionsJsonPath, JSON.stringify(extensionsJson, null, 2));
                        console.log(chalk_1.default.green('✓ Cleaned VS Code extensions.json'));
                    }
                }
            }
            catch (error) {
                console.log(chalk_1.default.yellow('⚠ Could not clean VS Code extensions.json'));
            }
        }
        // Log removal
        const logPath = path.join(process.cwd(), '.augment-removal.log');
        const logContent = {
            timestamp: new Date().toISOString(),
            filesRemoved: filesToRemove.length,
            checksums,
            success: true
        };
        fs.writeFileSync(logPath, JSON.stringify(logContent, null, 2));
        console.log(chalk_1.default.green('\n✓ Augment Extensions successfully removed!'));
        console.log(chalk_1.default.gray(`\nRemoval log saved to: ${logPath}`));
        console.log(chalk_1.default.blue('\nTo reinstall Augment Extensions:'));
        console.log(chalk_1.default.gray('  npm install -g @mytechtoday/augment-extensions'));
        console.log(chalk_1.default.gray('  augx init'));
    }
    catch (error) {
        console.error(chalk_1.default.red(`Error: ${error.message}`));
        process.exit(1);
    }
}
function collectFilesToRemove(augmentDir) {
    const files = [];
    function walkDir(dir) {
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                walkDir(fullPath);
            }
            else {
                files.push(fullPath);
            }
        }
    }
    if (fs.existsSync(augmentDir)) {
        walkDir(augmentDir);
    }
    return files;
}
function calculateChecksums(files) {
    const checksums = {};
    for (const file of files) {
        try {
            const content = fs.readFileSync(file);
            const hash = crypto.createHash('sha256').update(content).digest('hex');
            checksums[file] = hash;
        }
        catch (error) {
            // Skip files that can't be read
        }
    }
    return checksums;
}
//# sourceMappingURL=self-remove.js.map