package com.simplecleaner.app.business.ads.admob

import com.google.android.gms.ads.nativead.NativeAd
import com.simplecleaner.app.utils.LogEx
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.atomic.AtomicLong

/**
 * 原生广告缓存管理器
 */
class NativeAdCache {
    
    private val TAG = "NativeAdCache"
    
    // 缓存队列
    private val cacheQueue = ConcurrentLinkedDeque<NativeAd>()
    
    // 最后缓存时间
    private val lastCacheTime = AtomicLong(0L)
    
    // 缓存统计
    private var totalCached = 0L
    private var totalExpired = 0L
    
    /**
     * 添加广告到缓存
     */
    fun addToCache(nativeAd: NativeAd): Boolean {
        return try {
            if (cacheQueue.size >= NativeAdConfig.Cache.MAX_CACHE_SIZE) {
                // 缓存已满，移除最旧的广告
                val oldestAd = cacheQueue.pollFirst()
                oldestAd?.destroy()
                LogEx.logDebug(TAG, "Cache full, removed oldest ad")
            }
            
            cacheQueue.offerLast(nativeAd)
            lastCacheTime.set(System.currentTimeMillis())
            totalCached++
            
            LogEx.logDebug(TAG, "Ad added to cache, size: ${cacheQueue.size}")
            true
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Failed to add ad to cache: ${e.message}")
            false
        }
    }
    
    /**
     * 从缓存获取广告
     */
    fun getFromCache(): NativeAd? {
        return try {
            if (isCacheExpired()) {
                clearCache()
                return null
            }
            
            val nativeAd = cacheQueue.pollFirst()
            if (nativeAd != null) {
                LogEx.logDebug(TAG, "Ad retrieved from cache, remaining: ${cacheQueue.size}")
            }
            nativeAd
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Failed to get ad from cache: ${e.message}")
            null
        }
    }
    
    /**
     * 检查缓存是否过期
     */
    fun isCacheExpired(): Boolean {
        val lastTime = lastCacheTime.get()
        if (lastTime == 0L) return false
        
        val elapsedMinutes = (System.currentTimeMillis() - lastTime) / (1000 * 60)
        return elapsedMinutes >= NativeAdConfig.Cache.CACHE_EXPIRE_MINUTES
    }
    
    /**
     * 清空缓存
     */
    fun clearCache() {
        try {
            val size = cacheQueue.size
            cacheQueue.forEach { it.destroy() }
            cacheQueue.clear()
            totalExpired += size
            lastCacheTime.set(0L)
            
            LogEx.logDebug(TAG, "Cache cleared, destroyed $size ads")
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Failed to clear cache: ${e.message}")
        }
    }
    
    /**
     * 获取缓存大小
     */
    fun getCacheSize(): Int = cacheQueue.size
    
    /**
     * 检查是否有可用广告
     */
    fun hasAvailableAd(): Boolean {
        return cacheQueue.isNotEmpty() && !isCacheExpired()
    }
    
    /**
     * 获取缓存统计信息
     */
    fun getCacheStats(): CacheStats {
        return CacheStats(
            currentSize = cacheQueue.size,
            totalCached = totalCached,
            totalExpired = totalExpired,
            lastCacheTime = lastCacheTime.get()
        )
    }
    
    /**
     * 缓存统计信息
     */
    data class CacheStats(
        val currentSize: Int,
        val totalCached: Long,
        val totalExpired: Long,
        val lastCacheTime: Long
    )
} 