package com.remax.bill.ads.pangle

import android.content.Context
import android.view.ViewGroup
import com.bytedance.sdk.openadsdk.api.model.PAGErrorModel
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAd
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdInteractionCallback
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeRequest
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdLoadCallback
import com.bytedance.sdk.openadsdk.api.model.PAGAdEcpmInfo
import com.bytedance.sdk.openadsdk.api.model.PAGRevenueInfo
import com.remax.bill.BuildConfig
import com.remax.bill.ads.AdException
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.config.AdConfigManager
import com.remax.bill.ads.interceptor.ClickLimitInterceptor
import com.remax.bill.ads.interceptor.GlobalAdSwitchInterceptor
import com.remax.bill.ads.interceptor.InterceptorChain
import com.remax.bill.ads.interceptor.ShowCountLimitInterceptor
import com.remax.bill.ads.interceptor.ShowIntervalLimitInterceptor
import com.remax.bill.ads.log.AdLogger
import com.remax.base.ads.AdRevenueData
import com.remax.base.ads.AdRevenueManager
import com.remax.base.ads.RevenueInfo
import com.remax.base.ext.KvIntDelegate
import com.remax.base.report.DataReportManager
import com.remax.bill.ads.util.PositionGet
import com.remax.bill.ui.pangle.PangleNativeAdStyle
import com.remax.bill.ui.pangle.PangleNativeAdView
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.math.ceil
import kotlin.math.roundToLong

/**
 * Pangle原生广告控制器
 * 提供原生广告的加载和管理功能
 * 参考文档: https://www.pangleglobal.com/integration/android-native-ads
 * 
 * 注意：Pangle原生广告支持四种格式：
 * - 大图（1.91:1比例）
 * - 1280*720视频
 * - 方形图片
 * - 方形视频
 */
class PangleNativeAdController private constructor() {
    
    // 累积点击统计（持久化）
    private var totalClickCount by KvIntDelegate("pangle_native_ad_total_clicks", 0)

    // 累积关闭统计（持久化）
    private var totalCloseCount by KvIntDelegate("pangle_native_ad_total_close", 0)
    
    // 累积加载次数统计（持久化）
    private var totalLoadCount by KvIntDelegate("pangle_native_ad_total_loads", 0)

    // 累积加载成功次数统计（持久化）
    private var totalLoadSucCount by KvIntDelegate("pangle_native_ad_total_load_suc", 0)
    
    // 累积展示失败次数统计（持久化）
    private var totalShowFailCount by KvIntDelegate("pangle_native_ad_total_show_fails", 0)
    
    // 累积触发统计（持久化）
    private var totalShowTriggerCount by KvIntDelegate("pangle_native_ad_total_show_triggers", 0)
    
    // 累积展示统计（持久化）
    private var totalShowCount by KvIntDelegate("pangle_native_ad_total_shows", 0)
    
