"use strict";
/**
 * Version Cache Manager
 * Handles reading/writing version cache to avoid excessive GitHub API calls.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeVersionListCache = exports.readStaleVersionListCache = exports.readVersionListCache = exports.getVersionListCachePath = exports.migrateVersionPin = exports.isVersionPinned = exports.clearPinnedVersion = exports.savePinnedVersion = exports.getPinnedVersion = exports.writeInstalledVersion = exports.readInstalledVersion = exports.writeVersionCache = exports.readStaleVersionCache = exports.readVersionCache = exports.getVersionPinPath = exports.getVersionCachePath = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_generator_1 = require("../config/config-generator");
const types_1 = require("./types");
const platform_detector_1 = require("../binary/platform-detector");
/**
 * Get path to version cache file (backend-specific)
 */
function getVersionCachePath(backend = platform_detector_1.DEFAULT_BACKEND) {
    return path.join((0, config_generator_1.getBinDir)(), backend, '.version-cache.json');
}
exports.getVersionCachePath = getVersionCachePath;
/**
 * Get path to version pin file (backend-specific)
 */
function getVersionPinPath(backend = platform_detector_1.DEFAULT_BACKEND) {
    return path.join((0, config_generator_1.getBinDir)(), backend, types_1.VERSION_PIN_FILE);
}
exports.getVersionPinPath = getVersionPinPath;
/**
 * Read version cache if still valid (backend-specific)
 */
function readVersionCache(backend = platform_detector_1.DEFAULT_BACKEND) {
    return readVersionCacheInternal(backend, false);
}
exports.readVersionCache = readVersionCache;
/**
 * Read version cache even if expired.
 * Used as a resilience fallback when GitHub release lookups fail.
 */
