package com.gallery.free.wallpaper

import android.app.Application
import android.content.ComponentCallbacks2
import android.content.Context
import android.util.Log
import android.util.LruCache
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.ad.ironsourcelibrary.ISAdManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.gallery.free.wallpaper.database.FavorWpManager
import com.gallery.free.wallpaper.environment.ad.AdActivityManager
import com.gallery.free.wallpaper.environment.jb.MagicLockManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyApplication : Application() {

    companion object {
        @Volatile
        private var instance: MyApplication? = null
        val FIXED_CATEGORIES = listOf("Film", "Nature", "Travel")
        private const val JSON_SUFFIX = "_two.json"
        private const val PREFS_NAME = "wallpaper_app_settings"
        private const val KEY_FIRST_LAUNCH = "first_launch"
        private const val KEY_DEFAULT_CATEGORY = "default_category"
        private const val KEY_IMAGE_QUALITY = "image_quality"
        private const val KEY_LAST_CLEANUP = "last_cleanup_time"
        private const val MAX_WALLPAPERS_PER_CATEGORY = 200
        private const val MAX_CACHE_CATEGORIES = 3
        private const val CACHE_STATS_KEY = "cache_stats"
    }
    // 协程作用域
    private val applicationScope = CoroutineScope(Dispatchers.IO + Job())
    // 管理器
    private lateinit var favoriteManager: FavorWpManager
    // 缓存
    private val wallpaperCache = LruCache<String, List<WallpaperJson>>(1)
    private val wallpaperItemCache = LruCache<String, List<WpItem>>(1)
    // 配置
    private lateinit var appConfig: AppConfig
    // 缓存统计
    private var cacheHits = 0
    private var totalLoads = 0
    data class AppConfig(
        val fixedCategories: List<String> = FIXED_CATEGORIES,
        val preloadCategories: List<String> = FIXED_CATEGORIES, // 预加载也使用固定的三个分类
        val cacheSizeLimit: Int = MAX_CACHE_CATEGORIES,
        val enableAutoCleanup: Boolean = true,
        val imageQuality: String = "balanced",
        val maxWallpapersPerCategory: Int = MAX_WALLPAPERS_PER_CATEGORY
    )

    override fun onCreate() {
        super.onCreate()
        instance = this

        Log.d("MyApplication", "=== 应用启动 ===")
        Log.d("MyApplication", "包名: ${packageName}")
        Log.d("MyApplication", "数据库路径: ${getDatabasePath("FavoriteWallpapers.db")?.absolutePath}")
        Log.d("MyApplication", "缓存配置: 最多缓存 $MAX_CACHE_CATEGORIES 个分类，每分类 $MAX_WALLPAPERS_PER_CATEGORY 张")
        Log.d("MyApplication", "固定分类: ${FIXED_CATEGORIES.joinToString(", ")}")

        appConfig = AppConfig()
        initApplication()
        startMemoryMonitoring()

        // 验证固定分类文件
        validateFixedCategories()

        AdActivityManager.instance.setControl(this)
        MagicLockManager.init(this)

        ISAdManager.init("-------WallpaperGallery--------",this,"24e146eb5","1x1dmfonwgx54zkn","3r21zexffllavwqj","4v2mbujbbk8wq7ed",false,{

        }){

        }
    }

    /**
     * 验证固定分类文件是否存在
     */
    private fun validateFixedCategories() {
        applicationScope.launch {
            try {
                val assets = assets.list("") ?: emptyArray()
                val availableFiles = assets.filter { it.endsWith(".json") }

                Log.d("MyApplication", "=== 验证固定分类文件 ===")
                Log.d("MyApplication", "Assets中的JSON文件: ${availableFiles.joinToString(", ")}")

                for (category in FIXED_CATEGORIES) {
                    val expectedFileName = "${category}${JSON_SUFFIX}"
                    if (availableFiles.contains(expectedFileName)) {
                        Log.d("MyApplication", "✅ [$category]: $expectedFileName 存在")
                    } else {
                        Log.e("MyApplication", "❌ [$category]: $expectedFileName 不存在 - 将无法加载数据")
                    }
                }
            } catch (e: Exception) {
                Log.e("MyApplication", "验证分类文件失败", e)
            }
        }
    }

    private fun initApplication() {
        Log.d("MyApplication", "开始初始化应用")
        initDatabase()        // 1. 初始化数据库
        preloadWallpaperData() // 2. 预加载固定的三个分类
        configureImageLoader() // 3. 配置图片加载库
        initAppLifecycleObserver() // 4. 初始化应用状态监听
        initGlobalSettings()  // 5. 其他全局初始化
        Log.d("MyApplication", "应用初始化完成")
    }

    /**
     * 启动内存监控
     */
    private fun startMemoryMonitoring() {
        applicationScope.launch {
            while (true) {
                kotlinx.coroutines.delay(60000)

                val runtime = Runtime.getRuntime()
                val usedMemoryMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024)
                val maxMemoryMB = runtime.maxMemory() / (1024 * 1024)
                val usagePercent = (usedMemoryMB.toFloat() / maxMemoryMB.toFloat()) * 100

                Log.d("MemoryMonitor", "内存使用: ${"%.1f".format(usagePercent)}% ($usedMemoryMB/$maxMemoryMB MB)")
                if (usagePercent > 85) {
                    Log.w("MemoryMonitor", "内存使用率超过85%，执行清理")
                    clearExcessCaches()
                }
                if (totalLoads > 0 && totalLoads % 200 == 0) {
                    logCacheStatistics()
                }
            }
        }
    }

    /**
     * 记录缓存统计
     */
    private fun logCacheStatistics() {
        val hitRate = if (totalLoads > 0) {
            (cacheHits.toFloat() / totalLoads.toFloat()) * 100
        } else 0f

        val cachedCategories = wallpaperItemCache.snapshot().keys
        val totalWallpapers = cachedCategories.sumOf { category ->
            wallpaperItemCache.get(category)?.size ?: 0
        }

        Log.d("CacheStats", "=== 缓存统计 ===")
        Log.d("CacheStats", "命中率: ${"%.1f".format(hitRate)}% ($cacheHits/$totalLoads)")
        Log.d("CacheStats", "缓存分类数: ${cachedCategories.size}/$MAX_CACHE_CATEGORIES")
        Log.d("CacheStats", "总壁纸数: $totalWallpapers 张")
        Log.d("CacheStats", "缓存分类: ${cachedCategories.joinToString()}")

        // 保存统计
        getSharedPreferences(CACHE_STATS_KEY, Context.MODE_PRIVATE).edit()
            .putInt("totalLoads", totalLoads)
            .putInt("cacheHits", cacheHits)
            .putLong("lastCheck", System.currentTimeMillis())
            .apply()
    }

    /**
     * 清理多余缓存
     */
    private fun clearExcessCaches() {
        Log.d("MemoryMonitor", "清理多余缓存...")

        // 清理Glide内存缓存
        Glide.get(this).clearMemory()

        // 如果缓存分类超过限制，清理最少使用的
        if (wallpaperItemCache.size() > MAX_CACHE_CATEGORIES) {
            val snapshot = wallpaperItemCache.snapshot()
            val keys = snapshot.keys.toList()

            // 保留最近使用的，清理其他的（但不是全部清理）
            val excessCount = keys.size - MAX_CACHE_CATEGORIES
            if (excessCount > 0) {
                for (i in 0 until excessCount) {
                    wallpaperItemCache.remove(keys[i])
                    wallpaperCache.remove(keys[i])
                }
                Log.d("MemoryMonitor", "清理了 $excessCount 个分类缓存")
            }
        }
        if (System.currentTimeMillis() % 5 == 0L) {
            System.gc()
        }
    }

    /**
     * 初始化数据库
     */
    private fun initDatabase() {
        applicationScope.launch {
            try {
                favoriteManager = FavorWpManager.getInstance(this@MyApplication)

                val favoriteCount = favoriteManager.getFavoriteCount()
                Log.d("MyApplication", "✅ 数据库初始化完成")
                Log.d("MyApplication", "   数据库路径: ${getDatabasePath("FavoriteWallpapers.db")?.absolutePath}")
                Log.d("MyApplication", "   收藏数量: $favoriteCount")

                if (favoriteCount > 0) {
                    Log.d("MyApplication", "   数据库中有 $favoriteCount 条收藏记录，数据已保留")
                }

            } catch (e: Exception) {
                Log.e("MyApplication", "❌ 数据库初始化失败: ${e.message}", e)
            }
        }
    }

    /**
     * 预加载壁纸数据（每个分类只加载200张）
     */
    private fun preloadWallpaperData() {
        applicationScope.launch {
            try {
                Log.d("MyApplication", "开始预加载壁纸数据（固定三个分类，每分类${appConfig.maxWallpapersPerCategory}张）")

                // 只预加载固定的三个分类
                FIXED_CATEGORIES.forEach { category ->
                    preloadWallpaperCategory(category)
                }

                Log.d("MyApplication", "壁纸数据预加载完成")

            } catch (e: Exception) {
                Log.e("MyApplication", "壁纸数据预加载失败: ${e.message}", e)
            }
        }
    }

    /**
     * 预加载特定分类的壁纸数据（只加载200张）
     */
    private fun preloadWallpaperCategory(category: String) {
        applicationScope.launch {
            try {
                Log.d("MyApplication", "预加载固定分类: $category (限${appConfig.maxWallpapersPerCategory}张)")

                val fileName = "${category}${JSON_SUFFIX}"

                // JsonUtils 加载数据
                val allWallpapers = Utils_json.loadWallpapersFromAssets(
                    this@MyApplication,
                    fileName
                )

                if (allWallpapers.isNotEmpty()) {
                    val limitedWallpapers = if (allWallpapers.size > appConfig.maxWallpapersPerCategory) {
                        Log.d("MyApplication", "分类 [$category] 有 ${allWallpapers.size} 张，只加载前 ${appConfig.maxWallpapersPerCategory} 张")
                        allWallpapers.take(appConfig.maxWallpapersPerCategory)
                    } else {
                        allWallpapers
                    }

                    // 缓存原始 JSON 数据
                    synchronized(wallpaperCache) {
                        wallpaperCache.put(category, limitedWallpapers)
                    }

                    val wallpaperItems = limitedWallpapers.map { wallpaperJson ->
                        Utils_json.convertToWallpaperItem(wallpaperJson)
                    }

                    synchronized(wallpaperItemCache) {
                        wallpaperItemCache.put(category, wallpaperItems)
                    }

                    Log.d("MyApplication", "✅ 预加载分类 [$category] 完成，数量: ${limitedWallpapers.size}")
                } else {
                    Log.w("MyApplication", "⚠️ 分类 [$category] 没有数据或加载失败")
                }

            } catch (e: Exception) {
                Log.e("MyApplication", "❌ 预加载分类 [$category] 失败: ${e.message}", e)
            }
        }
    }

    /**
     * 获取壁纸数据（优先从缓存获取，最多200张）
     */
    suspend fun getWallpaperData(category: String): List<WallpaperJson> {
        totalLoads++
        return withContext(Dispatchers.IO) {
            val categoryName = if (category.endsWith("_two.json")) {
                category.replace("_two.json", "")
            } else {
                category
            }

            // 先从缓存获取
            synchronized(wallpaperCache) {
                val cachedData = wallpaperCache.get(categoryName)
                if (cachedData != null) {
                    cacheHits++
                    Log.d("MyApplication", "缓存命中: [$categoryName] 数量: ${cachedData.size}")
                    return@withContext cachedData
                }
            }

            // 缓存中没有，则加载
            Log.d("MyApplication", "缓存未命中: [$categoryName]，开始加载")
            val fileName = if (category.endsWith(".json")) category else "${categoryName}_two.json"

            val allWallpapers = Utils_json.loadWallpapersFromAssets(
                this@MyApplication,
                fileName
            )
            val wallpapers = if (allWallpapers.size > appConfig.maxWallpapersPerCategory) {
                Log.d("MyApplication", "分类 [$categoryName] 有 ${allWallpapers.size} 张，只返回前 ${appConfig.maxWallpapersPerCategory} 张")
                allWallpapers.take(appConfig.maxWallpapersPerCategory)
            } else {
                allWallpapers
            }

            // 更新缓存（如果数据有效）
            if (wallpapers.isNotEmpty()) {
                synchronized(wallpaperCache) {
                    wallpaperCache.put(categoryName, wallpapers)
                }

                Log.d("MyApplication", "已缓存分类: [$categoryName] 数量: ${wallpapers.size}")
            }

            return@withContext wallpapers
        }
    }

    /**
     * 获取转换后的壁纸项目（优先从缓存获取，最多200张）
     */
    suspend fun getWallpaperItems(category: String): List<WpItem> {
        totalLoads++
        return withContext(Dispatchers.IO) {
            val categoryName = if (category.endsWith("_two.json")) {
                category.replace("_two.json", "")
            } else {
                category
            }

            // 先从缓存获取
            synchronized(wallpaperItemCache) {
                val cachedItems = wallpaperItemCache.get(categoryName)
                if (cachedItems != null) {
                    cacheHits++
                    Log.d("MyApplication", "缓存命中: [$categoryName] 数量: ${cachedItems.size}")
                    return@withContext cachedItems
                }
            }

            // 缓存中没有，则获取数据并转换
            val wallpapers = getWallpaperData(category)
            val wallpaperItems = wallpapers.map { wallpaperJson ->
                Utils_json.convertToWallpaperItem(wallpaperJson)
            }

            // 更新缓存
            if (wallpaperItems.isNotEmpty()) {
                synchronized(wallpaperItemCache) {
                    wallpaperItemCache.put(categoryName, wallpaperItems)
                }
            }

            return@withContext wallpaperItems
        }
    }
    /**
     * 配置图片加载库
     */
    private fun configureImageLoader() {
        try {
            val requestOptions = RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .timeout(10000)
                .skipMemoryCache(true)

            Log.d("MyApplication", "✅ 图片加载库配置完成")

        } catch (e: Exception) {
            Log.e("MyApplication", "❌ 图片加载库配置失败: ${e.message}", e)
        }
    }

    /**
     * 初始化应用生命周期监听
     */
    private fun initAppLifecycleObserver() {
        try {
            ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
            Log.d("MyApplication", "✅ 应用生命周期监听已初始化")

        } catch (e: Exception) {
            Log.e("MyApplication", "❌ 应用生命周期监听初始化失败: ${e.message}", e)
        }
    }

    /**
     * 初始化全局设置
     */
    private fun initGlobalSettings() {
        applicationScope.launch {
            try {
                initDefaultPreferences()

                if (appConfig.enableAutoCleanup) {
                    cleanTempFiles()
                }

                Log.d("MyApplication", "✅ 全局设置初始化完成")

            } catch (e: Exception) {
                Log.e("MyApplication", "❌ 全局设置初始化失败: ${e.message}", e)
            }
        }
    }

    /**
     * 初始化默认的首选项设置
     */
    private fun initDefaultPreferences() {
        val sharedPrefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

        val isFirstLaunch = !sharedPrefs.contains(KEY_FIRST_LAUNCH) ||
                sharedPrefs.getBoolean(KEY_FIRST_LAUNCH, true)

        if (isFirstLaunch) {
            Log.d("MyApplication", "🎉 首次启动应用")
        }

        with(sharedPrefs.edit()) {
            if (!sharedPrefs.contains(KEY_FIRST_LAUNCH)) {
                putBoolean(KEY_FIRST_LAUNCH, true)
            }
            if (!sharedPrefs.contains(KEY_DEFAULT_CATEGORY)) {
                putString(KEY_DEFAULT_CATEGORY, "Film")
            }
            if (!sharedPrefs.contains(KEY_IMAGE_QUALITY)) {
                putString(KEY_IMAGE_QUALITY, "balanced")
            }
            if (!sharedPrefs.contains(KEY_LAST_CLEANUP)) {
                putLong(KEY_LAST_CLEANUP, System.currentTimeMillis())
            }
            apply()
        }

        Log.d("MyApplication", "✅ 默认首选项设置完成")

        if (isFirstLaunch) {
            sharedPrefs.edit().putBoolean(KEY_FIRST_LAUNCH, false).apply()
            Log.d("MyApplication", "已将首次启动标记设置为 false")
        }
    }

    /**
     * 清理临时文件
     */
    private fun cleanTempFiles() {
        try {
            val sharedPrefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val lastCleanupTime = sharedPrefs.getLong(KEY_LAST_CLEANUP, 0)
            val currentTime = System.currentTimeMillis()

            if (currentTime - lastCleanupTime > 7 * 24 * 60 * 60 * 1000L) {
                applicationScope.launch {
                    Glide.get(this@MyApplication).clearDiskCache()

                    val snapshot = wallpaperItemCache.snapshot()
                    val keys = snapshot.keys.toList()

                    if (keys.size > MAX_CACHE_CATEGORIES) {
                        for (i in 0 until keys.size - MAX_CACHE_CATEGORIES) {
                            wallpaperItemCache.remove(keys[i])
                            wallpaperCache.remove(keys[i])
                        }
                    }

                    sharedPrefs.edit().putLong(KEY_LAST_CLEANUP, currentTime).apply()
                    Log.d("MyApplication", "✅ 临时文件清理完成")
                }
            }

        } catch (e: Exception) {
            Log.w("MyApplication", "清理临时文件时出错: ${e.message}")
        }
    }

    /**
     * 应用生命周期观察者
     */
    inner class AppLifecycleObserver : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppForegrounded() {
            Log.d("MyApplication", "📱 应用进入前台")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppBackgrounded() {
            Log.d("MyApplication", "📱 应用进入后台")
            // 进入后台时，清理Glide内存缓存
            Glide.get(this@MyApplication).clearMemory()
            System.gc()
        }
    }

    /**
     * 当系统内存不足时调用
     */
    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)

        Log.d("MyApplication", "🔄 内存紧张，级别: $level")

        when (level) {
            ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE,
            ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW,
            ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> {
                // 清理Glide内存缓存
                Glide.get(this).clearMemory()

                // 清理应用缓存
                synchronized(wallpaperCache) {
                    wallpaperCache.trimToSize(0)
                }
                synchronized(wallpaperItemCache) {
                    wallpaperItemCache.trimToSize(0)
                }

                // 强制垃圾回收
                System.gc()
                System.runFinalization()

                Log.d("MyApplication", "清理了所有缓存")
            }
            ComponentCallbacks2.TRIM_MEMORY_BACKGROUND,
            ComponentCallbacks2.TRIM_MEMORY_MODERATE,
            ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> {
                // 清理所有资源
                synchronized(wallpaperCache) {
                    wallpaperCache.evictAll()
                }
                synchronized(wallpaperItemCache) {
                    wallpaperItemCache.evictAll()
                }
                Glide.get(this).clearMemory()

                Log.d("MyApplication", "应用在后台，清理了所有资源")
            }
        }
    }

    /**
     * 当应用终止时调用
     */
    override fun onTerminate() {
        // 清理资源
        synchronized(wallpaperCache) {
            wallpaperCache.evictAll()
        }
        synchronized(wallpaperItemCache) {
            wallpaperItemCache.evictAll()
        }

        // 取消所有协程
        applicationScope.coroutineContext.cancelChildren()

        instance = null
        super.onTerminate()
        Log.d("MyApplication", "🛑 应用终止")
    }
}