package com.hikoncont.security

import android.content.Context
import android.content.pm.ApplicationInfo
import android.os.Build
import android.os.Debug
import android.os.Process
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.system.exitProcess

/**
 * 反调试检测器
 * 用于检测调试器、模拟器、Root等威胁
 */
object AntiDebugDetector {
    
    private val isDebugDetected = AtomicBoolean(false)
    private val isEmulatorDetected = AtomicBoolean(false)
    private val isRootDetected = AtomicBoolean(false)
    
    /**
     * 初始化反调试检测
     */
    fun initialize(context: Context) {
        if (com.hikoncont.BuildConfig.ENABLE_ANTI_DEBUG) {
            startAntiDebugProtection(context)
        }
    }
    
    /**
     * 启动反调试保护
     */
    private fun startAntiDebugProtection(context: Context) {
        // 在后台线程运行检测
        Thread {
            while (true) {
                try {
                    // 检测调试器
                    if (detectDebugger(context)) {
                        handleThreatDetected("调试器检测", "检测到调试器连接")
                    }
                    
                    // 检测模拟器
                    if (detectEmulator()) {
                        handleThreatDetected("模拟器检测", "检测到模拟器环境")
                    }
                    
                    // 检测Root
                    if (detectRoot(context)) {
                        handleThreatDetected("Root检测", "检测到Root环境")
                    }
                    
                    // 检测Xposed
                    if (detectXposed()) {
                        handleThreatDetected("Xposed检测", "检测到Xposed框架")
                    }
                    
                    // 检测Frida
                    if (detectFrida()) {
                        handleThreatDetected("Frida检测", "检测到Frida框架")
                    }
                    
                    // 检测应用签名
                    if (detectSignatureTampering(context)) {
                        handleThreatDetected("签名检测", "检测到应用签名被篡改")
                    }
                    
                    // 暂停检测
                    Thread.sleep(5000) // 每5秒检测一次
                } catch (e: Exception) {
                    // 忽略异常，继续检测
                }
            }
        }.start()
    }
    
