package com.hikoncont.service

import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.hikoncont.MediaProjectionHolder
import com.hikoncont.manager.SmartMediaProjectionManager
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 权限健康监控服务
 * 
 * 专门监控Android 15的MediaProjection权限状态，
 * 提供主动的权限维护和异常恢复机制
 */
class PermissionHealthMonitor(private val context: Context) {
    
    companion object {
        private const val TAG = "PermissionHealthMonitor"
        private const val HEALTH_CHECK_INTERVAL = 30000L // 30秒检查一次
        private const val ANDROID_15_CHECK_INTERVAL = 15000L // Android 15每15秒检查一次
        
        @Volatile
        private var instance: PermissionHealthMonitor? = null
        
        fun getInstance(context: Context): PermissionHealthMonitor {
            return instance ?: synchronized(this) {
                instance ?: PermissionHealthMonitor(context.applicationContext).also { instance = it }
            }
        }
    }
    
    private val isMonitoring = AtomicBoolean(false)
    private val monitorScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
    private var healthCheckJob: Job? = null
    
    // 健康状态统计
    @Volatile private var totalChecks = 0
    @Volatile private var healthyChecks = 0
    @Volatile private var permissionLossEvents = 0
    @Volatile private var successfulRecoveries = 0
    @Volatile private var failedRecoveries = 0
    
    /**
     * 启动权限健康监控
     */
    fun startMonitoring() {
        if (isMonitoring.get()) {
            Log.d(TAG, "权限健康监控已在运行")
            return
        }
        
        Log.i(TAG, "🏥 启动权限健康监控服务")
        isMonitoring.set(true)
        
        val checkInterval = if (Build.VERSION.SDK_INT >= 35) {
            ANDROID_15_CHECK_INTERVAL
        } else {
            HEALTH_CHECK_INTERVAL
        }
        
        healthCheckJob = monitorScope.launch {
            while (isActive && isMonitoring.get()) {
                try {
                    performHealthCheck()
                    delay(checkInterval)
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 健康检查异常", e)
                    delay(checkInterval)
                }
            }
        }
        
        Log.i(TAG, "✅ 权限健康监控已启动，检查间隔: ${checkInterval / 1000}秒")
    }
    
    /**
     * 停止权限健康监控
     */
    fun stopMonitoring() {
        if (!isMonitoring.get()) {
            Log.d(TAG, "权限健康监控未运行")
            return
        }
        
        Log.i(TAG, "🛑 停止权限健康监控服务")
        isMonitoring.set(false)
        healthCheckJob?.cancel()
        
        // 输出监控统计
        logHealthStatistics()
    }
    
