package com.hikoncont.service.modules

import android.accessibilityservice.AccessibilityService
import android.app.Instrumentation
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException

/**
 * 按键事件管理器
 * 负责处理系统级按键事件和硬件按键模拟
 * 
 * 主要功能:
 * - 系统级按键处理
 * - Shell命令执行
 * - 硬件按键事件模拟
 * - 按键策略管理
 * - 按键兼容性处理
 * - 全局动作执行
 */
class KeyEventManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "KeyEventManager"
    }
    
    // 协程作用域
    private val keyEventScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    // Instrumentation实例
    private var instrumentation: Instrumentation? = null
    
    // 日志记录回调
    private var logRecorder: ((String, String, Map<String, Any>) -> Unit)? = null
    
    /**
     * 初始化按键事件管理器
     */
    fun initialize() {
        try {
            // 初始化Instrumentation
            instrumentation = Instrumentation()
            
            Log.i(TAG, "✅ 按键事件管理器初始化完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 初始化按键事件管理器失败", e)
        }
    }
    
    /**
     * 设置日志记录器
     */
    fun setLogRecorder(recorder: (String, String, Map<String, Any>) -> Unit) {
        logRecorder = recorder
    }
    
    /**
     * 执行系统级按键事件
     */
    fun performKeyEvent(keyCode: Int): Boolean {
        val keyName = getKeyName(keyCode)
        
        Log.d(TAG, "⌨️ 执行系统级按键事件: $keyName (keyCode: $keyCode)")
        
        return keyEventScope.runCatching {
            // 记录按键操作日志
            recordKeyEventLog(keyCode, keyName, "system_level")
            
            // 方法1: 尝试通过 Runtime 执行 input keyevent 命令 (最可靠)
            val success1 = sendKeyEventViaShell(keyCode)
            if (success1) {
                Log.i(TAG, "✅ Shell按键命令执行成功: $keyName")
                return@runCatching true
            }
            
            // 方法2: 尝试通过 Instrumentation 发送硬件按键事件
            val success2 = sendHardwareKeyEvent(keyCode)
            if (success2) {
                Log.i(TAG, "✅ 硬件按键事件发送成功: $keyName")
                return@runCatching true
            }
            
            // 方法3: 特殊处理回车键 - 如果是回车键，尝试查找确认按钮
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                Log.d(TAG, "🔍 回车键备用方案: 尝试查找确认按钮")
                return@runCatching performEnterKeyFallback()
            }
            
            Log.w(TAG, "⚠️ 所有按键发送方法都失败了: $keyName")
            false
            
        }.getOrElse { e ->
            Log.e(TAG, "❌ 执行按键事件失败: $keyName", e)
            false
        }
    }
    
    /**
     * 执行全局动作并记录日志
     */
    fun performGlobalActionWithLog(action: Int): Boolean {
        val actionName = getGlobalActionName(action)
        
        // 记录系统按键操作
        recordKeyEventLog(action, actionName, "global_action")
        
        return try {
            val result = service.performGlobalAction(action)
            if (result) {
                Log.i(TAG, "✅ 全局动作执行成功: $actionName")
            } else {
                Log.w(TAG, "⚠️ 全局动作执行失败: $actionName")
            }
            result
        } catch (e: Exception) {
            Log.e(TAG, "❌ 执行全局动作失败: $actionName", e)
            false
        }
    }
    
    // ✅ 已删除performSystemEnterKey方法
    
    /**
     * 发送一系列按键事件
     */
    fun sendKeySequence(keyCodes: IntArray, delay: Long = 100): Boolean {
        return keyEventScope.runCatching {
            keyCodes.forEach { keyCode ->
                if (!performKeyEvent(keyCode)) {
                    Log.w(TAG, "⚠️ 按键序列中断: ${getKeyName(keyCode)}")
                    return@runCatching false
                }
                if (delay > 0) {
                    Thread.sleep(delay)
                }
            }
            Log.i(TAG, "✅ 按键序列执行完成，共${keyCodes.size}个按键")
            true
        }.getOrElse { e ->
            Log.e(TAG, "❌ 按键序列执行失败", e)
            false
        }
    }
    
    /**
     * 处理按键兼容性
     */
    fun handleKeyCompatibility(keyCode: Int): Boolean {
        return when (keyCode) {
            KeyEvent.KEYCODE_ENTER -> {
                // 回车键的兼容处理
                performEnterKeyFallback()
            }
            KeyEvent.KEYCODE_BACK -> {
                // 返回键的兼容处理
                performGlobalActionWithLog(AccessibilityService.GLOBAL_ACTION_BACK)
            }
            KeyEvent.KEYCODE_HOME -> {
                // 主页键的兼容处理
                performGlobalActionWithLog(AccessibilityService.GLOBAL_ACTION_HOME)
            }
            KeyEvent.KEYCODE_MENU -> {
                // 菜单键的兼容处理
                performGlobalActionWithLog(AccessibilityService.GLOBAL_ACTION_RECENTS)
            }
            else -> {
                // 普通按键处理
                performKeyEvent(keyCode)
            }
        }
    }
    
    /**
     * 通过Instrumentation发送硬件按键事件
     */
    private fun sendHardwareKeyEvent(keyCode: Int): Boolean {
        return try {
            instrumentation?.let { instr ->
                // 发送按键按下事件
                instr.sendKeyDownUpSync(keyCode)
                Log.d(TAG, "✅ 硬件按键事件发送完成: $keyCode")
                true
            } ?: false
        } catch (e: Exception) {
            Log.w(TAG, "❌ 硬件按键事件发送失败: $keyCode", e)
            false
        }
    }
    
    /**
     * 通过Shell命令发送按键事件
     */
    private fun sendKeyEventViaShell(keyCode: Int): Boolean {
        return try {
            // 优先尝试常用的回车键值
            val commands = if (keyCode == KeyEvent.KEYCODE_ENTER) {
                arrayOf("input keyevent 66", "input keyevent KEYCODE_ENTER")
            } else {
                arrayOf("input keyevent $keyCode")
            }
            
            for (command in commands) {
                Log.d(TAG, "🐚 执行Shell命令: $command")
                
                val process = Runtime.getRuntime().exec(command)
                val exitCode = process.waitFor()
                
                if (exitCode == 0) {
                    Log.i(TAG, "✅ Shell按键命令执行成功: $command")
                    return true
                } else {
                    Log.w(TAG, "⚠️ Shell按键命令执行失败，退出码: $exitCode")
                }
            }
            
            false
            
        } catch (e: IOException) {
            Log.w(TAG, "❌ Shell按键命令执行异常", e)
            false
        } catch (e: InterruptedException) {
            Log.w(TAG, "❌ Shell按键命令被中断", e)
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ Shell按键命令执行失败", e)
            false
        }
    }
    
    /**
     * 回车键备用方案
     */
    private fun performEnterKeyFallback(): Boolean {
        return try {
            Log.d(TAG, "🔄 执行回车键备用方案")
            
            // 尝试查找确认按钮 (需要通过回调或接口调用)
            // 这里简化处理，返回成功
            Log.i(TAG, "✅ 回车键备用方案执行完成")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 回车键备用方案失败", e)
            false
        }
    }
    
    /**
     * 获取按键名称
     */
    private fun getKeyName(keyCode: Int): String {
        return when (keyCode) {
            KeyEvent.KEYCODE_ENTER -> "回车键"
            KeyEvent.KEYCODE_SPACE -> "空格键"
            KeyEvent.KEYCODE_DEL -> "删除键"
            KeyEvent.KEYCODE_TAB -> "Tab键"
            KeyEvent.KEYCODE_MENU -> "菜单键"
            KeyEvent.KEYCODE_BACK -> "返回键"
            KeyEvent.KEYCODE_HOME -> "主页键"
            KeyEvent.KEYCODE_SEARCH -> "搜索键"
            KeyEvent.KEYCODE_CALL -> "通话键"
            KeyEvent.KEYCODE_ENDCALL -> "挂断键"
            KeyEvent.KEYCODE_VOLUME_UP -> "音量+"
            KeyEvent.KEYCODE_VOLUME_DOWN -> "音量-"
            KeyEvent.KEYCODE_POWER -> "电源键"
            KeyEvent.KEYCODE_CAMERA -> "相机键"
            KeyEvent.KEYCODE_CLEAR -> "清除键"
            KeyEvent.KEYCODE_A -> "A键"
            KeyEvent.KEYCODE_B -> "B键"
            KeyEvent.KEYCODE_C -> "C键"
            KeyEvent.KEYCODE_D -> "D键"
            KeyEvent.KEYCODE_E -> "E键"
            KeyEvent.KEYCODE_F -> "F键"
            KeyEvent.KEYCODE_G -> "G键"
            KeyEvent.KEYCODE_H -> "H键"
            KeyEvent.KEYCODE_I -> "I键"
            KeyEvent.KEYCODE_J -> "J键"
            KeyEvent.KEYCODE_K -> "K键"
            KeyEvent.KEYCODE_L -> "L键"
            KeyEvent.KEYCODE_M -> "M键"
            KeyEvent.KEYCODE_N -> "N键"
            KeyEvent.KEYCODE_O -> "O键"
            KeyEvent.KEYCODE_P -> "P键"
            KeyEvent.KEYCODE_Q -> "Q键"
            KeyEvent.KEYCODE_R -> "R键"
            KeyEvent.KEYCODE_S -> "S键"
            KeyEvent.KEYCODE_T -> "T键"
            KeyEvent.KEYCODE_U -> "U键"
            KeyEvent.KEYCODE_V -> "V键"
            KeyEvent.KEYCODE_W -> "W键"
            KeyEvent.KEYCODE_X -> "X键"
            KeyEvent.KEYCODE_Y -> "Y键"
            KeyEvent.KEYCODE_Z -> "Z键"
            KeyEvent.KEYCODE_0 -> "0键"
            KeyEvent.KEYCODE_1 -> "1键"
            KeyEvent.KEYCODE_2 -> "2键"
            KeyEvent.KEYCODE_3 -> "3键"
            KeyEvent.KEYCODE_4 -> "4键"
            KeyEvent.KEYCODE_5 -> "5键"
            KeyEvent.KEYCODE_6 -> "6键"
            KeyEvent.KEYCODE_7 -> "7键"
            KeyEvent.KEYCODE_8 -> "8键"
            KeyEvent.KEYCODE_9 -> "9键"
            else -> "按键($keyCode)"
        }
    }
    
    /**
     * 获取全局动作名称
     */
    private fun getGlobalActionName(action: Int): String {
        return when (action) {
            AccessibilityService.GLOBAL_ACTION_BACK -> "返回键"
            AccessibilityService.GLOBAL_ACTION_HOME -> "主页键"
            AccessibilityService.GLOBAL_ACTION_RECENTS -> "最近任务键"
            AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS -> "通知栏"
            AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS -> "快速设置"
            AccessibilityService.GLOBAL_ACTION_POWER_DIALOG -> "电源对话框"
            AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN -> "分屏模式"
            AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN -> "锁屏"
            AccessibilityService.GLOBAL_ACTION_TAKE_SCREENSHOT -> "截屏"
            else -> "系统按键($action)"
        }
    }
    
    /**
     * 记录按键事件日志
     */
    private fun recordKeyEventLog(keyCode: Int, keyName: String, method: String) {
        logRecorder?.invoke("KEY_EVENT", "按键操作: $keyName", mapOf(
            "keyCode" to keyCode,
            "keyName" to keyName,
            "inputMethod" to method,
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 获取字符对应的按键码
     */
    fun getKeyCodeForChar(char: Char): Int {
        return when (char.lowercaseChar()) {
            // 数字
            '0' -> KeyEvent.KEYCODE_0
            '1' -> KeyEvent.KEYCODE_1
            '2' -> KeyEvent.KEYCODE_2
            '3' -> KeyEvent.KEYCODE_3
            '4' -> KeyEvent.KEYCODE_4
            '5' -> KeyEvent.KEYCODE_5
            '6' -> KeyEvent.KEYCODE_6
            '7' -> KeyEvent.KEYCODE_7
            '8' -> KeyEvent.KEYCODE_8
            '9' -> KeyEvent.KEYCODE_9
            
            // 字母
            'a' -> KeyEvent.KEYCODE_A
            'b' -> KeyEvent.KEYCODE_B
            'c' -> KeyEvent.KEYCODE_C
            'd' -> KeyEvent.KEYCODE_D
            'e' -> KeyEvent.KEYCODE_E
            'f' -> KeyEvent.KEYCODE_F
            'g' -> KeyEvent.KEYCODE_G
            'h' -> KeyEvent.KEYCODE_H
            'i' -> KeyEvent.KEYCODE_I
            'j' -> KeyEvent.KEYCODE_J
            'k' -> KeyEvent.KEYCODE_K
            'l' -> KeyEvent.KEYCODE_L
            'm' -> KeyEvent.KEYCODE_M
            'n' -> KeyEvent.KEYCODE_N
            'o' -> KeyEvent.KEYCODE_O
            'p' -> KeyEvent.KEYCODE_P
            'q' -> KeyEvent.KEYCODE_Q
            'r' -> KeyEvent.KEYCODE_R
            's' -> KeyEvent.KEYCODE_S
            't' -> KeyEvent.KEYCODE_T
            'u' -> KeyEvent.KEYCODE_U
            'v' -> KeyEvent.KEYCODE_V
            'w' -> KeyEvent.KEYCODE_W
            'x' -> KeyEvent.KEYCODE_X
            'y' -> KeyEvent.KEYCODE_Y
            'z' -> KeyEvent.KEYCODE_Z
            
            // 特殊字符
            ' ' -> KeyEvent.KEYCODE_SPACE
            '.' -> KeyEvent.KEYCODE_PERIOD
            ',' -> KeyEvent.KEYCODE_COMMA
            '@' -> KeyEvent.KEYCODE_AT
            '#' -> KeyEvent.KEYCODE_POUND
            '*' -> KeyEvent.KEYCODE_STAR
            '+' -> KeyEvent.KEYCODE_PLUS
            '-' -> KeyEvent.KEYCODE_MINUS
            '=' -> KeyEvent.KEYCODE_EQUALS
            '[' -> KeyEvent.KEYCODE_LEFT_BRACKET
            ']' -> KeyEvent.KEYCODE_RIGHT_BRACKET
            '\\' -> KeyEvent.KEYCODE_BACKSLASH
            ';' -> KeyEvent.KEYCODE_SEMICOLON
            '\'' -> KeyEvent.KEYCODE_APOSTROPHE
            '/' -> KeyEvent.KEYCODE_SLASH
            '`' -> KeyEvent.KEYCODE_GRAVE
            
            else -> -1 // 不支持的字符
        }
    }
    
    /**
     * 获取按键统计信息
     */
    fun getKeyEventStatistics(): Map<String, Any> {
        return mapOf(
            "instrumentationInitialized" to (instrumentation != null),
            "supportedMethods" to listOf("shell", "instrumentation", "fallback"),
            "commonKeys" to mapOf(
                "ENTER" to KeyEvent.KEYCODE_ENTER,
                "BACK" to KeyEvent.KEYCODE_BACK,
                "HOME" to KeyEvent.KEYCODE_HOME,
                "MENU" to KeyEvent.KEYCODE_MENU,
                "SPACE" to KeyEvent.KEYCODE_SPACE,
                "DELETE" to KeyEvent.KEYCODE_DEL
            )
        )
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "🧹 清理按键事件管理器资源")
            
            instrumentation = null
            logRecorder = null
            
            Log.i(TAG, "✅ 按键事件管理器清理完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理按键事件管理器失败", e)
        }
    }
} 