    /**
     * 检测调试器
     */
    private fun detectDebugger(context: Context): Boolean {
        // 方法1：检测应用是否在调试状态
        val isAppDebuggable = (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
        
        // 方法2：检测是否有调试器连接
        val isDebuggerConnected = Debug.isDebuggerConnected()
        
        // 方法3：检测等待调试器
        val isWaitingForDebugger = Debug.waitingForDebugger()
        
        // 方法4：检测TracerPid
        val hasTracerPid = hasTracerPid()
        
        // 方法5：检测JDWP端口
        val hasJdwpPort = hasJdwpPort()
        
        val detected = isDebuggerConnected || isWaitingForDebugger || hasTracerPid || hasJdwpPort
        
        if (detected && !isDebugDetected.get()) {
            isDebugDetected.set(true)
        }
        
        return detected
    }
    
    /**
     * 检测TracerPid
     */
    private fun hasTracerPid(): Boolean {
        return try {
            val status = File("/proc/self/status")
            val reader = BufferedReader(FileReader(status))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                if (line!!.startsWith("TracerPid:")) {
                    val pid = line!!.substring(10).trim()
                    reader.close()
                    return pid != "0"
                }
            }
            reader.close()
            false
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 检测JDWP端口
     */
    private fun hasJdwpPort(): Boolean {
        return try {
            val net = File("/proc/net/tcp")
            val reader = BufferedReader(FileReader(net))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                if (line!!.contains(":1F90")) { // JDWP端口8080的16进制
                    reader.close()
                    return true
                }
            }
            reader.close()
            false
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 检测模拟器
     */
    private fun detectEmulator(): Boolean {
        // 检测设备特征
        val deviceFeatures = listOf(
            Build.FINGERPRINT.contains("generic"),
            Build.FINGERPRINT.contains("emulator"),
            Build.MODEL.contains("Emulator"),
            Build.MODEL.contains("Android SDK"),
            Build.MANUFACTURER.contains("Genymotion"),
            Build.HARDWARE.contains("goldfish"),
            Build.HARDWARE.contains("ranchu"),
            Build.PRODUCT.contains("sdk"),
            Build.PRODUCT.contains("emulator"),
            Build.BOARD.contains("goldfish"),
            Build.BOARD.contains("ranchu"),
            Build.BRAND.contains("generic"),
            android.os.Build.DEVICE.contains("generic"),
            android.os.Build.DEVICE.contains("emulator"),
        )
        
        // 检测模拟器特有文件
        val emulatorFiles = listOf(
            "/dev/socket/qemud",
            "/dev/qemu_pipe",
            "/system/lib/libc_malloc_debug_qemu.so",
            "/sys/qemu_trace",
            "/system/bin/qemu-props",
            "/dev/socket/genyd",
            "/dev/socket/baseband_genyd"
        )
        
        val hasEmulatorFile = emulatorFiles.any { File(it).exists() }
        val hasEmulatorFeature = deviceFeatures.any { it }
        
        val detected = hasEmulatorFile || hasEmulatorFeature
        
        if (detected && !isEmulatorDetected.get()) {
            isEmulatorDetected.set(true)
        }
        
        return detected
    }
    
    /**
     * 检测Root
     */
    private fun detectRoot(context: Context): Boolean {
        // 检测Root文件
        val rootFiles = listOf(
            "/system/app/Superuser.apk",
            "/sbin/su",
            "/system/bin/su",
            "/system/xbin/su",
            "/data/local/xbin/su",
            "/data/local/bin/su",
            "/system/sd/xbin/su",
            "/system/bin/failsafe/su",
            "/data/local/su",
            "/su/bin/su",
            "/system/xbin/busybox",
            "/system/bin/busybox",
            "/data/local/busybox",
            "/data/local/xbin/busybox"
        )
        
        val hasRootFile = rootFiles.any { File(it).exists() }
        
        // 检测Root应用
        val rootApps = listOf(
            "com.noshufou.android.su",
            "com.thirdparty.superuser",
            "eu.chainfire.supersu",
            "com.koushikdutta.superuser",
            "com.zachspong.temprootremovejb",
            "com.ramdroid.appquarantine",
            "com.topjohnwu.magisk"
        )
        
        val hasRootApp = rootApps.any { isPackageInstalled(context, it) }
        
        val detected = hasRootFile || hasRootApp
        
        if (detected && !isRootDetected.get()) {
            isRootDetected.set(true)
        }
        
        return detected
    }
    
    /**
     * 检测Xposed框架
     */
    private fun detectXposed(): Boolean {
        return try {
            // 检测Xposed类
            Class.forName("de.robv.android.xposed.XposedBridge")
            true
        } catch (e: ClassNotFoundException) {
            // 检测Xposed文件
            val xposedFiles = listOf(
                "/data/data/de.robv.android.xposed.installer",
                "/data/data/com.solohsu.android.edxp.manager",
                "/data/data/org.meowcat.edxposed.manager"
            )
            xposedFiles.any { File(it).exists() }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 检测Frida框架
     */
    private fun detectFrida(): Boolean {
        // 检测Frida端口
        val fridaPorts = listOf(27042, 27043, 27044, 27045)
        
        return try {
            val net = File("/proc/net/tcp")
            val reader = BufferedReader(FileReader(net))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                for (port in fridaPorts) {
                    val hexPort = Integer.toHexString(port).uppercase()
                    if (line!!.contains(":$hexPort")) {
                        reader.close()
                        return true
                    }
                }
            }
            reader.close()
            false
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 检测签名篡改
     */
    private fun detectSignatureTampering(context: Context): Boolean {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(
                context.packageName, 
                android.content.pm.PackageManager.GET_SIGNATURES
            )
            
            // 获取签名信息
            val signatures = packageInfo.signatures
            if (signatures == null || signatures.isEmpty()) {
                return true
            }
            
            // 这里可以添加预期的签名校验
            // 在实际部署时，应该存储正确的签名哈希值
            
            false
        } catch (e: Exception) {
            true
        }
    }
    
    /**
     * 检查包是否已安装
     */
    private fun isPackageInstalled(context: Context, packageName: String): Boolean {
        return try {
            val pm = context.packageManager
            pm.getPackageInfo(packageName, 0)
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 处理威胁检测
     */
    private fun handleThreatDetected(threatType: String, description: String) {
        // 在实际部署时，可以采取更严厉的措施
        // 这里采用渐进式处理
        
        // 1. 记录威胁
        android.util.Log.w("AntiDebug", "$threatType: $description")
        
        // 2. 延迟处理，增加分析难度
        Thread.sleep((1000..5000).random().toLong())
        
        // 3. 根据威胁类型决定处理方式
        when (threatType) {
            "调试器检测" -> {
                // 可以选择终止进程或采取其他措施
                if (com.hikoncont.BuildConfig.ENABLE_ANTI_DEBUG) {
                    // 生产环境可以启用进程终止
                    // Process.killProcess(Process.myPid())
                    // exitProcess(0)
                }
            }
            "模拟器检测" -> {
                // 可以限制功能或要求验证
                if (com.hikoncont.BuildConfig.ENABLE_EMULATOR_DETECTION) {
                    // 在模拟器环境中可以限制功能
                }
            }
            "Root检测" -> {
                // 可以限制敏感功能
                if (com.hikoncont.BuildConfig.ENABLE_ROOT_DETECTION) {
                    // 在Root环境中可以限制功能
                }
            }
        }
    }
    
    /**
     * 获取威胁检测状态
     */
    fun getThreatStatus(): ThreatStatus {
        return ThreatStatus(
            isDebugDetected = isDebugDetected.get(),
            isEmulatorDetected = isEmulatorDetected.get(),
            isRootDetected = isRootDetected.get()
        )
    }
    
    /**
     * 威胁状态数据类
     */
    data class ThreatStatus(
        val isDebugDetected: Boolean,
        val isEmulatorDetected: Boolean,
        val isRootDetected: Boolean
    ) {
        val isAnyThreatDetected: Boolean
            get() = isDebugDetected || isEmulatorDetected || isRootDetected
    }
} 