"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.updateCommand = updateCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
async function updateCommand(options) {
    try {
        console.log(chalk_1.default.blue('\n🔄 Updating modules...\n'));
        // 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'));
        if (!config.modules || config.modules.length === 0) {
            console.log(chalk_1.default.yellow('No modules linked. Use "augx link <module>" to link modules.'));
            return;
        }
        const modulesToUpdate = options.module
            ? config.modules.filter((m) => m.name === options.module)
            : config.modules;
        if (modulesToUpdate.length === 0) {
            console.error(chalk_1.default.red(`Module not found: ${options.module}`));
            process.exit(1);
        }
        let updatedCount = 0;
        let upToDateCount = 0;
        let errorCount = 0;
        for (const linkedModule of modulesToUpdate) {
            const result = await updateModule(linkedModule, config);
            if (result === 'updated') {
                updatedCount++;
            }
            else if (result === 'up-to-date') {
                upToDateCount++;
            }
            else {
                errorCount++;
            }
        }
        // Save updated config
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
        console.log(chalk_1.default.bold.green('\n✨ Update complete!\n'));
        console.log(chalk_1.default.gray(`Updated: ${updatedCount}`));
        console.log(chalk_1.default.gray(`Up to date: ${upToDateCount}`));
        if (errorCount > 0) {
            console.log(chalk_1.default.red(`Errors: ${errorCount}`));
        }
        console.log();
    }
    catch (error) {
        console.error(chalk_1.default.red('Error updating modules:'), error);
        process.exit(1);
    }
}
async function updateModule(linkedModule, config) {
    try {
        const modulesDir = path.join(__dirname, '../../../augment-extensions');
        const modulePath = path.join(modulesDir, linkedModule.name);
        const moduleJsonPath = path.join(modulePath, 'module.json');
        if (!fs.existsSync(moduleJsonPath)) {
            console.log(chalk_1.default.red(`✗ ${linkedModule.name}: Module not found`));
            return 'error';
        }
        const moduleData = JSON.parse(fs.readFileSync(moduleJsonPath, 'utf-8'));
        const latestVersion = moduleData.version;
        const currentVersion = linkedModule.version;
        if (latestVersion === currentVersion) {
            console.log(chalk_1.default.gray(`○ ${linkedModule.name}: Already up to date (v${currentVersion})`));
            return 'up-to-date';
        }
        // Check if it's a newer version
        if (compareVersions(latestVersion, currentVersion) > 0) {
            // Update in config
            const moduleIndex = config.modules.findIndex((m) => m.name === linkedModule.name);
            if (moduleIndex >= 0) {
                config.modules[moduleIndex].version = latestVersion;
                config.modules[moduleIndex].description = moduleData.description;
            }
            console.log(chalk_1.default.green(`✓ ${linkedModule.name}: Updated ${currentVersion} → ${latestVersion}`));
            return 'updated';
        }
        else {
            console.log(chalk_1.default.yellow(`⚠ ${linkedModule.name}: Current version (${currentVersion}) is newer than available (${latestVersion})`));
            return 'up-to-date';
        }
    }
    catch (error) {
        console.log(chalk_1.default.red(`✗ ${linkedModule.name}: Error updating - ${error}`));
        return 'error';
    }
}
function compareVersions(v1, v2) {
    const parts1 = v1.split('.').map(Number);
    const parts2 = v2.split('.').map(Number);
    for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
        const part1 = parts1[i] || 0;
        const part2 = parts2[i] || 0;
        if (part1 > part2)
            return 1;
        if (part1 < part2)
            return -1;
    }
    return 0;
}
//# sourceMappingURL=update.js.map