package com.omixlab.lckcontrol.util

import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.core.graphics.drawable.toBitmap
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

data class GameInfo(
    val packageName: String,
    val label: String,
    val icon: ImageBitmap,
)

@Singleton
class GameInfoProvider @Inject constructor(
    @ApplicationContext private val context: Context,
) {
    private val cache = HashMap<String, GameInfo?>()

    fun resolve(packageName: String): GameInfo? {
        if (packageName.isBlank()) return null
        return cache.getOrPut(packageName) {
            try {
                val pm = context.packageManager
                val appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
                val label = pm.getApplicationLabel(appInfo).toString()
                // Use loadIcon for higher density, fall back to getApplicationIcon
                val drawable = appInfo.loadIcon(pm)
                val size = (48 * context.resources.displayMetrics.density).toInt()
                val icon = drawable.toBitmap(size, size).asImageBitmap()
                Log.d("GameInfoProvider", "Resolved $packageName -> $label")
                GameInfo(packageName, label, icon)
            } catch (_: PackageManager.NameNotFoundException) {
                Log.w("GameInfoProvider", "Package not found: $packageName")
                null
            }
        }
    }

    /** Invalidate cache so icons are re-fetched on next resolve */
    fun invalidate(packageName: String) {
        cache.remove(packageName)
    }
}