    /**
     * 执行健康检查
     */
    private suspend fun performHealthCheck() {
        try {
            totalChecks++
            
            Log.v(TAG, "🔍 执行第${totalChecks}次权限健康检查")
            
            // 🔧 优化权限检查逻辑，避免误报
            val smartManager = SmartMediaProjectionManager.getInstance(context)
            val hasMediaProjection = smartManager.getCurrentMediaProjection() != null
            val hasPermissionData = MediaProjectionHolder.getPermissionData() != null
            val permissionDataValid = MediaProjectionHolder.isPermissionDataValid()
            
            // 获取权限统计信息
            val stats = MediaProjectionHolder.getPermissionStats()
            
            // 🔧 更智能的健康判断：Android 15设备更宽松的判断标准
            val isHealthy = if (android.os.Build.VERSION.SDK_INT >= 35) {
                // Android 15：只要有权限数据且数据有效就认为是健康的
                hasPermissionData && permissionDataValid
            } else {
                // 其他版本：需要有MediaProjection或有效的权限数据
                hasMediaProjection || (hasPermissionData && permissionDataValid)
            }
            
            Log.v(TAG, "🔍 权限健康检查: MediaProjection=$hasMediaProjection, 权限数据=$hasPermissionData, 数据有效=$permissionDataValid, 总体健康=$isHealthy")
            
            if (isHealthy) {
                // 权限状态正常
                healthyChecks++
                handleHealthyState(stats)
            } else {
                // 🚨 只有在确实没有任何权限时才认为是问题
                Log.w(TAG, "⚠️ 确认权限问题 - MediaProjection=$hasMediaProjection, 权限数据=$hasPermissionData, 数据有效=$permissionDataValid")
                handleUnhealthyState(hasMediaProjection, permissionDataValid, stats)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 健康检查执行失败", e)
        }
    }
    
    /**
     * 处理健康状态
     */
    private fun handleHealthyState(stats: Map<String, Any>) {
        Log.v(TAG, "✅ 权限状态健康")
        
        // Android 15设备进行额外的稳定性检查
        if (Build.VERSION.SDK_INT >= 35) {
            val permissionAge = stats["permissionAge"] as? Long ?: 0L
            val maxAge = 2 * 60 * 60 * 1000L // 2小时
            
            if (permissionAge > maxAge * 0.8) { // 权限年龄超过80%
                Log.w(TAG, "⚠️ Android 15权限即将过期，提前准备更新")
                preparePermissionRefresh()
            }
        }
    }
    
    /**
     * 处理不健康状态
     */
    private suspend fun handleUnhealthyState(
        hasValidPermission: Boolean, 
        permissionDataValid: Boolean, 
        stats: Map<String, Any>
    ) {
        Log.w(TAG, "⚠️ 检测到权限问题 - 有效权限: $hasValidPermission, 数据有效: $permissionDataValid")
        
        // ✅ 添加保护性检查：确认权限确实丢失
        val permissionData = MediaProjectionHolder.getPermissionData()
        val hasMediaProjection = MediaProjectionHolder.getMediaProjection() != null
        
        if (permissionData != null) {
            Log.i(TAG, "🛡️ 权限数据仍然存在，可能是误报，不计入权限丢失事件")
            return
        }
        
        permissionLossEvents++
        
        // 尝试智能恢复
        if (attemptSmartRecovery()) {
            successfulRecoveries++
            Log.i(TAG, "✅ 智能恢复成功")
        } else {
            failedRecoveries++
            Log.w(TAG, "❌ 智能恢复失败")
            
            // ✅ 只有在恢复失败次数真的很多时才发送权限异常通知
            if (failedRecoveries >= 5) { // 提高阈值从 3 到 5
                Log.w(TAG, "⚠️ 连续恢复失败次数过多($failedRecoveries)，发送权限异常通知")
                notifyPermissionIssue()
            } else {
                Log.i(TAG, "🔄 恢复失败次数尚可接受($failedRecoveries)，继续监控")
            }
        }
    }
    
    /**
     * 尝试智能恢复
     */
    private suspend fun attemptSmartRecovery(): Boolean {
        return try {
            Log.i(TAG, "🔧 尝试智能权限恢复")
            
            // 使用MediaProjectionHolder的智能恢复
            val recovered = MediaProjectionHolder.attemptSmartRecovery()
            
            if (recovered != null) {
                Log.i(TAG, "✅ 智能恢复成功")
                
                // 通知AccessibilityService权限已恢复
                val intent = Intent("android.mycustrecev.PERMISSION_HEALTH_RECOVERED")
                context.sendBroadcast(intent)
                
                true
            } else {
                Log.w(TAG, "❌ 智能恢复失败")
                false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 智能恢复异常", e)
            false
        }
    }
    
    /**
     * 准备权限刷新（Android 15预防性措施）
     */
    private fun preparePermissionRefresh() {
        monitorScope.launch {
            try {
                Log.i(TAG, "🔄 Android 15权限预防性刷新")
                
                val smartManager = SmartMediaProjectionManager.getInstance(context)
                val permissionData = MediaProjectionHolder.getPermissionData()
                
                if (permissionData != null) {
                    val (resultCode, resultData) = permissionData
                    if (resultData != null) {
                        // 重新设置权限，刷新时间戳
                        if (smartManager.setMediaProjection(resultCode, resultData)) {
                            Log.i(TAG, "✅ 权限预防性刷新成功")
                        }
                    }
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 权限预防性刷新失败", e)
            }
        }
    }
    
    /**
     * 通知权限问题
     */
    private fun notifyPermissionIssue() {
        try {
            // 发送权限问题广播
            val intent = Intent("android.mycustrecev.PERMISSION_HEALTH_ISSUE").apply {
                putExtra("total_checks", totalChecks)
                putExtra("healthy_checks", healthyChecks)
                putExtra("permission_loss_events", permissionLossEvents)
                putExtra("successful_recoveries", successfulRecoveries)
                putExtra("failed_recoveries", failedRecoveries)
            }
            context.sendBroadcast(intent)
            
            Log.w(TAG, "📡 已发送权限健康问题通知")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送权限问题通知失败", e)
        }
    }
    
    /**
     * 获取健康统计信息
     */
    fun getHealthStatistics(): Map<String, Any> {
        val healthRate = if (totalChecks > 0) {
            (healthyChecks.toDouble() / totalChecks * 100).toInt()
        } else {
            100
        }
        
        val recoveryRate = if (permissionLossEvents > 0) {
            (successfulRecoveries.toDouble() / permissionLossEvents * 100).toInt()
        } else {
            100
        }
        
        return mapOf(
            "isMonitoring" to isMonitoring.get(),
            "totalChecks" to totalChecks,
            "healthyChecks" to healthyChecks,
            "healthRate" to healthRate,
            "permissionLossEvents" to permissionLossEvents,
            "successfulRecoveries" to successfulRecoveries,
            "failedRecoveries" to failedRecoveries,
            "recoveryRate" to recoveryRate,
            "androidVersion" to Build.VERSION.SDK_INT,
            "checkInterval" to if (Build.VERSION.SDK_INT >= 35) ANDROID_15_CHECK_INTERVAL else HEALTH_CHECK_INTERVAL
        )
    }
    
    /**
     * 记录健康统计信息
     */
    private fun logHealthStatistics() {
        val stats = getHealthStatistics()
        
        Log.i(TAG, """
            📊 权限健康监控统计报告:
            ========================================
            • 监控状态: ${if (stats["isMonitoring"] as Boolean) "运行中" else "已停止"}
            • 总检查次数: ${stats["totalChecks"]}
            • 健康检查次数: ${stats["healthyChecks"]}
            • 健康率: ${stats["healthRate"]}%
            • 权限丢失事件: ${stats["permissionLossEvents"]}
            • 成功恢复次数: ${stats["successfulRecoveries"]}
            • 失败恢复次数: ${stats["failedRecoveries"]}
            • 恢复成功率: ${stats["recoveryRate"]}%
            • Android版本: ${stats["androidVersion"]}
            • 检查间隔: ${(stats["checkInterval"] as Long) / 1000}秒
            ========================================
        """.trimIndent())
    }
    
    /**
     * 手动触发健康检查
     */
    fun manualHealthCheck() {
        if (!isMonitoring.get()) {
            Log.w(TAG, "⚠️ 监控服务未运行，无法执行手动检查")
            return
        }
        
        Log.i(TAG, "🔍 执行手动健康检查")
        monitorScope.launch {
            performHealthCheck()
        }
    }
    
    /**
     * 重置统计信息
     */
    fun resetStatistics() {
        totalChecks = 0
        healthyChecks = 0
        permissionLossEvents = 0
        successfulRecoveries = 0
        failedRecoveries = 0
        Log.i(TAG, "🔄 健康统计信息已重置")
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        stopMonitoring()
        monitorScope.cancel()
        instance = null
        Log.i(TAG, "🧹 权限健康监控服务已清理")
    }
} 