"use strict";
/**
 * CLIProxy Binary Service
 *
 * Handles CLIProxyAPI binary version management:
 * - Get current version status
 * - Install specific versions
 * - Install latest version
 * - Version pinning
 */
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.clearPin = exports.getPinned = exports.isPinned = exports.installLatest = exports.installVersion = exports.isValidVersionFormat = exports.checkLatestVersion = exports.getBinaryStatus = void 0;
const binary_manager_1 = require("../binary-manager");
const platform_detector_1 = require("../binary/platform-detector");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/**
 * Get current binary status for a specific backend
 */
function getBinaryStatus(backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    const backendConfig = platform_detector_1.BACKEND_CONFIG[effectiveBackend];
    return {
        installed: (0, binary_manager_1.isCLIProxyInstalled)(effectiveBackend),
        currentVersion: (0, binary_manager_1.getInstalledCliproxyVersion)(effectiveBackend),
        pinnedVersion: (0, binary_manager_1.getPinnedVersion)(effectiveBackend),
        binaryPath: (0, binary_manager_1.getCLIProxyPath)(effectiveBackend),
        fallbackVersion: backendConfig.fallbackVersion,
        backend: effectiveBackend,
    };
}
exports.getBinaryStatus = getBinaryStatus;
/**
 * Check for latest version
 */
async function checkLatestVersion(backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    try {
        // Use checkCliproxyUpdate which is backend-aware (uses correct GitHub repo)
        const { checkCliproxyUpdate } = await Promise.resolve().then(() => __importStar(require('../binary-manager')));
        const updateResult = await checkCliproxyUpdate(effectiveBackend);
        const latestVersion = updateResult.latestVersion;
        const currentVersion = (0, binary_manager_1.getInstalledCliproxyVersion)(effectiveBackend);
        const updateAvailable = latestVersion !== currentVersion;
        return {
            success: true,
            latestVersion,
            currentVersion: currentVersion || undefined,
            updateAvailable,
        };
    }
    catch (error) {
        return {
            success: false,
            error: error.message,
        };
    }
}
exports.checkLatestVersion = checkLatestVersion;
/**
 * Validate version format (supports X.Y.Z or X.Y.Z-N suffix)
 */
function isValidVersionFormat(version) {
    return /^\d+\.\d+\.\d+(-\d+)?$/.test(version);
}
exports.isValidVersionFormat = isValidVersionFormat;
/**
 * Install a specific version and pin it
 */
async function installVersion(version, verbose = false, backend) {
    if (!isValidVersionFormat(version)) {
        return {
            success: false,
            version,
            error: 'Invalid version format. Expected format: X.Y.Z (e.g., 6.5.53)',
        };
    }
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    try {
        await (0, binary_manager_1.installCliproxyVersion)(version, verbose, effectiveBackend);
        (0, binary_manager_1.savePinnedVersion)(version, effectiveBackend);
        return {
            success: true,
            version,
            wasPinned: true,
        };
    }
    catch (error) {
        return {
            success: false,
            version,
            error: error.message,
        };
    }
}
exports.installVersion = installVersion;
/**
 * Install latest version and clear any pin
 */
async function installLatest(verbose = false, backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    try {
        const latestVersion = await (0, binary_manager_1.fetchLatestCliproxyVersion)(effectiveBackend);
        const currentVersion = (0, binary_manager_1.getInstalledCliproxyVersion)(effectiveBackend);
        const wasPinned = (0, binary_manager_1.isVersionPinned)(effectiveBackend);
        if ((0, binary_manager_1.isCLIProxyInstalled)(effectiveBackend) && latestVersion === currentVersion && !wasPinned) {
            return {
                success: true,
                version: latestVersion,
                error: `Already running latest version: v${latestVersion}`,
            };
        }
        await (0, binary_manager_1.installCliproxyVersion)(latestVersion, verbose, effectiveBackend);
        (0, binary_manager_1.clearPinnedVersion)(effectiveBackend);
        return {
            success: true,
            version: latestVersion,
            wasPinned,
        };
    }
    catch (error) {
        return {
            success: false,
            version: '',
            error: error.message,
        };
    }
}
exports.installLatest = installLatest;
/**
 * Check if a version is pinned
 */
function isPinned(backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    return (0, binary_manager_1.isVersionPinned)(effectiveBackend);
}
exports.isPinned = isPinned;
/**
 * Get pinned version if any
 */
function getPinned(backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    return (0, binary_manager_1.getPinnedVersion)(effectiveBackend);
}
exports.getPinned = getPinned;
/**
 * Clear version pin
 */
function clearPin(backend) {
    const configuredBackend = backend ?? (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy?.backend ?? platform_detector_1.DEFAULT_BACKEND;
    const effectiveBackend = (0, binary_manager_1.resolveLocalBackend)(configuredBackend, { notifyOnPlus: true });
    (0, binary_manager_1.clearPinnedVersion)(effectiveBackend);
}
exports.clearPin = clearPin;
//# sourceMappingURL=binary-service.js.map