package com.hikoncont.crash

import android.content.Context
import android.os.Build
import android.util.Log
import io.socket.client.Socket
import kotlinx.coroutines.*
import org.json.JSONObject

/**
 * 崩溃日志上传器
 * 在应用重启后检查本地崩溃日志，通过 Socket.IO 上传到服务端
 */
class CrashLogUploader(private val context: Context) {

    companion object {
        private const val TAG = "CrashLogUploader"
        private const val MAX_LOG_SIZE = 512 * 1024 // 单个日志最大512KB
        private const val UPLOAD_DELAY_MS = 5000L // 启动后延迟5秒再上传，等待Socket连接稳定
    }

    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    /**
     * 在Socket连接成功后调用，上传待处理的崩溃日志
     */
    fun uploadPendingLogs(socket: Socket?, deviceId: String) {
        scope.launch {
            try {
                delay(UPLOAD_DELAY_MS)

                val crashHandler = CrashHandler.getInstance()
                val pendingLogs = crashHandler.getPendingCrashLogs()

                if (pendingLogs.isEmpty()) {
                    Log.d(TAG, "📋 无待上传的崩溃日志")
                    return@launch
                }

                Log.i(TAG, "📤 发现 ${pendingLogs.size} 个崩溃日志待上传")

                for (logFile in pendingLogs) {
                    if (socket?.connected() != true) {
                        Log.w(TAG, "⚠️ Socket未连接，停止上传")
                        break
                    }

                    try {
                        val content = logFile.readText()
                        if (content.length > MAX_LOG_SIZE) {
                            Log.w(TAG, "⚠️ 崩溃日志过大，截断: ${logFile.name} (${content.length}B)")
                        }

                        val payload = JSONObject().apply {
                            put("deviceId", deviceId)
                            put("fileName", logFile.name)
                            put("content", content.take(MAX_LOG_SIZE))
                            put("fileSize", logFile.length())
                            put("crashTime", extractCrashTimestamp(logFile.name))
                            put("uploadTime", System.currentTimeMillis())
                            put("deviceModel", Build.MODEL)
                            put("osVersion", "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
                        }

                        socket.emit("crash_log", payload)
                        Log.i(TAG, "✅ 已上传崩溃日志: ${logFile.name}")

                        // 上传成功后删除本地文件
                        logFile.delete()
                        Log.d(TAG, "🗑️ 已删除本地崩溃日志: ${logFile.name}")

                        // 间隔发送，避免拥塞
                        delay(500)
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 上传崩溃日志失败: ${logFile.name}", e)
                    }
                }

                Log.i(TAG, "📤 崩溃日志上传完成")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 崩溃日志上传流程异常", e)
            }
        }
    }

    /**
     * 从文件名提取崩溃时间戳
     * 文件名格式: crash_2025-01-01_12-00-00_1234567890.log
     */
    private fun extractCrashTimestamp(fileName: String): Long {
        return try {
            val parts = fileName.removeSuffix(".log").split("_")
            parts.lastOrNull()?.toLongOrNull() ?: 0L
        } catch (_: Exception) {
            0L
        }
    }

    fun destroy() {
        scope.cancel()
    }
}