function readStaleVersionCache(backend = platform_detector_1.DEFAULT_BACKEND) {
    return readVersionCacheInternal(backend, true);
}
exports.readStaleVersionCache = readStaleVersionCache;
function readVersionCacheInternal(backend, allowExpired) {
    const cachePath = getVersionCachePath(backend);
    if (!fs.existsSync(cachePath)) {
        return null;
    }
    try {
        const content = fs.readFileSync(cachePath, 'utf8');
        const cache = JSON.parse(content);
        // Check if cache is still valid, unless caller explicitly allows stale fallback.
        if (allowExpired || Date.now() - cache.checkedAt < types_1.VERSION_CACHE_DURATION_MS) {
            return cache;
        }
        // Cache expired
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Write version to cache (backend-specific)
 */
function writeVersionCache(version, backend = platform_detector_1.DEFAULT_BACKEND) {
    const cachePath = getVersionCachePath(backend);
    const cache = {
        latestVersion: version,
        checkedAt: Date.now(),
    };
    try {
        fs.mkdirSync(path.dirname(cachePath), { recursive: true });
        fs.writeFileSync(cachePath, JSON.stringify(cache), 'utf8');
    }
    catch {
        // Silent fail - caching is optional
    }
}
exports.writeVersionCache = writeVersionCache;
/**
 * Read installed version from .version file
 */
function readInstalledVersion(binPath, fallbackVersion) {
    const versionFile = path.join(binPath, '.version');
    if (fs.existsSync(versionFile)) {
        try {
            return fs.readFileSync(versionFile, 'utf8').trim();
        }
        catch {
            return fallbackVersion;
        }
    }
    return fallbackVersion;
}
exports.readInstalledVersion = readInstalledVersion;
/**
 * Write installed version to .version file
 */
function writeInstalledVersion(binPath, version) {
    const versionFile = path.join(binPath, '.version');
    try {
        fs.writeFileSync(versionFile, version, 'utf8');
    }
    catch {
        // Silent fail - not critical
    }
}
exports.writeInstalledVersion = writeInstalledVersion;
/**
 * Get pinned version if one exists (backend-specific)
 */
function getPinnedVersion(backend = platform_detector_1.DEFAULT_BACKEND) {
    const pinPath = getVersionPinPath(backend);
    if (!fs.existsSync(pinPath)) {
        return null;
    }
    try {
        return fs.readFileSync(pinPath, 'utf8').trim();
    }
    catch {
        return null;
    }
}
exports.getPinnedVersion = getPinnedVersion;
/**
 * Save pinned version to persist user's explicit choice (backend-specific)
 */
function savePinnedVersion(version, backend = platform_detector_1.DEFAULT_BACKEND) {
    const pinPath = getVersionPinPath(backend);
    try {
        fs.mkdirSync(path.dirname(pinPath), { recursive: true });
        fs.writeFileSync(pinPath, version, 'utf8');
    }
    catch {
        // Silent fail - not critical
    }
}
exports.savePinnedVersion = savePinnedVersion;
/**
 * Clear pinned version (unpin) - backend-specific
 */
function clearPinnedVersion(backend = platform_detector_1.DEFAULT_BACKEND) {
    const pinPath = getVersionPinPath(backend);
    if (fs.existsSync(pinPath)) {
        try {
            fs.unlinkSync(pinPath);
        }
        catch {
            // Silent fail
        }
    }
}
exports.clearPinnedVersion = clearPinnedVersion;
/**
 * Check if a version is currently pinned (backend-specific)
 */
function isVersionPinned(backend = platform_detector_1.DEFAULT_BACKEND) {
    return getPinnedVersion(backend) !== null;
}
exports.isVersionPinned = isVersionPinned;
/**
 * Migrate old shared version pin to backend-specific location.
 * Called once on first run after update.
 */
function migrateVersionPin(backend) {
    const oldPinPath = path.join((0, config_generator_1.getBinDir)(), types_1.VERSION_PIN_FILE);
    if (!fs.existsSync(oldPinPath))
        return;
    try {
        const oldVersion = fs.readFileSync(oldPinPath, 'utf8').trim();
        if (!oldVersion)
            return;
        // Save to new backend-specific location
        savePinnedVersion(oldVersion, backend);
        // Delete old shared file
        fs.unlinkSync(oldPinPath);
    }
    catch {
        // Silent fail - not critical
    }
}
exports.migrateVersionPin = migrateVersionPin;
// ==================== Version List Cache ====================
const VERSION_LIST_CACHE_FILE = '.version-list-cache.json';
/**
 * Get path to version list cache file (backend-specific)
 */
function getVersionListCachePath(backend = platform_detector_1.DEFAULT_BACKEND) {
    return path.join((0, config_generator_1.getBinDir)(), backend, VERSION_LIST_CACHE_FILE);
}
exports.getVersionListCachePath = getVersionListCachePath;
/**
 * Read version list cache if still valid (backend-specific)
 */
function readVersionListCache(backend = platform_detector_1.DEFAULT_BACKEND) {
    return readVersionListCacheInternal(backend, false);
}
exports.readVersionListCache = readVersionListCache;
/**
 * Read version list cache even if expired.
 * Used as a resilience fallback when GitHub release lookups fail.
 */
function readStaleVersionListCache(backend = platform_detector_1.DEFAULT_BACKEND) {
    return readVersionListCacheInternal(backend, true);
}
exports.readStaleVersionListCache = readStaleVersionListCache;
function readVersionListCacheInternal(backend, allowExpired) {
    const cachePath = getVersionListCachePath(backend);
    if (!fs.existsSync(cachePath)) {
        return null;
    }
    try {
        const content = fs.readFileSync(cachePath, 'utf8');
        const cache = JSON.parse(content);
        // Check if cache is still valid, unless caller explicitly allows stale fallback.
        if (allowExpired || Date.now() - cache.checkedAt < types_1.VERSION_CACHE_DURATION_MS) {
            return cache;
        }
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Write version list to cache (backend-specific)
 */
function writeVersionListCache(cache, backend = platform_detector_1.DEFAULT_BACKEND) {
    const cachePath = getVersionListCachePath(backend);
    try {
        fs.mkdirSync(path.dirname(cachePath), { recursive: true });
        fs.writeFileSync(cachePath, JSON.stringify(cache), 'utf8');
    }
    catch {
        // Silent fail - caching is optional
    }
}
exports.writeVersionListCache = writeVersionListCache;
//# sourceMappingURL=version-cache.js.map