package com.nexlab.openclaw.node.service

import android.app.AppOpsManager
import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Service for usage statistics - get foreground app, app usage, etc.
 */
@Singleton
class UsageStatsService @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val usageStatsManager: UsageStatsManager =
        context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager

    /**
     * Check if usage stats permission is granted
     */
    fun hasPermission(): Boolean {
        val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            appOps.unsafeCheckOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(),
                context.packageName
            )
        } else {
            @Suppress("DEPRECATION")
            appOps.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(),
                context.packageName
            )
        }
        return mode == AppOpsManager.MODE_ALLOWED
    }

    /**
     * Open usage stats permission settings
     */
    fun openPermissionSettings() {
        val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    /**
     * Get the current foreground app package name
     */
    fun getForegroundApp(): String? {
        if (!hasPermission()) return null

        val endTime = System.currentTimeMillis()
        val startTime = endTime - 1000 * 60 // Last minute

        val usageEvents = usageStatsManager.queryEvents(startTime, endTime)
        var foregroundApp: String? = null

        while (usageEvents.hasNextEvent()) {
            val event = UsageEvents.Event()
            usageEvents.getNextEvent(event)

            if (event.eventType == UsageEvents.Event.ACTIVITY_RESUMED) {
                foregroundApp = event.packageName
            }
        }

        return foregroundApp
    }

    /**
     * Get app name from package
     */
    fun getAppName(packageName: String): String {
        return try {
            val pm = context.packageManager
            val appInfo = pm.getApplicationInfo(packageName, 0)
            pm.getApplicationLabel(appInfo).toString()
        } catch (e: Exception) {
            packageName
        }
    }

    /**
     * Get list of recently used apps
     */
    fun getRecentApps(limit: Int = 10): List<AppUsageInfo> {
        if (!hasPermission()) return emptyList()

        val endTime = System.currentTimeMillis()
        val startTime = endTime - 1000 * 60 * 60 // Last hour

        val usageEvents = usageStatsManager.queryEvents(startTime, endTime)
        val appUsage = mutableMapOf<String, Long>()

        while (usageEvents.hasNextEvent()) {
            val event = UsageEvents.Event()
            usageEvents.getNextEvent(event)

            if (event.eventType == UsageEvents.Event.ACTIVITY_RESUMED) {
                val currentTime = appUsage[event.packageName] ?: 0L
                appUsage[event.packageName] = currentTime + 1 // Count launches
            }
        }

        return appUsage.entries
            .sortedByDescending { it.value }
            .take(limit)
            .map { (packageName, launches) ->
                AppUsageInfo(
                    packageName = packageName,
                    appName = getAppName(packageName),
                    launchCount = launches.toInt()
                )
            }
    }

    data class AppUsageInfo(
        val packageName: String,
        val appName: String,
        val launchCount: Int
    )
}
