RelenciaUpdateHelper = RelenciaUpdateHelper or {}

local activeHandler = nil

function RelenciaUpdateHelper.tryLaunch(reason, onFinished)
    reason = reason or 'unknown'

    if isLocalEnv and isLocalEnv() then
        g_logger.info(string.format('[Updater] Skipping auto-update (%s) because RELENCIA_ENV=local', reason))
        return false
    end

    g_modules.ensureModuleLoaded('updater')

    local hasUpdater = g_app.hasUpdater and g_app.hasUpdater()
    local updaterModule = g_modules.getModule and g_modules.getModule('updater') or nil

    if not hasUpdater or not updaterModule or not Updater or not Updater.check then
        g_logger.error(string.format('[Updater] Unable to launch updater for reason "%s": updater module unavailable.', reason))
        return false
    end

    if activeHandler then
        disconnect(g_app, { onUpdateFinished = activeHandler })
        activeHandler = nil
    end

    local function finished()
        disconnect(g_app, { onUpdateFinished = finished })
        activeHandler = nil
        if onFinished then
            onFinished(true)
        end
    end

    connect(g_app, { onUpdateFinished = finished })
    activeHandler = finished

    g_logger.info(string.format('[Updater] Launching updater (reason=%s)', reason))
    Updater.check({ reason = reason })
    return true
end
