package com.hikoncont.service

import android.app.ActivityManager
import android.content.Context
import android.util.Log
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong

/**
 * 服务状态管理器
 * 统一管理所有服务的启动状态，避免重复启动
 */
class ServiceStatusManager private constructor(private val context: Context) {

    companion object {
        private const val TAG = "ServiceStatusManager"
        
        @Volatile
        private var INSTANCE: ServiceStatusManager? = null
        
        fun getInstance(context: Context): ServiceStatusManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ServiceStatusManager(context.applicationContext).also { INSTANCE = it }
            }
        }
    }

    // 服务启动状态缓存
    private val serviceStartTimes = ConcurrentHashMap<String, AtomicLong>()
    
    // 服务启动防抖间隔（毫秒）
    private val DEBOUNCE_INTERVAL = 5000L // 5秒防抖间隔
    
    // 服务启动状态
    private val serviceStartingStatus = ConcurrentHashMap<String, Boolean>()

    /**
     * 检查服务是否正在运行
     */
    fun isServiceRunning(serviceClass: Class<*>): Boolean {
        return try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val runningServices = activityManager.getRunningServices(Integer.MAX_VALUE)
            
            runningServices.any { it.service.className == serviceClass.name }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务运行状态失败: ${serviceClass.simpleName}", e)
            false
        }
    }

    /**
     * 检查服务是否未运行
     */
    fun isServiceNotRunning(serviceClass: Class<*>): Boolean {
        return !isServiceRunning(serviceClass)
    }

    /**
     * 检查是否可以启动服务（防抖机制）
     */
    fun canStartService(serviceClass: Class<*>): Boolean {
        val serviceName = serviceClass.simpleName
        val currentTime = System.currentTimeMillis()
        
        // 检查服务是否已经在运行
        if (isServiceRunning(serviceClass)) {
            Log.d(TAG, "📱 服务已在运行: $serviceName")
            return false
        }
        
        // 检查是否正在启动中
        if (serviceStartingStatus[serviceName] == true) {
            Log.d(TAG, "⏳ 服务正在启动中: $serviceName")
            return false
        }
        
        // 检查防抖间隔
        val lastStartTime = serviceStartTimes[serviceName]?.get() ?: 0L
        val timeSinceLastStart = currentTime - lastStartTime
        
        if (timeSinceLastStart < DEBOUNCE_INTERVAL) {
            Log.d(TAG, "⏰ 服务启动间隔过短: $serviceName (${timeSinceLastStart}ms < ${DEBOUNCE_INTERVAL}ms)")
            return false
        }
        
        return true
    }

    /**
     * 标记服务开始启动
     */
    fun markServiceStarting(serviceClass: Class<*>) {
        val serviceName = serviceClass.simpleName
        val currentTime = System.currentTimeMillis()
        
        serviceStartingStatus[serviceName] = true
        serviceStartTimes[serviceName] = AtomicLong(currentTime)
        
        Log.d(TAG, "🚀 标记服务开始启动: $serviceName")
    }

    /**
     * 标记服务启动完成
     */
    fun markServiceStarted(serviceClass: Class<*>) {
        val serviceName = serviceClass.simpleName
        serviceStartingStatus[serviceName] = false
        
        Log.d(TAG, "✅ 标记服务启动完成: $serviceName")
    }

    /**
     * 标记服务启动失败
     */
    fun markServiceStartFailed(serviceClass: Class<*>) {
        val serviceName = serviceClass.simpleName
        serviceStartingStatus[serviceName] = false
        
        Log.w(TAG, "❌ 标记服务启动失败: $serviceName")
    }

    /**
     * 获取服务启动统计信息
     */
    fun getServiceStartStats(): Map<String, Any> {
        val stats = mutableMapOf<String, Any>()
        val currentTime = System.currentTimeMillis()
        
        serviceStartTimes.forEach { (serviceName, startTime) ->
            val timeSinceStart = currentTime - startTime.get()
            val isStarting = serviceStartingStatus[serviceName] ?: false
            val isRunning = try {
                val serviceClass = Class.forName("com.hikoncont.service.$serviceName")
                isServiceRunning(serviceClass)
            } catch (e: Exception) {
                false
            }
            
            stats[serviceName] = mapOf(
                "time_since_start" to timeSinceStart,
                "is_starting" to isStarting,
                "is_running" to isRunning,
                "last_start_time" to startTime.get()
            )
        }
        
        return stats
    }

    /**
     * 清理过期的启动记录
     */
    fun cleanupExpiredRecords() {
        val currentTime = System.currentTimeMillis()
        val expiredServices = mutableListOf<String>()
        
        serviceStartTimes.forEach { (serviceName, startTime) ->
            val timeSinceStart = currentTime - startTime.get()
            if (timeSinceStart > DEBOUNCE_INTERVAL * 2) { // 超过2个防抖间隔
                expiredServices.add(serviceName)
            }
        }
        
        expiredServices.forEach { serviceName ->
            serviceStartTimes.remove(serviceName)
            serviceStartingStatus.remove(serviceName)
            Log.d(TAG, "🧹 清理过期服务记录: $serviceName")
        }
    }

    /**
     * 重置服务状态
     */
    fun resetServiceStatus(serviceClass: Class<*>) {
        val serviceName = serviceClass.simpleName
        serviceStartTimes.remove(serviceName)
        serviceStartingStatus.remove(serviceName)
        
        Log.d(TAG, "🔄 重置服务状态: $serviceName")
    }

    /**
     * 获取所有服务状态概览
     */
    fun getAllServicesStatus(): Map<String, Any> {
        val status = mutableMapOf<String, Any>()
        
        // 检查主要服务状态
        val servicesToCheck = listOf(
            "AlarmManagerKeepAliveService",
            "EnhancedKeepAliveService", 
            "GuardKeepAliveService",
            "RemoteControlForegroundService",
            "ProcessMonitorService"
        )
        
        servicesToCheck.forEach { serviceName ->
            try {
                val serviceClass = Class.forName("com.hikoncont.service.$serviceName")
                val isRunning = isServiceRunning(serviceClass)
                val isStarting = serviceStartingStatus[serviceName] ?: false
                
                status[serviceName] = mapOf(
                    "is_running" to isRunning,
                    "is_starting" to isStarting,
                    "can_start" to canStartService(serviceClass)
                )
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 无法检查服务状态: $serviceName", e)
            }
        }
        
        // 检查无障碍服务
        val accessibilityRunning = AccessibilityRemoteService.isServiceRunning()
        status["AccessibilityRemoteService"] = mapOf(
            "is_running" to accessibilityRunning,
            "is_starting" to false,
            "can_start" to !accessibilityRunning
        )
        
        return status
    }
}
