package com.hikoncont.service.modules

import android.content.Context
import android.util.Log
import com.hikoncont.OperationLogCollector
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 日志记录管理器
 * 负责管理操作日志的记录、收集和存储
 * 
 * 主要功能:
 * - 操作日志记录
 * - 日志状态控制
 * - 日志数据格式化
 * - 日志存储管理
 * - 系统事件记录
 * - 用户交互记录
 */
class LoggingManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "LoggingManager"
    }
    
    // 协程作用域
    private val loggingScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    // 日志收集器
    private var logCollector: OperationLogCollector? = null
    
    // 日志记录状态
    private var isLoggingEnabled = false
    
    // 日志缓存
    private val logBuffer = mutableListOf<LogEntry>()
    private val maxBufferSize = 1000
    
    /**
     * 初始化日志管理器
     */
    fun initialize(existingLogCollector: OperationLogCollector? = null) {
        try {
            // ✅ 修复：使用传递进来的logCollector实例，确保实例一致性
            if (existingLogCollector != null) {
                logCollector = existingLogCollector
                Log.i(TAG, "✅ 使用现有的OperationLogCollector实例")
            } else {
                // 初始化日志收集器（备用方案）
                logCollector = OperationLogCollector(service)
                Log.i(TAG, "✅ 创建新的OperationLogCollector实例")
            }
            
            Log.i(TAG, "✅ 日志记录管理器初始化完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 初始化日志记录管理器失败", e)
        }
    }
    
    /**
     * 启用操作日志记录
     */
    fun enableLogging() {
        // 暂停：暂时不启用日志记录功能
        // Log.i(TAG, "⏸️ 暂停：暂时不启用日志记录功能")
        // return
        
        try {
            isLoggingEnabled = true
            logCollector?.startLogging()
            Log.i(TAG, "📝 操作日志记录已启用")
            
            // 记录启用日志的事件
            recordOperationLog("SYSTEM_EVENT", "日志记录已启用", null)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启用日志记录失败", e)
        }
    }
    
    /**
     * 禁用操作日志记录
     */
    fun disableLogging() {
        try {
            // 记录禁用日志的事件
            recordOperationLog("SYSTEM_EVENT", "日志记录已禁用", null)
            
            isLoggingEnabled = false
            logCollector?.stopLogging()
            Log.i(TAG, "🔇 操作日志记录已禁用")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 禁用日志记录失败", e)
        }
    }
    
    /**
     * 记录操作日志
     */
    fun recordOperationLog(logType: String, content: String, extraData: Map<String, Any>?) {
        if (!isLoggingEnabled) {
            return
        }
        
        loggingScope.launch {
            try {
                val logEntry = LogEntry(
                    timestamp = System.currentTimeMillis(),
                    logType = logType,
                    content = content,
                    extraData = extraData ?: emptyMap()
                )
                
                // 添加到缓存
                synchronized(logBuffer) {
                    logBuffer.add(logEntry)
                    if (logBuffer.size > maxBufferSize) {
                        logBuffer.removeAt(0) // 移除最老的记录
                    }
                }
                
                // 使用日志收集器记录
                logCollector?.recordLog(logType, content, extraData)
                
                Log.v(TAG, "📝 记录操作日志: [$logType] $content")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 记录操作日志失败: $content", e)
            }
        }
    }
    
    /**
     * 记录点击操作日志
     */
    fun recordClickLog(x: Float, y: Float, target: String = "", method: String = "") {
        recordOperationLog("CLICK", "点击操作: $target", mapOf(
            "x" to x.toDouble(),
            "y" to y.toDouble(),
            "target" to target,
            "method" to method,
            "inputMethod" to "remote_control"
        ))
    }
    
    /**
     * 记录滑动操作日志
     */
    fun recordSwipeLog(startX: Float, startY: Float, endX: Float, endY: Float, duration: Long) {
        recordOperationLog("SWIPE", "滑动操作: ($startX, $startY) → ($endX, $endY)", mapOf(
            "startX" to startX.toDouble(),
            "startY" to startY.toDouble(),
            "endX" to endX.toDouble(),
            "endY" to endY.toDouble(),
            "duration" to duration,
            "inputMethod" to "remote_control"
        ))
    }
    
    /**
     * 记录长按操作日志
     */
    fun recordLongPressLog(x: Float, y: Float, target: String = "") {
        recordOperationLog("LONG_PRESS", "长按操作: $target", mapOf(
            "x" to x.toDouble(),
            "y" to y.toDouble(),
            "target" to target,
            "inputMethod" to "remote_control"
        ))
    }
    
    /**
     * 记录文本输入日志
     */
    fun recordTextInputLog(text: String, method: String = "remote_control") {
        recordOperationLog("TEXT_INPUT", "文本输入: ${text.take(50)}${if (text.length > 50) "..." else ""}", mapOf(
            "textLength" to text.length,
            "inputMethod" to method,
            "containsPassword" to isPasswordLike(text)
        ))
    }
    
    /**
     * 记录按键操作日志
     */
    fun recordKeyEventLog(keyCode: Int, keyName: String, method: String = "system_level") {
        recordOperationLog("KEY_EVENT", "按键操作: $keyName", mapOf(
            "keyCode" to keyCode,
            "keyName" to keyName,
            "inputMethod" to method
        ))
    }
    
    /**
     * 记录系统事件日志
     */
    fun recordSystemEventLog(event: String, details: String = "", extraData: Map<String, Any>? = null) {
        recordOperationLog("SYSTEM_EVENT", "$event: $details", extraData)
    }
    
    /**
     * 记录用户交互日志
     */
    fun recordUserInteractionLog(eventType: String, packageName: String, className: String, text: String = "") {
        recordOperationLog("USER_INTERACTION", "用户交互: $eventType", mapOf(
            "eventType" to eventType,
            "packageName" to packageName,
            "className" to className,
            "text" to text.take(100),
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 记录调试信息日志
     */
    fun recordDebugLog(debugType: String, message: String, data: Map<String, Any>? = null) {
        recordOperationLog("DEBUG", "$debugType: $message", data ?: emptyMap())
    }
    
    /**
     * 记录错误日志
     */
    fun recordErrorLog(errorType: String, message: String, exception: Throwable? = null) {
        val errorData = mutableMapOf<String, Any>(
            "errorType" to errorType,
            "message" to message,
            "timestamp" to System.currentTimeMillis()
        )
        
        exception?.let { e ->
            errorData["exceptionClass"] = e.javaClass.simpleName
            errorData["exceptionMessage"] = e.message ?: "No message"
            errorData["stackTrace"] = e.stackTrace.take(5).joinToString("\n") { it.toString() }
        }
        
        recordOperationLog("ERROR", "错误: $errorType - $message", errorData)
    }
    
    /**
     * 获取日志记录状态
     */
    fun isLoggingEnabled(): Boolean = isLoggingEnabled
    
    /**
     * 获取日志统计信息
     */
    fun getLogStatistics(): Map<String, Any> {
        return synchronized(logBuffer) {
            val typeCount = mutableMapOf<String, Int>()
            logBuffer.forEach { entry ->
                typeCount[entry.logType] = (typeCount[entry.logType] ?: 0) + 1
            }
            
            mapOf(
                "totalLogs" to logBuffer.size,
                "isEnabled" to isLoggingEnabled,
                "bufferSize" to logBuffer.size,
                "maxBufferSize" to maxBufferSize,
                "typeDistribution" to typeCount,
                "oldestLog" to (logBuffer.firstOrNull()?.timestamp ?: 0),
                "newestLog" to (logBuffer.lastOrNull()?.timestamp ?: 0)
            )
        }
    }
    
    /**
     * 获取最近的日志记录
     */
    fun getRecentLogs(count: Int = 50): List<LogEntry> {
        return synchronized(logBuffer) {
            logBuffer.takeLast(count).toList()
        }
    }
    
    /**
     * 按类型获取日志记录
     */
    fun getLogsByType(logType: String, count: Int = 50): List<LogEntry> {
        return synchronized(logBuffer) {
            logBuffer.filter { it.logType == logType }.takeLast(count)
        }
    }
    
    /**
     * 清空日志缓存
     */
    fun clearLogBuffer() {
        synchronized(logBuffer) {
            logBuffer.clear()
            Log.i(TAG, "🧹 日志缓存已清空")
        }
        
        recordOperationLog("SYSTEM_EVENT", "日志缓存已清空", null)
    }
    
    /**
     * 格式化日志数据
     */
    fun formatLogData(logEntry: LogEntry): String {
        return buildString {
            append("[${formatTimestamp(logEntry.timestamp)}] ")
            append("[${logEntry.logType}] ")
            append(logEntry.content)
            
            if (logEntry.extraData.isNotEmpty()) {
                append(" | 数据: ")
                append(logEntry.extraData.entries.joinToString(", ") { "${it.key}=${it.value}" })
            }
        }
    }
    
    /**
     * 导出日志数据
     */
    fun exportLogData(): String {
        return synchronized(logBuffer) {
            buildString {
                appendLine("=== 操作日志导出 ===")
                appendLine("导出时间: ${formatTimestamp(System.currentTimeMillis())}")
                appendLine("日志总数: ${logBuffer.size}")
                appendLine("日志状态: ${if (isLoggingEnabled) "启用" else "禁用"}")
                appendLine()
                
                logBuffer.forEach { logEntry ->
                    appendLine(formatLogData(logEntry))
                }
            }
        }
    }
    
    /**
     * 管理日志存储
     */
    fun manageLogStorage() {
        loggingScope.launch {
            try {
                // 清理过期日志
                val oneDayAgo = System.currentTimeMillis() - 24 * 60 * 60 * 1000L
                synchronized(logBuffer) {
                    logBuffer.removeAll { it.timestamp < oneDayAgo }
                }
                
                Log.d(TAG, "🧹 日志存储管理完成，清理了过期日志")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 日志存储管理失败", e)
            }
        }
    }
    
    /**
     * 更新日志收集器状态
     */
    fun updateLogCollectorStatus(enabled: Boolean) {
        try {
            // 暂停：暂时不启动日志收集器
            // if (enabled && logCollector != null) {
            //     logCollector?.startLogging()
            // } else {
            //     logCollector?.stopLogging()
            // }
            
            Log.d(TAG, "⏸️ 暂停：暂时不更新日志收集器状态: $enabled")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 更新日志收集器状态失败", e)
        }
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "🧹 清理日志管理器资源")
            
            // 停止日志记录
            if (isLoggingEnabled) {
                disableLogging()
            }
            
            // 清理日志收集器
            logCollector?.cleanup()
            logCollector = null
            
            // 清空缓存
            synchronized(logBuffer) {
                logBuffer.clear()
            }
            
            Log.i(TAG, "✅ 日志管理器清理完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理日志管理器失败", e)
        }
    }
    
    // 私有辅助方法
    
    /**
     * 格式化时间戳
     */
    private fun formatTimestamp(timestamp: Long): String {
        return try {
            val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", java.util.Locale.getDefault())
            sdf.format(java.util.Date(timestamp))
        } catch (e: Exception) {
            timestamp.toString()
        }
    }
    
    /**
     * 检查是否为密码类文本
     */
    private fun isPasswordLike(text: String): Boolean {
        return text.length > 4 && text.length < 50 && 
               (text.any { it.isDigit() } || text.any { it.isLetter() })
    }
    
    /**
     * 日志条目数据类
     */
    data class LogEntry(
        val timestamp: Long,
        val logType: String,
        val content: String,
        val extraData: Map<String, Any>
    )
} 