package com.hikoncont.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.hikoncont.service.AccessibilityRemoteService
import com.hikoncont.MainActivity
import com.hikoncont.manager.SmartMediaProjectionManager
import kotlinx.coroutines.*

/**
 * 智能权限恢复广播接收器
 * 
 * 处理以下场景：
 * 1. Android 15权限丢失的智能恢复
 * 2. 非侵入式权限恢复提示
 * 3. 用户确认后的权限重新申请
 */
class SmartPermissionRecoveryReceiver : BroadcastReceiver() {
    
    companion object {
        private const val TAG = "SmartPermissionRecovery"
        private const val RECOVERY_NOTIFICATION_ID = 9999
    }
    
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "android.mycustrecev.SMART_PERMISSION_RECOVERY" -> {
                handleSmartPermissionRecovery(context, intent)
            }
            "android.mycustrecev.USER_CONFIRM_RECOVERY" -> {
                handleUserConfirmRecovery(context, intent)
            }
            "android.mycustrecev.ANDROID15_SECONDARY_CONFIRMATION" -> {
                handleAndroid15SecondaryConfirmation(context, intent)
            }
            "android.mycustrecev.DEEP_RECOVERY_MODE" -> {
                handleDeepRecoveryMode(context, intent)
            }
        }
    }
    
    /**
     * 处理智能权限恢复
     */
    private fun handleSmartPermissionRecovery(context: Context, intent: Intent) {
        try {
            val recoveryType = intent.getStringExtra("recovery_type")
            val attempt = intent.getIntExtra("attempt", 1)
            val maxAttempts = intent.getIntExtra("max_attempts", 3)
            
            Log.i(TAG, "🔔 收到智能权限恢复请求: $recoveryType (尝试 $attempt/$maxAttempts)")
            
            when (recoveryType) {
                "user_prompted" -> {
                    showNonIntrusiveRecoveryNotification(context, attempt, maxAttempts)
                }
                "silent_failed" -> {
                    // 静默恢复失败，记录但不打扰用户
                    Log.w(TAG, "⚠️ 静默权限恢复失败，等待下次机会")
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理智能权限恢复失败", e)
        }
    }
    
    /**
     * 显示非侵入式恢复通知
     */
    private fun showNonIntrusiveRecoveryNotification(context: Context, attempt: Int, maxAttempts: Int) {
        try {
            // 检查是否应该显示通知
            if (!shouldShowRecoveryNotification(context)) {
                Log.i(TAG, "🤐 根据策略，不显示恢复通知")
                return
            }
            
            Log.i(TAG, "📢 显示非侵入式权限恢复通知")
            
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
            
            // 创建通知渠道（Android 8.0+）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = android.app.NotificationChannel(
                    "permission_recovery",
                    "权限恢复",
                    android.app.NotificationManager.IMPORTANCE_DEFAULT
                ).apply {
                    description = "服务权限恢复通知"
                    setSound(null, null) // 静音通知
                    enableVibration(false) // 不震动
                    enableLights(false) // 不闪灯
                }
                notificationManager.createNotificationChannel(channel)
            }
            
            // 创建恢复意图
            val recoveryIntent = Intent(context, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("AUTO_REQUEST_PERMISSION", true)
                putExtra("PERMISSION_LOST_RECOVERY", true)
                putExtra("SMART_RECOVERY", true)
            }
            
            val pendingIntent = android.app.PendingIntent.getActivity(
                context, 
                0, 
                recoveryIntent, 
                android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
            )
            
            // 创建忽略意图
            val ignoreIntent = Intent("android.mycustrecev.IGNORE_RECOVERY")
            val ignorePendingIntent = android.app.PendingIntent.getBroadcast(
                context,
                1,
                ignoreIntent,
                android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
            )
            
            // 构建通知
            val notification = android.app.Notification.Builder(context, "permission_recovery")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle("服务权限需要恢复")
                .setContentText("权限已丢失，点击恢复功能")
                .setStyle(android.app.Notification.BigTextStyle()
                    .bigText("检测到服务权限丢失，可能是由于：\n• 设备锁屏后系统自动停止\n• Android 15系统限制\n\n点击此通知可快速恢复权限，或者忽略此次提醒。"))
                .setContentIntent(pendingIntent)
                .addAction(
                    android.R.drawable.ic_media_play,
                    "恢复权限",
                    pendingIntent
                )
                .addAction(
                    android.R.drawable.ic_delete,
                    "忽略",
                    ignorePendingIntent
                )
                .setAutoCancel(true)
                .setPriority(android.app.Notification.PRIORITY_DEFAULT)
                .setOngoing(false)
                .build()
            
            notificationManager.notify(RECOVERY_NOTIFICATION_ID, notification)
            
            Log.i(TAG, "✅ 非侵入式恢复通知已显示")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示恢复通知失败", e)
        }
    }
    
    /**
     * 判断是否应该显示恢复通知
     */
    private fun shouldShowRecoveryNotification(context: Context): Boolean {
        try {
            // 检查AccessibilityService是否正在运行
            if (!AccessibilityRemoteService.isServiceRunning()) {
                Log.w(TAG, "⚠️ AccessibilityService未运行，不显示恢复通知")
                return false
            }
            
            // 检查用户是否在最近5分钟内忽略过恢复通知
            val prefs = context.getSharedPreferences("smart_recovery", Context.MODE_PRIVATE)
            val lastIgnoreTime = prefs.getLong("last_ignore_time", 0)
            val currentTime = System.currentTimeMillis()
            
            if (currentTime - lastIgnoreTime < 300000) { // 5分钟
                Log.d(TAG, "🤐 用户最近忽略过恢复通知，暂不显示")
                return false
            }
            
            // 统一使用保守的通知策略，间隔10分钟确保Android 11+设备稳定性
            val lastNotificationTime = prefs.getLong("last_notification_time", 0)
            if (currentTime - lastNotificationTime < 600000) { // 统一间隔10分钟
                Log.d(TAG, "🕐 通知间隔未到，暂不显示")
                return false
            }
            
            // 更新最后通知时间
            prefs.edit().putLong("last_notification_time", currentTime).apply()
            
            return true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查通知显示条件失败", e)
            return false
        }
    }
    
    /**
     * 处理用户确认恢复
     */
    private fun handleUserConfirmRecovery(context: Context, intent: Intent) {
        try {
            Log.i(TAG, "✅ 用户确认权限恢复，启动权限申请流程")
            
            // 取消通知
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
            notificationManager.cancel(RECOVERY_NOTIFICATION_ID)
            
            // 启动MainActivity进行权限申请
            val mainIntent = Intent(context, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("AUTO_REQUEST_PERMISSION", true)
                putExtra("PERMISSION_LOST_RECOVERY", true)
                putExtra("USER_CONFIRMED_RECOVERY", true)
            }
            
            context.startActivity(mainIntent)
            
            Log.i(TAG, "🚀 已启动用户确认的权限恢复流程")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理用户确认恢复失败", e)
        }
    }
    
    /**
     * 处理二次确认（统一处理Android 11+设备）
     */
    private fun handleAndroid15SecondaryConfirmation(context: Context, intent: Intent) {
        try {
            Log.i(TAG, "🔍 处理二次确认")
            
            // 重新激活PermissionGranter以处理可能的二次确认对话框
            val activateIntent = Intent("android.mycustrecev.REACTIVATE_PERMISSION_GRANTER")
            context.sendBroadcast(activateIntent)
            
            Log.i(TAG, "🛡️ 已重新激活PermissionGranter处理二次确认")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理二次确认失败", e)
        }
    }
    
    /**
     * 处理深度恢复模式
     */
    private fun handleDeepRecoveryMode(context: Context, intent: Intent) {
        try {
            Log.w(TAG, "🔧 启动深度恢复模式")
            
            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            val isKeepAliveScenario = intent.getBooleanExtra("from_keepalive", false) ||
                    intent.getBooleanExtra("keepalive_launch", false) ||
                    intent.getBooleanExtra("from_service", false)
            
            if (isKeepAliveScenario) {
                Log.i(TAG, "💡 深度恢复模式在保活场景下，不启动MainActivity（避免保活程序拉起）")
                Log.i(TAG, "💡 建议：通过通知让用户主动打开应用进行深度恢复")
                return
            }
            
            // 深度恢复：完全重新初始化权限系统
            CoroutineScope(Dispatchers.Main).launch {
                try {
                    // 1. 等待3秒，让系统稳定
                    delay(3000)
                    
                    // 2. 清理SmartMediaProjectionManager状态
                    val smartManager = SmartMediaProjectionManager.getInstance(context)
                    smartManager.cleanup()
                    
                    // 3. 重新初始化
                    delay(1000)
                    smartManager.initialize()
                    
                    // 4. 启动权限重新申请（非保活场景）
                    val recoveryIntent = Intent(context, MainActivity::class.java).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        putExtra("AUTO_REQUEST_PERMISSION", true)
                        putExtra("DEEP_RECOVERY", true)
                        putExtra("PERMISSION_LOST_RECOVERY", true)
                        putExtra("user_initiated", true) // 标记为用户主动触发
                    }
                    
                    context.startActivity(recoveryIntent)
                    
                    Log.i(TAG, "✅ 深度恢复模式已启动（非保活场景）")
                    
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 深度恢复模式执行失败", e)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理深度恢复模式失败", e)
        }
    }
} 