"use strict";
/**
 * 🆕 FAF Update Checker - Keep users informed about new versions
 * Checks once per day, non-intrusive, respects quiet mode
 */
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.checkForUpdates = checkForUpdates;
exports.forceUpdateCheck = forceUpdateCheck;
const colors_1 = require("../fix-once/colors");
const fs_1 = require("fs");
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const https_1 = __importDefault(require("https"));
const championship_style_1 = require("./championship-style");
const announcements_1 = require("./announcements");
const CACHE_FILE = path.join(os.homedir(), '.faf-cli-cache', 'update-check.json');
const CHECK_INTERVAL = 24 * 60 * 60 * 1000; // 24 hours
const REGISTRY_URL = 'https://registry.npmjs.org/faf-cli/latest';
/**
 * Fetch latest version from npm registry
 */
async function fetchLatestVersion() {
    return new Promise((resolve) => {
        https_1.default.get(REGISTRY_URL, (res) => {
            let data = '';
            res.on('data', (chunk) => data += chunk);
            res.on('end', () => {
                try {
                    const json = JSON.parse(data);
                    resolve(json.version);
                }
                catch {
                    resolve(null);
                }
            });
        }).on('error', () => resolve(null));
    });
}
/**
 * Read update cache
 */
async function readCache() {
    try {
        await fs_1.promises.mkdir(path.dirname(CACHE_FILE), { recursive: true });
        const content = await fs_1.promises.readFile(CACHE_FILE, 'utf-8');
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
/**
 * Write update cache
 */
async function writeCache(cache) {
    try {
        await fs_1.promises.mkdir(path.dirname(CACHE_FILE), { recursive: true });
        await fs_1.promises.writeFile(CACHE_FILE, JSON.stringify(cache, null, 2));
    }
    catch {
        // Silent fail - not critical
    }
}
/**
 * Compare semantic versions
 */
function isNewerVersion(latest, current) {
    const parseVersion = (v) => {
        const parts = v.replace(/^v/, '').split('.').map(Number);
        return {
            major: parts[0] || 0,
            minor: parts[1] || 0,
            patch: parts[2] || 0
        };
    };
    const latestVer = parseVersion(latest);
    const currentVer = parseVersion(current);
    if (latestVer.major > currentVer.major)
        return true;
    if (latestVer.major < currentVer.major)
        return false;
    if (latestVer.minor > currentVer.minor)
        return true;
    if (latestVer.minor < currentVer.minor)
        return false;
    return latestVer.patch > currentVer.patch;
}
/**
 * Check for updates (respects quiet mode)
 */
async function checkForUpdates(options) {
    // Don't check in quiet mode
    if (options?.quiet)
        return;
    // Don't check in CI/CD environments
    if (process.env.CI || process.env.CONTINUOUS_INTEGRATION)
        return;
    try {
        const packageJson = require('../../package.json');
        const currentVersion = packageJson.version;
        // Check cache
        const cache = await readCache();
        const now = Date.now();
        // Skip if checked recently
        if (cache && (now - cache.lastCheck) < CHECK_INTERVAL) {
            // But still show if update available and not shown yet
            if (cache.latestVersion &&
                cache.currentVersion === currentVersion &&
                isNewerVersion(cache.latestVersion, currentVersion)) {
                showUpdateMessage(cache.latestVersion, currentVersion);
            }
            return;
        }
        // Fetch latest version
        const latestVersion = await fetchLatestVersion();
        if (!latestVersion)
            return;
        // Update cache
        await writeCache({
            lastCheck: now,
            latestVersion,
            currentVersion
        });
        // Show update if available
        if (isNewerVersion(latestVersion, currentVersion)) {
            showUpdateMessage(latestVersion, currentVersion);
        }
    }
    catch {
        // Silent fail - update check is not critical
    }
}
/**
 * Show update message
 */
function showUpdateMessage(latest, current) {
    // Use the new announcement system for cleaner display
    (0, announcements_1.showUpdateAvailable)(current, latest);
}
/**
 * Force check (for testing or manual trigger)
 */
async function forceUpdateCheck() {
    const packageJson = require('../../package.json');
    const currentVersion = packageJson.version;
    const latestVersion = await fetchLatestVersion();
    if (!latestVersion) {
        console.log(colors_1.chalk.red('Failed to check for updates'));
        return;
    }
    if (isNewerVersion(latestVersion, currentVersion)) {
        showUpdateMessage(latestVersion, currentVersion);
    }
    else {
        console.log(championship_style_1.FAF_COLORS.fafGreen(`✅ You're on the latest version (v${currentVersion})`));
    }
}
//# sourceMappingURL=update-checker.js.map