package com.flashlink.vpn

import android.annotation.SuppressLint
import android.content.Context
import org.json.JSONObject
import java.io.File
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

/**
 * Core日志记录器 - 用于记录核心模块的stats和version信息
 * 功能：
 * 1. 记录 stats 统计信息
 * 2. 记录 version 版本信息
 * 3. 线程安全的文件读写
 */
class CoreLogger private constructor(context: Context) {
    
    private val context: Context = context.applicationContext
    
    // 全局文件锁，防止多个方法同时读写文件
    private val fileLock = ReentrantLock()
    
    companion object {
        private const val LOG_FOLDER = "boost_logs"
        private const val CORE_LOG_FILE = "core.json"
        private const val BUFFER_SIZE = 8192

        @SuppressLint("StaticFieldLeak")
        @Volatile
        private var instance: CoreLogger? = null
        
        fun getInstance(context: Context): CoreLogger {
            return instance ?: synchronized(this) {
                instance ?: CoreLogger(context).also { instance = it }
            }
        }
    }
    
    /**
     * 获取core.json文件路径
     */
    private fun getCoreLogFile(): File {
        val logDir = File(context.filesDir, LOG_FOLDER)
        if (!logDir.exists()) {
            logDir.mkdirs()
        }
        return File(logDir, CORE_LOG_FILE)
    }
    
    /**
     * 读取core.json文件内容
     */
    private fun readCoreJsonFile(): JSONObject {
        val coreLogFile = getCoreLogFile()
        if (!coreLogFile.exists()) {
            return JSONObject()
        }
        
        val content = coreLogFile.bufferedReader(bufferSize = BUFFER_SIZE).use { it.readText() }
        
        if (content.isEmpty()) {
            return JSONObject()
        }
        
        return try {
            JSONObject(content)
        } catch (e: Exception) {
            VLog.e(TAG, "readCoreJsonFile parse error: ${e.message}")
            JSONObject()
        }
    }
    
    /**
     * 写入core.json文件内容
     */
    private fun writeCoreJsonFile(coreData: JSONObject) {
        val coreLogFile = getCoreLogFile()
        coreLogFile.bufferedWriter().use { writer ->
            writer.write(coreData.toString(2))
            writer.flush()
        }
    }
    
    /**
     * 安全地更新core.json文件
     */
    private inline fun safeUpdateCoreJson(operationName: String, crossinline update: (JSONObject) -> Unit) {
        fileLock.withLock {
            try {
                val coreData = readCoreJsonFile()
                
                // 执行具体的更新操作
                try {
                    update(coreData)
                } catch (e: Exception) {
                    VLog.e(TAG, "$operationName Error in update callback: ${e.message}")
                    return
                }
                
                // 保存更新后的文件
                writeCoreJsonFile(coreData)
                VLog.i(TAG, "$operationName successfully updated core.json")
                
            } catch (e: Exception) {
                VLog.e(TAG, "$operationName Error updating core.json: ${e.message}")
            }
        }
    }
    
    /**
     * 安全地更新JSONObject
     */
    private fun safePut(jsonObject: JSONObject?, key: String, value: Any?, operationName: String) {
        if (jsonObject == null) {
            VLog.e(TAG, "$operationName JSONObject is null, cannot put key: $key")
            return
        }
        
        try {
            jsonObject.put(key, value)
        } catch (e: Exception) {
            VLog.e(TAG, "$operationName Failed to put key '$key' with value '$value': ${e.message}")
        }
    }
    
    /**
     * 解析stats字符串并将内容拆解存储到coreData中
     * @param statsStr stats的JSON字符串
     * @param coreData 目标JSONObject
     * @param operationName 操作名称（用于日志）
     */
    private fun parseAndPutStats(statsStr: String?, coreData: JSONObject, operationName: String) {
        if (statsStr.isNullOrEmpty()) {
            VLog.w(TAG, "$operationName stats is null or empty")
            return
        }
        
        try {
            val statsJson = JSONObject(statsStr)
            // 遍历stats中的所有字段，直接拆解到coreData中
            val keys = statsJson.keys()
            while (keys.hasNext()) {
                val key = keys.next()
                val value = statsJson.get(key)
                safePut(coreData, key, value, operationName)
            }
        } catch (e: Exception) {
            VLog.e(TAG, "$operationName Failed to parse stats: ${e.message}")
        }
    }

    /**
     * 同时更新stats和version信息
     * @param stats 统计信息JSON字符串，内容会被拆解存储
     * @param version 版本信息int
     */
    fun updateStatsAndVersion(stats: String?, version: Long) {
        safeUpdateCoreJson("updateStatsAndVersion") { coreData ->
            val currentTime = System.currentTimeMillis()
            parseAndPutStats(stats, coreData, "updateStatsAndVersion")
            safePut(coreData, "version", version, "updateStatsAndVersion")
            safePut(coreData, "generatedTime", currentTime, "updateStatsAndVersion")
        }
    }
    
    /**
     * 获取当前core.json的内容
     * @return JSON字符串，如果文件不存在或读取失败返回null
     */
    fun getCoreLogContent(): String? {
        return fileLock.withLock {
            try {
                val coreData = readCoreJsonFile()
                coreData.toString(2)
            } catch (e: Exception) {
                VLog.e(TAG, "getCoreLogContent error: ${e.message}")
                null
            }
        }
    }
    
    /**
     * 清空core.json文件
     */
    fun clearCoreLog() {
        fileLock.withLock {
            try {
                val coreLogFile = getCoreLogFile()
                if (coreLogFile.exists()) {
                    coreLogFile.delete()
                }
                VLog.i(TAG, "clearCoreLog successfully cleared core.json")
            } catch (e: Exception) {
                VLog.e(TAG, "clearCoreLog error: ${e.message}")
            }
        }
    }
}

private const val TAG = "CoreLogger"
