package com.sshproxy.vpn.data

import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build

object InstalledAppsProvider {

    /**
     * All enabled installed packages that can be excluded from the VPN tunnel.
     * Unlike launcher-only queries, this includes apps without a home-screen icon.
     */
    fun loadInstalledApps(context: Context, includeSystemApps: Boolean): List<AppInfo> {
        val pm = context.packageManager
        val installed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            pm.getInstalledApplications(PackageManager.ApplicationInfoFlags.of(0))
        } else {
            @Suppress("DEPRECATION")
            pm.getInstalledApplications(0)
        }

        return installed
            .asSequence()
            .filter { it.enabled }
            .filter { it.packageName != context.packageName }
            .filter { appInfo -> includeSystemApps || !appInfo.isPureSystemApp() }
            .map { appInfo ->
                AppInfo(
                    packageName = appInfo.packageName,
                    label = appInfo.loadLabel(pm).toString().ifBlank { appInfo.packageName },
                    icon = runCatching { appInfo.loadIcon(pm) }
                        .getOrDefault(pm.defaultActivityIcon)
                )
            }
            .sortedWith(compareBy({ it.label.lowercase() }, { it.packageName }))
            .toList()
    }

    private fun ApplicationInfo.isPureSystemApp(): Boolean {
        val isSystem = (flags and ApplicationInfo.FLAG_SYSTEM) != 0
        val isUpdatedSystem = (flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
        return isSystem && !isUpdatedSystem
    }
}
