package com.hikoncont

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log

/**
 * 保活启动器Activity - 借鉴反编译项目的OpenActivity实现
 * 主要职责：
 * 1. 启动指定的应用包
 * 2. 保活服务启动
 * 3. 透明Activity管理
 */
class KeepAliveLauncherActivity : Activity() {

    companion object {
        private const val TAG = "KeepAliveLauncher"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i(TAG, "🚀 保活启动器Activity创建")
        
        try {
            // 启动保活服务
            startKeepAliveServices()
            
            // 处理启动请求
            handleLaunchRequest()
            
            // 延迟关闭Activity
            scheduleFinish()
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 保活启动器Activity初始化失败", e)
        }
    }

    /**
     * 启动保活服务
     */
    private fun startKeepAliveServices() {
        try {
            Log.i(TAG, "🛡️ 启动保活服务")
            
            // 只记录日志，不重复启动综合保活管理器
            Log.i(TAG, "✅ 保活服务启动完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活服务失败", e)
        }
    }

    /**
     * 处理启动请求
     */
    private fun handleLaunchRequest() {
        try {
            val intent = intent
            val targetPackage = intent.getStringExtra("target_package")
            val launchMain = intent.getBooleanExtra("launch_main", false)
            
            when {
                !targetPackage.isNullOrEmpty() -> {
                    // 启动指定应用（伪装保活）
                    launchTargetApp(targetPackage)
                }
                launchMain -> {
                    // 启动主Activity
                    launchMainActivity()
                }
                else -> {
                    // 默认启动主Activity
                    launchMainActivity()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理启动请求失败", e)
        }
    }

    /**
     * 启动目标应用
     */
    private fun launchTargetApp(packageName: String) {
        try {
            Log.i(TAG, "🎯 启动目标应用: $packageName")
            
            val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
            if (launchIntent != null) {
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(launchIntent)
                Log.i(TAG, "✅ 目标应用启动成功")
            } else {
                Log.w(TAG, "⚠️ 无法启动目标应用: $packageName")
                // 启动主Activity作为备选
                launchMainActivity()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动目标应用失败", e)
            // 启动主Activity作为备选
            launchMainActivity()
        }
    }

    /**
     * 启动主Activity - 保活场景改为启动透明保活Activity
     */
    private fun launchMainActivity() {
        try {
            Log.i(TAG, "🫥 保活场景，启动透明保活Activity（不启动MainActivity）")
            
            // ✅ 修复：保活场景启动透明保活Activity，不启动MainActivity
            val transparentIntent = Intent(this, com.hikoncont.TransparentKeepAliveActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) // 禁用动画，避免闪屏
                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("from_keepalive_launcher", true)
                putExtra("timestamp", System.currentTimeMillis())
            }
            
            startActivity(transparentIntent)
            Log.i(TAG, "✅ 透明保活Activity启动成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动透明保活Activity失败", e)
        }
    }


    /**
     * 安排Activity关闭
     */
    private fun scheduleFinish() {
        try {
            Handler(Looper.getMainLooper()).postDelayed({
                try {
                    finish()
                    Log.d(TAG, "✅ 保活启动器Activity已关闭")
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 关闭Activity失败", e)
                }
            }, 100L) // 100ms后关闭
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 安排Activity关闭失败", e)
        }
    }
}
