"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkForUpdates = checkForUpdates;
const colors_1 = require("./colors");
const logger_1 = require("./logger");
const pacakge_json_helper_1 = require("./pacakge.json.helper");
const clack = __importStar(require("@clack/prompts"));
const logger = logger_1.Logger.getInstance("version-check");
/**
 * Compare two semver version strings
 * Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2
 */
function compareVersions(v1, v2) {
    const parts1 = v1.replace(/^v/, "").split(".").map(Number);
    const parts2 = v2.replace(/^v/, "").split(".").map(Number);
    for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
        const p1 = parts1[i] || 0;
        const p2 = parts2[i] || 0;
        if (p1 < p2)
            return -1;
        if (p1 > p2)
            return 1;
    }
    return 0;
}
/**
 * Check if a newer version of the CLI is available on npm
 * Logs a warning message if an update is available
 */
async function checkForUpdates() {
    try {
        const packageName = "@interopio/iocd-cli";
        const currentVersion = pacakge_json_helper_1.PackageJSONHelper.getCliPackageJson().version;
        logger.debug(`Checking for updates... Current version: ${currentVersion}`);
        // Fetch latest version from npm registry with a short timeout
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 3000); // 3 second timeout
        const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`, {
            signal: controller.signal,
            headers: {
                Accept: "application/json",
            },
        });
        clearTimeout(timeoutId);
        if (!response.ok) {
            logger.debug(`Failed to fetch npm registry: ${response.status}`);
            return;
        }
        const data = (await response.json());
        const latestVersion = data.version;
        logger.debug(`Latest version on npm: ${latestVersion}`);
        if (compareVersions(currentVersion, latestVersion) < 0) {
            // Current version is older than latest
            clack.log.warn((0, colors_1.yellow)(`A new version of ${packageName} is available: ${latestVersion} (current: ${currentVersion}). Run npm i ${packageName}@latest to update.`));
            logger.debug("A new version of ${packageName} is available: ${latestVersion} (current: ${currentVersion})");
        }
    }
    catch (error) {
        // Silently fail - don't block CLI execution for version check failures
        if (error instanceof Error && error.name === "AbortError") {
            logger.debug("Version check timed out");
        }
        else {
            logger.debug(`Version check failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
    }
}
//# sourceMappingURL=version-check.js.map