    companion object {
        private const val TAG = "PangleNativeAdController"
        private const val AD_TIMEOUT = 1 * 60 * 60 * 1000L // 1小时过期
        private const val DEFAULT_CACHE_SIZE_PER_AD_UNIT = 1
        
        @Volatile
        private var INSTANCE: PangleNativeAdController? = null
        
        fun getInstance(): PangleNativeAdController {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: PangleNativeAdController().also { INSTANCE = it }
            }
        }
    }
    
    // 内存缓存池 - 存储预加载的广告
    private val adCachePool = mutableListOf<CachedNativeAd>()
    private val maxCacheSizePerAdUnit = DEFAULT_CACHE_SIZE_PER_AD_UNIT
    
    // 拦截器链
    private val interceptorChain = InterceptorChain(
        interceptors = listOf(
            GlobalAdSwitchInterceptor(),
            ShowCountLimitInterceptor(),
            ShowIntervalLimitInterceptor(),
            ClickLimitInterceptor()
        )
    )
    
    private val nativeAdView = PangleNativeAdView()
    
    /**
     * 缓存的原生广告数据类
     */
    private data class CachedNativeAd(
        val ad: PAGNativeAd,
        val adUnitId: String,
        val loadTime: Long = System.currentTimeMillis()
    ) {
        fun isExpired(): Boolean {
            return System.currentTimeMillis() - loadTime > AD_TIMEOUT
        }
    }
    
    /**
     * 预加载原生广告（可选，用于提前准备）
     * @param context 上下文
     * @param adUnitId 广告位ID，如果为空则使用默认ID
     */
    suspend fun preloadAd(context: Context, adUnitId: String? = null): AdResult<Unit> {
        if(!GlobalAdSwitchInterceptor.isGlobalAdEnabled()){
            return AdResult.Failure(
                AdException(
                    code = -100,
                    message = "原生广告全局开关已关闭，中断加载"
                ))
        }
        val finalAdUnitId = adUnitId ?: BuildConfig.PANGLE_NATIVE_ID
        return loadAdToCache(context, finalAdUnitId)
    }
    
    /**
     * 获取原生广告（自动处理加载）
     * @param context 上下文
     * @param adUnitId 广告位ID，如果为空则使用默认ID
     */
    suspend fun getAd(context: Context, adUnitId: String? = null): AdResult<PAGNativeAd> {
        val finalAdUnitId = adUnitId ?: BuildConfig.PANGLE_NATIVE_ID
        
        // 1. 尝试从缓存获取广告
        var cachedAd = getCachedAd(finalAdUnitId)
        
        // 2. 如果缓存为空，立即加载并缓存一个广告
        if (cachedAd == null) {
            AdLogger.d("缓存为空，立即加载Pangle原生广告，广告位ID: %s", finalAdUnitId)
            loadAdToCache(context, finalAdUnitId)
            cachedAd = getCachedAd(finalAdUnitId)
        }
        
        return if (cachedAd != null) {
            AdLogger.d("使用缓存中的Pangle原生广告，广告位ID: %s", finalAdUnitId)
            AdResult.Success(cachedAd.ad)
        } else {
            AdResult.Failure(createAdException("load ad fail"))
        }
    }
    
    /**
     * 显示原生广告到指定容器（简化版接口）
     * @param context 上下文
     * @param container 目标容器（根视图）
     * @param style 广告样式，默认为标准样式
     * @param adUnitId 广告位ID，如果为空则使用默认ID
     * @return 是否显示成功
     */
    suspend fun showAdInContainer(
        context: Context,
        container: ViewGroup,
        style: PangleNativeAdStyle = PangleNativeAdStyle.STANDARD,
        adUnitId: String? = null
    ): Boolean {
        val finalAdUnitId = adUnitId ?: BuildConfig.PANGLE_NATIVE_ID
        
        // 累积触发统计
        totalShowTriggerCount++
        AdLogger.d("Pangle原生广告累积触发展示次数: $totalShowTriggerCount")
        
        reportAdData(
            eventName = "ad_position",
            params = mapOf(
                "ad_unit_name" to finalAdUnitId,
                "position" to PositionGet.get(),
                "number" to totalShowTriggerCount
            )
        )
        
        // 拦截器检查
        when (val interceptResult = interceptorChain.intercept(context, AdConfigManager.getNativeConfig())) {
            is AdResult.Failure -> {
                // 累积展示失败次数统计
                totalShowFailCount++
                AdLogger.d("Pangle原生广告累积展示失败次数: $totalShowFailCount")
                
                reportAdData(
                    eventName = "ad_show_fail",
                    params = mapOf(
                        "ad_unit_name" to finalAdUnitId,
                        "position" to PositionGet.get(),
                        "number" to totalShowFailCount,
                        "reason" to interceptResult.error.message
                    )
                )
                
                AdLogger.w("Pangle原生广告拦截器检查失败: %s", interceptResult.error.message)
                return false
            }
            else -> { /* continue */ }
        }
        
        return try {
            when (val result = getAd(context, adUnitId)) {
                is AdResult.Success -> {
                    val nativeAd = result.data

                    if(!nativeAd.isReady){
                        throw IllegalArgumentException("native_not_ready")
                    }
                    var currentRevenueUsd: Double? = null
                    var currentCurrency: String? = null
                    var currentAdSource: String? = null
                    var impressionPlacement: String? = null
                    var impressionRevenueAdUnit: String? = null

                    // 使用PangleNativeAdView绑定广告到容器，内部会处理 registerViewForInteraction
                    val success = nativeAdView.bindNativeAdToContainer(
                        context = context,
                        container = container,
                        nativeAd = nativeAd,
                        style = style,
                        interactionListener = object : PAGNativeAdInteractionCallback() {
                            override fun onAdShowed() {
                                AdLogger.d("Pangle原生广告开始显示")
                                val pagRevenueInfo: PAGRevenueInfo? = nativeAd.pagRevenueInfo
                                val ecpmInfo: PAGAdEcpmInfo? = pagRevenueInfo?.showEcpm
                                currentCurrency = ecpmInfo?.currency
                                currentAdSource = ecpmInfo?.adnName
                                impressionPlacement = ecpmInfo?.placement
                                impressionRevenueAdUnit = ecpmInfo?.adUnit
                                // Pangle 的 revenue 本身就是美元，直接使用
                                val revenueUsd = ecpmInfo?.revenue?.toDoubleOrNull() ?: 0.0
                                currentRevenueUsd = revenueUsd
                                val impressionValue = revenueUsd

                                totalShowCount++
                                AdLogger.d("Pangle原生广告累积展示次数: $totalShowCount")
                                AdConfigManager.getNativeConfig().recordShow()

                                reportAdData(
                                    eventName = "ad_impression",
                                    params = mapOf(
                                        "ad_unit_name" to finalAdUnitId,
                                        "position" to PositionGet.get(),
                                        "number" to totalShowCount,
                                        "ad_source" to (currentAdSource ?: "Pangle"),
                                        "value" to impressionValue,
                                        "currency" to (currentCurrency ?: "USD")
                                    )
                                )

                                currentRevenueUsd?.let { revenueValue ->
                                    reportAdRevenueWithValue(
                                        adUnitId = finalAdUnitId,
                                        valueUsd = revenueValue,
                                        currencyCode = currentCurrency,
                                        adNetwork = currentAdSource,
                                        placement = impressionPlacement,
                                        ecpmAdUnitId = impressionRevenueAdUnit
                                    )
                                    // Pangle 的 revenue 本身就是美元，直接使用
                                    val revenueUsd = ecpmInfo?.revenue?.toDoubleOrNull()?.toLong() ?: 0L
                                    AdLogger.d(
                                        "Pangle原生广告收益上报(onShow): adUnit=%s, placement=%s, adn=%s, revenueUsd=%.4f, currency=%s",
                                        impressionRevenueAdUnit ?: finalAdUnitId,
                                        impressionPlacement ?: "",
                                        currentAdSource ?: "Pangle",
                                        revenueValue,
                                        currentCurrency ?: ""
                                    )
                                }
                            }

                            override fun onAdClicked() {
                                AdLogger.d("Pangle原生广告被点击")
                                totalClickCount++
                                AdLogger.d("Pangle原生广告累积点击次数: $totalClickCount")
                                AdConfigManager.getNativeConfig().recordClick()

                                reportAdData(
                                    eventName = "ad_click",
                                    params = mapOf(
                                        "ad_unit_name" to finalAdUnitId,
                                        "position" to PositionGet.get(),
                                        "number" to totalClickCount,
                                        "ad_source" to (currentAdSource ?: "Pangle"),
                                        "value" to (nativeAd.pagRevenueInfo?.showEcpm?.revenue?.toDoubleOrNull() ?: 0.0),
                                        "currency" to (currentCurrency ?: "USD")
                                    )
                                )
                            }

                            override fun onAdDismissed() {
                                AdLogger.d("Pangle原生广告关闭")
                                totalCloseCount++
                                reportAdData(
                                    eventName = "ad_close",
                                    params = mapOf(
                                        "ad_unit_name" to finalAdUnitId,
                                        "position" to PositionGet.get(),
                                        "number" to totalCloseCount,
                                        "ad_source" to (currentAdSource ?: "Pangle"),
                                        "value" to (nativeAd.pagRevenueInfo?.showEcpm?.revenue?.toDoubleOrNull() ?: 0.0),
                                        "currency" to (currentCurrency ?: "USD")
                                    )
                                )
                            }

                            override fun onAdShowFailed(error: PAGErrorModel) {
                                super.onAdShowFailed(error)
                                totalShowFailCount++
                                AdLogger.e(
                                    "Pangle原生广告显示失败: code=%d, message=%s",
                                    error.errorCode,
                                    error.errorMessage
                                )
                                reportAdData(
                                    eventName = "ad_show_fail",
                                    params = mapOf(
                                        "ad_unit_name" to finalAdUnitId,
                                        "position" to PositionGet.get(),
                                        "number" to totalShowFailCount,
                                        "reason" to error.errorMessage.orEmpty(),
                                        "ad_source" to (currentAdSource ?: "Pangle")
                                    )
                                )
                            }
                        }
                    )
                    
                    if (success) {
                        true
                    } else {
                        totalShowFailCount++
                        AdLogger.d("Pangle原生广告累积展示失败次数: $totalShowFailCount")
                        reportAdData(
                            eventName = "ad_show_fail",
                            params = mapOf(
                                "ad_unit_name" to finalAdUnitId,
                                "position" to PositionGet.get(),
                                "number" to totalShowFailCount,
                                "reason" to "bind_failed"
                            )
                        )
                        false
                    }
                }
                is AdResult.Failure -> {
                    // 累积展示失败次数统计
                    totalShowFailCount++
                    AdLogger.d("Pangle原生广告累积展示失败次数: $totalShowFailCount")
                    
                    reportAdData(
                        eventName = "ad_show_fail",
                        params = mapOf(
                            "ad_unit_name" to finalAdUnitId,
                            "position" to PositionGet.get(),
                            "number" to totalShowFailCount,
                            "reason" to result.error.message
                        )
                    )
                    false
                }
                AdResult.Loading -> {
                    // 保持加载状态
                    false
                }
            }
        } catch (e: Exception) {
            // 累积展示失败次数统计
            totalShowFailCount++
            AdLogger.d("Pangle原生广告累积展示失败次数: $totalShowFailCount")
            
            reportAdData(
                eventName = "ad_show_fail",
                params = mapOf(
                    "ad_unit_name" to finalAdUnitId,
                    "position" to PositionGet.get(),
                    "number" to totalShowFailCount,
                    "reason" to "${e.message}"
                )
            )
            
            AdLogger.e("显示Pangle原生广告失败", e)
            false
        }
    }
    
    /**
     * 基础广告加载方法
     */
    @Suppress("UNUSED_PARAMETER")
    private suspend fun loadAd(context: Context, adUnitId: String): PAGNativeAd? {
        // 累积加载次数统计
        totalLoadCount++
        AdLogger.d("Pangle原生广告累积加载次数: $totalLoadCount")
        
        reportAdData(
            eventName = "ad_start_load",
            params = mapOf(
                "ad_unit_name" to adUnitId,
                "number" to totalLoadCount
            )
        )
        
        return suspendCancellableCoroutine { continuation ->
            val startTime = System.currentTimeMillis()
            
            // 创建PAGNativeRequest对象（推荐作为Activity的成员变量）
            val request = PAGNativeRequest(context)
            
            // 加载广告并注册回调
            PAGNativeAd.loadAd(adUnitId, request, object : PAGNativeAdLoadCallback {
                override fun onAdLoaded(ad: PAGNativeAd) {
                    val loadTime = System.currentTimeMillis() - startTime
                    AdLogger.d("Pangle原生广告加载成功，广告位ID: %s, 耗时: %dms", adUnitId, loadTime)
                    totalLoadSucCount++
                    
                    reportAdData(
                        eventName = "ad_loaded",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "number" to totalLoadSucCount,
                            "ad_source" to "Pangle",
                            "pass_time" to ceil(loadTime / 1000.0).toInt()
                        )
                    )

                    continuation.resume(ad)
                }

                override fun onError(model :PAGErrorModel) {
                    val code = model.errorCode
                    val message = model.errorMessage
                    val loadTime = System.currentTimeMillis() - startTime
                    AdLogger.e("Pangle原生广告加载失败，广告位ID: %s, 耗时: %dms, 错误码: %d, 错误信息: %s", 
                        adUnitId, loadTime, code, message)
                    
                    reportAdData(
                        eventName = "ad_load_fail",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "number" to totalLoadSucCount,
                            "ad_source" to "Pangle",
                            "pass_time" to ceil(loadTime / 1000.0).toInt(),
                            "reason" to message
                        )
                    )
                    
                    continuation.resume(null)
                }
            })
        }
    }
    
    /**
     * 加载广告到缓存
     */
    private suspend fun loadAdToCache(context: Context, adUnitId: String): AdResult<Unit> {
        return try {
            // 检查缓存是否已满
            val currentAdUnitCount = getCachedAdCount(adUnitId)
            if (currentAdUnitCount >= maxCacheSizePerAdUnit) {
                AdLogger.w("广告位 %s 缓存已满，当前缓存: %d/%d", adUnitId, currentAdUnitCount, maxCacheSizePerAdUnit)
                return AdResult.Success(Unit)
            }
            
            // 加载广告
            val nativeAd = loadAd(context, adUnitId)
            if (nativeAd != null) {
                synchronized(adCachePool) {
                    adCachePool.add(CachedNativeAd(nativeAd, adUnitId))
                    val currentCount = getCachedAdCount(adUnitId)
                    AdLogger.d("Pangle原生广告加载成功并缓存，广告位ID: %s，该广告位缓存数量: %d/%d", adUnitId, currentCount, maxCacheSizePerAdUnit)
                }
                AdResult.Success(Unit)
            } else {
                AdResult.Failure(createAdException("广告加载失败"))
            }
        } catch (e: Exception) {
            AdLogger.e("Pangle原生loadAdToCache异常", e)
            AdResult.Failure(AdException(0, "加载异常: ${e.message}", e))
        }
    }
    
    /**
     * 从缓存获取广告
     */
    private fun getCachedAd(adUnitId: String): CachedNativeAd? {
        synchronized(adCachePool) {
            val index = adCachePool.indexOfFirst { it.adUnitId == adUnitId && !it.isExpired() }
            return if (index != -1) {
                adCachePool.removeAt(index)
            } else {
                null
            }
        }
    }

    private fun peekCachedAd(adUnitId: String): PAGNativeAd? {
        synchronized(adCachePool) {
            return adCachePool.firstOrNull { it.adUnitId == adUnitId && !it.isExpired() }?.ad
        }
    }
    
    /**
     * 获取指定广告位的缓存数量
     */
    private fun getCachedAdCount(adUnitId: String): Int {
        synchronized(adCachePool) {
            return adCachePool.count { it.adUnitId == adUnitId && !it.isExpired() }
        }
    }
    
    /**
     * 检查指定广告位缓存是否已满
     */
    private fun isCacheFull(adUnitId: String): Boolean {
        return getCachedAdCount(adUnitId) >= maxCacheSizePerAdUnit
    }
    
    /**
     * 获取当前加载的广告数据
     */
    fun getCurrentAd(adUnitId: String? = null): PAGNativeAd? {
        val finalAdUnitId = adUnitId ?: BuildConfig.PANGLE_NATIVE_ID
        return peekCachedAd(finalAdUnitId)
    }
    
    /**
     * 检查是否有可用的广告
     */
    fun isAdLoaded(adUnitId: String? = null): Boolean {
        val finalAdUnitId = adUnitId ?: BuildConfig.PANGLE_NATIVE_ID
        return getCachedAdCount(finalAdUnitId) > 0
    }
    
    /**
     * 销毁广告
     */
    fun destroyAd() {
        synchronized(adCachePool) {
            // PAGNativeAd没有destroy方法，只需要清理缓存
            adCachePool.clear()
        }
        AdLogger.d("Pangle原生广告已销毁")
    }
    
    /**
     * 清理资源
     */
    fun destroy() {
        destroyAd()
        AdLogger.d("Pangle原生广告控制器已清理")
    }
    
    /**
     * 创建广告异常
     */
    private fun createAdException(message: String, cause: Throwable? = null): AdException {
        return AdException(
            code = 0,
            message = message,
            cause = cause
        )
    }
    
    /**
     * 通用数据上报函数
     * @param eventName 事件名称
     * @param params 参数Map，会与基础参数合并
     */
    private fun reportAdData(eventName: String, params: Map<String, Any>) {
        val data = mutableMapOf<String, Any>(
            "ad_platform" to "Pangle",
            "ad_format" to "Native"
        )
        
        // 直接合并传入的参数
        data.putAll(params)

        if(eventName == "ad_impression"){
            DataReportManager.reportDataByName("ThinkingData", eventName, data)
        } else{
            DataReportManager.reportData(eventName, data)
        }
    }

    private fun reportAdRevenueWithValue(
        adUnitId: String,
        valueUsd: Double,
        currencyCode: String?,
        adNetwork: String?,
        placement: String?,
        ecpmAdUnitId: String?
    ) {
        val adRevenueData = AdRevenueData(
            revenue = RevenueInfo(
                value = valueUsd,
                currencyCode = currencyCode ?: ""
            ),
            adRevenueNetwork = adNetwork ?: "Pangle",
            adRevenueUnit = ecpmAdUnitId ?: adUnitId,
            adRevenuePlacement = placement ?: "",
            adFormat = "Native"
        )

        AdRevenueManager.reportAdRevenue(adRevenueData)
        AdLogger.d(
            "Pangle原生广告真实收益数据已上报，广告位ID: %s, 收益: %.4f %s, adn=%s, placement=%s",
            ecpmAdUnitId ?: adUnitId,
            valueUsd,
            currencyCode ?: "",
            adNetwork ?: "Pangle",
            placement ?: ""
        )
    }
}

