"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.unlinkCommand = unlinkCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const module_system_1 = require("../utils/module-system");
async function unlinkCommand(moduleName, options = {}) {
    try {
        console.log(chalk_1.default.blue(`Unlinking module: ${moduleName}`));
        // Load extensions config
        const configPath = path.join(process.cwd(), '.augment', 'extensions.json');
        if (!fs.existsSync(configPath)) {
            console.error(chalk_1.default.red('Augment Extensions not initialized. Run: augx init'));
            process.exit(1);
        }
        const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
        // Check if it's a collection
        const collections = (0, module_system_1.discoverCollections)();
        const collection = collections.find(c => c.fullName === moduleName || c.metadata.name === moduleName);
        if (collection) {
            await unlinkCollection(collection, config, configPath, options);
            return;
        }
        // Check if module is linked
        const moduleIndex = config.modules.findIndex((m) => m.name === moduleName);
        if (moduleIndex === -1) {
            console.log(chalk_1.default.yellow(`Module not linked: ${moduleName}`));
            return;
        }
        // Check for dependencies
        const dependentModules = config.modules.filter((m) => m.dependencies && m.dependencies.includes(moduleName));
        if (dependentModules.length > 0 && !options.force) {
            console.error(chalk_1.default.red(`\nCannot unlink ${moduleName}. The following modules depend on it:\n`));
            dependentModules.forEach((m) => {
                console.error(chalk_1.default.red(`  - ${m.name}`));
            });
            console.error(chalk_1.default.yellow('\nUse --force to unlink anyway (may break dependent modules)'));
            process.exit(1);
        }
        // Remove from config
        config.modules.splice(moduleIndex, 1);
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
        console.log(chalk_1.default.green(`✓ Successfully unlinked: ${moduleName}`));
        if (dependentModules.length > 0) {
            console.log(chalk_1.default.yellow('\n⚠ Warning: The following modules may be affected:'));
            dependentModules.forEach((m) => {
                console.log(chalk_1.default.yellow(`  - ${m.name}`));
            });
        }
    }
    catch (error) {
        console.error(chalk_1.default.red(`Error: ${error.message}`));
        process.exit(1);
    }
}
async function unlinkCollection(collection, config, configPath, options) {
    console.log(chalk_1.default.blue(`\nUnlinking collection: ${collection.metadata.displayName}\n`));
    console.log(chalk_1.default.gray(`This will unlink ${collection.metadata.modules.length} module(s):\n`));
    for (const module of collection.metadata.modules) {
        console.log(chalk_1.default.gray(`  - ${module.id}`));
    }
    // Unlink all modules in the collection
    let unlinkedCount = 0;
    for (const module of collection.metadata.modules) {
        const moduleIndex = config.modules.findIndex((m) => m.name === module.id);
        if (moduleIndex >= 0) {
            config.modules.splice(moduleIndex, 1);
            unlinkedCount++;
            console.log(chalk_1.default.green(`  ✓ Unlinked: ${module.id}`));
        }
        else {
            console.log(chalk_1.default.gray(`  - Skipped (not linked): ${module.id}`));
        }
    }
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    console.log(chalk_1.default.green(`\n✓ Successfully unlinked collection (${unlinkedCount} modules removed)`));
}
//# sourceMappingURL=unlink.js.map