package com.remax.bill.ads.pangle

import android.app.Activity
import android.content.Context
import com.bytedance.sdk.openadsdk.api.model.PAGAdEcpmInfo
import com.bytedance.sdk.openadsdk.api.model.PAGErrorModel
import com.bytedance.sdk.openadsdk.api.model.PAGRevenueInfo
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAd
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAdInteractionCallback
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAdLoadCallback
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenRequest
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 kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.math.ceil
import kotlin.math.roundToLong

/**
 * Pangle开屏广告控制器
 * 专门处理开屏广告的加载和显示
 * 参考文档: https://www.pangleglobal.com/integration/android-App-Open-Ads
 * 
 * 预加载说明：
 * - Pangle SDK会在广告显示或关闭后自动开始新的广告请求（自动预加载后续广告）
 * - 但第一次显示时，如果没有预加载，可能需要等待加载时间
 * - 建议在应用启动时调用preloadAd()预加载第一个广告，以提升首次显示体验
 * - 后续广告由SDK自动处理，无需手动预加载
 */
class PangleAppOpenAdController private constructor() {
    
    // 累积点击统计（持久化）
    private var totalClickCount by KvIntDelegate("pangle_app_open_ad_total_clicks", 0)

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

    // 累积加载成功次数统计（持久化）
    private var totalLoadSucCount by KvIntDelegate("pangle_app_open_ad_total_load_suc", 0)
    
    // 累积展示失败次数统计（持久化）
    private var totalShowFailCount by KvIntDelegate("pangle_app_open_ad_total_show_fails", 0)
    
    // 累积触发统计（持久化）
    private var totalShowTriggerCount by KvIntDelegate("pangle_app_open_ad_total_show_triggers", 0)
    
    // 累积展示统计（持久化）
    private var totalShowCount by KvIntDelegate("pangle_app_open_ad_total_shows", 0)
    
    companion object {
        private const val TAG = "PangleAppOpenAdController"
        private const val LOAD_TIMEOUT = 7000L // 加载超时时间7秒
        
        @Volatile
        private var INSTANCE: PangleAppOpenAdController? = null
        
        fun getInstance(): PangleAppOpenAdController {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: PangleAppOpenAdController().also { INSTANCE = it }
            }
        }
    }
    
    // 当前加载的广告请求（推荐作为Activity的成员变量）
    private var currentAppOpenRequest: PAGAppOpenRequest? = null
    
    // 当前加载的广告对象
    private var currentAppOpenAd: PAGAppOpenAd? = null
    
    // 拦截器链
    private val interceptorChain = InterceptorChain(
        interceptors = listOf(
            GlobalAdSwitchInterceptor(),
            ShowCountLimitInterceptor(),
            ShowIntervalLimitInterceptor(),
            ClickLimitInterceptor()
        )
    )
    
    /**
     * 预加载开屏广告
     * 建议在应用启动时调用此方法预加载第一个广告，以提升首次显示体验
     * 注意：后续广告由Pangle SDK自动预加载，无需手动调用
     * 
     * @param context 上下文
     * @param adUnitId 广告位ID
     */
    suspend fun preloadAd(context: Context, adUnitId: String): AdResult<Unit> {
        if(!GlobalAdSwitchInterceptor.isGlobalAdEnabled()){
            return AdResult.Failure(
                AdException(
                    code = -100,
                    message = "开屏全局广告已关闭，中断加载"
                ))
        }
        return loadAd(context, adUnitId)
    }

    fun hasCachedAd(): Boolean {
        return currentAppOpenAd != null
    }

    fun getCurrentAd(): PAGAppOpenAd? = currentAppOpenAd

    /**
     * 基础广告加载方法
     */
    @Suppress("UNUSED_PARAMETER")
    private suspend fun loadAd(context: Context, adUnitId: String): AdResult<Unit> {
        // 累积加载次数统计
        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()

            // 创建PAGAppOpenRequest对象（推荐作为Activity的成员变量）
            val request = PAGAppOpenRequest(context)
            request.setTimeout(LOAD_TIMEOUT.toInt()) // 设置加载超时时间
            
            currentAppOpenRequest = request
            
            // 加载广告并注册回调
            PAGAppOpenAd.loadAd(adUnitId, request, object : PAGAppOpenAdLoadCallback {
                override fun onAdLoaded(ad: PAGAppOpenAd) {
                    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()
                        )
                    )

                    currentAppOpenAd = ad
                    continuation.resume(AdResult.Success(Unit))
                }

                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
                        )
                    )
                    
                    currentAppOpenAd = null
                    continuation.resume(AdResult.Failure(
                        createAdException("广告加载失败: ${message} (code: ${code})")
                    ))
                }
            })
        }
    }
    
    /**
     * 显示开屏广告
     * @param activity Activity上下文
     * @param adUnitId 广告位ID
     * @param onLoaded 加载回调
     */
    suspend fun showAd(
        activity: Activity, 
        adUnitId: String,
        onLoaded: ((isSuc: Boolean) -> Unit)? = null
    ): AdResult<Unit> {
        // 累积触发广告展示次数统计
        totalShowTriggerCount++
        AdLogger.d("Pangle开屏广告累积触发展示次数: $totalShowTriggerCount")

        reportAdData(
            eventName = "ad_position",
            params = mapOf(
                "ad_unit_name" to adUnitId,
                "position" to PositionGet.get(),
                "number" to totalShowTriggerCount
            )
        )
        
        // 拦截器检查
        when (val interceptResult = interceptorChain.intercept(activity, AdConfigManager.getAppOpenConfig())) {
            is AdResult.Failure -> {
                // 累积展示失败次数统计
                totalShowFailCount++
                AdLogger.d("Pangle开屏广告累积展示失败次数: $totalShowFailCount")
                onLoaded?.invoke(false)
                reportAdData(
                    eventName = "ad_show_fail",
                    params = mapOf(
                        "ad_unit_name" to adUnitId,
                        "position" to PositionGet.get(),
                        "number" to totalShowFailCount,
                        "reason" to interceptResult.error.message,
                    )
                )
                return interceptResult
            }
            else -> { /* continue */ }
        }
        
        val adResult = try {
            // 如果当前没有加载的广告，先加载
            if (currentAppOpenAd == null) {
                AdLogger.d("当前没有广告，立即加载Pangle开屏广告，广告位ID: %s", adUnitId)
                val loadResult = loadAd(activity, adUnitId)
                if (loadResult is AdResult.Failure) {
                    onLoaded?.invoke(false)
                    return loadResult
                }
            }

            val ad = currentAppOpenAd
            if (ad != null) {
                AdLogger.d("显示Pangle开屏广告，广告位ID: %s", adUnitId)
                onLoaded?.invoke(true)

                // 显示广告
                val result = showAdInternal(activity, ad, adUnitId)
                
                // 清空当前广告，Pangle SDK会自动加载下一个
                currentAppOpenAd = null
                
                result
            } else {
                onLoaded?.invoke(false)
                AdResult.Failure(createAdException("广告加载失败"))
            }
        } catch (e: Exception) {
            AdLogger.e("显示Pangle开屏广告异常", e)
            AdResult.Failure(createAdException("显示广告异常: ${e.message}", e))
        }

        return adResult
    }
    
    /**
     * 显示广告的内部实现
     */
    private suspend fun showAdInternal(
        activity: Activity, 
        appOpenAd: PAGAppOpenAd, 
        adUnitId: String
    ): AdResult<Unit> {
        return suspendCancellableCoroutine { continuation ->
            // 临时变量保存收益数据
            var currentRevenueUsd: Double? = null
            var currentCurrency: String? = null
            var currentAdSource: String? = null
            var currentPlacement: String? = null
            var currentRevenueAdUnit: String? = null
 
            // 注册广告事件回调（需要在显示前注册）
            appOpenAd.setAdInteractionListener(object : PAGAppOpenAdInteractionCallback() {
                override fun onAdShowed() {
                    val pagRevenueInfo: PAGRevenueInfo? = appOpenAd.pagRevenueInfo
                    val ecpmInfo: PAGAdEcpmInfo? = pagRevenueInfo?.showEcpm
                    currentCurrency = ecpmInfo?.currency
                    currentAdSource = ecpmInfo?.adnName
                    currentPlacement = ecpmInfo?.placement
                    currentRevenueAdUnit = ecpmInfo?.adUnit
                    // Pangle 的 revenue 本身就是美元，直接使用
                    val revenueUsd = ecpmInfo?.revenue?.toDoubleOrNull() ?: 0.0
                    currentRevenueUsd = revenueUsd
                    AdLogger.d(
                        "Pangle开屏广告eCPM信息: revenue=%s, currency=%s, adn=%s, placement=%s, adUnit=%s",
                        ecpmInfo?.revenue?.toString() ?: "",
                        currentCurrency ?: "",
                        currentAdSource ?: "",
                        currentPlacement ?: "",
                        currentRevenueAdUnit ?: ""
                    )
                    val impressionValue = revenueUsd
 
                    AdLogger.d("Pangle开屏广告开始显示")
 
                    // 累积展示统计
                    totalShowCount++
                    AdLogger.d("Pangle开屏广告累积展示次数: $totalShowCount")
 
                    AdConfigManager.getAppOpenConfig().recordShow()
                    reportAdData(
                        eventName = "ad_impression",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "position" to PositionGet.get(),
                            "number" to totalShowCount,
                            "ad_source" to (currentAdSource ?: "Pangle"),
                            "value" to impressionValue,
                            "currency" to (currentCurrency ?: "USD")
                        )
                    )

                    currentRevenueUsd?.let { revenueValue ->
                        reportAdRevenueWithValue(
                            adUnitId = adUnitId,
                            valueUsd = revenueValue,
                            currencyCode = currentCurrency,
                            adNetwork = currentAdSource,
                            placement = currentPlacement,
                            ecpmAdUnitId = currentRevenueAdUnit
                        )
                        // Pangle 的 revenue 本身就是美元，直接使用
                        val revenueUsd = ecpmInfo?.revenue?.toDoubleOrNull()?.toLong() ?: 0L
                        AdLogger.d(
                            "Pangle开屏广告收益上报(onShow): adUnit=%s, placement=%s, adn=%s, revenueUsd=%.4f, currency=%s",
                            currentRevenueAdUnit ?: adUnitId,
                            currentPlacement ?: "",
                            currentAdSource ?: "Pangle",
                            revenueValue,
                            currentCurrency ?: ""
                        )
                    }
                }
 
                override fun onAdClicked() {
                    AdLogger.d("Pangle开屏广告被点击")
 
                    // 累积点击统计
                    totalClickCount++
                    AdLogger.d("Pangle开屏广告累积点击次数: $totalClickCount")
                    AdLogger.d(
                        "Pangle开屏广告点击时收益数据: %s",
                        if (currentRevenueUsd != null) {
                            "value=${currentRevenueUsd}, currency=${currentCurrency ?: ""}" }
                        else {
                            "暂无收益数据"
                        }
                    )
 
                    AdConfigManager.getAppOpenConfig().recordClick()
                    reportAdData(
                        eventName = "ad_click",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "position" to PositionGet.get(),
                            "number" to totalClickCount,
                            "ad_source" to (currentAdSource ?: "Pangle"),
                            "value" to (appOpenAd.pagRevenueInfo?.showEcpm?.revenue?.toDoubleOrNull() ?: 0.0),
                            "currency" to (currentCurrency ?: "USD")
                        )
                    )
                }
 
                override fun onAdDismissed() {
                    totalCloseCount++
                    AdLogger.d("Pangle开屏广告关闭")
                    reportAdData(
                        eventName = "ad_close",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "position" to PositionGet.get(),
                            "number" to totalCloseCount,
                            "ad_source" to (currentAdSource ?: "Pangle"),
                            "value" to (appOpenAd.pagRevenueInfo?.showEcpm?.revenue?.toDoubleOrNull() ?: 0.0),
                            "currency" to (currentCurrency ?: "USD")
                        )
                    )
 
                    val result = AdResult.Success(Unit)
                    if (continuation.isActive) {
                        continuation.resume(result)
                    }
                }
 
                override fun onAdShowFailed(pagErrorModel: PAGErrorModel) {
                    super.onAdShowFailed(pagErrorModel)
                    totalShowFailCount++
                    AdLogger.e(
                        "Pangle开屏广告显示失败: code=%d, message=%s",
                        pagErrorModel.errorCode,
                        pagErrorModel.errorMessage
                    )
                    reportAdData(
                        eventName = "ad_show_fail",
                        params = mapOf(
                            "ad_unit_name" to adUnitId,
                            "position" to PositionGet.get(),
                            "number" to totalShowFailCount,
                            "reason" to pagErrorModel.errorMessage.orEmpty(),
                            "ad_source" to (currentAdSource ?: "Pangle")
                        )
                    )
                }
            })
 
            // 显示广告（必须在主线程调用）
            if (!appOpenAd.isReady) {
                AdLogger.w("Pangle开屏广告未就绪，无法显示")
                totalShowFailCount++
                reportAdData(
                    eventName = "ad_show_fail",
                    params = mapOf(
                        "ad_unit_name" to adUnitId,
                        "position" to PositionGet.get(),
                        "number" to totalShowFailCount,
                        "reason" to "app_open_not_ready",
                        "ad_source" to (currentAdSource ?: "Pangle")
                    )
                )
                val result = AdResult.Failure(createAdException("广告未准备就绪"))
                if (continuation.isActive) {
                    continuation.resume(result)
                }
                return@suspendCancellableCoroutine
            }

            try {
                appOpenAd.show(activity)
            } catch (e: Exception) {
                AdLogger.e("显示Pangle开屏广告异常", e)
                totalShowFailCount++
                reportAdData(
                    eventName = "ad_show_fail",
                    params = mapOf(
                        "ad_unit_name" to adUnitId,
                        "position" to PositionGet.get(),
                        "number" to totalShowFailCount,
                        "reason" to e.message.orEmpty()
                    )
                )
                val result = AdResult.Failure(createAdException("显示失败: ${e.message}", e))
                if (continuation.isActive) {
                    continuation.resume(result)
                }
            }
        }
    }
 
    /**
     * 上报广告收益数据（使用真实收益值）
     * @param adUnitId 广告位ID
     * @param valueUsd 收益值（美元）
     * @param currencyCode 货币代码
     */
    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 = "Splash"
        )

        // 上报收益数据（内部已处理初始化和异常）
        AdRevenueManager.reportAdRevenue(adRevenueData)
        AdLogger.d(
            "Pangle开屏广告真实收益数据已上报，广告位ID: %s, 收益: %.4f %s, adn=%s, placement=%s",
            ecpmAdUnitId ?: adUnitId,
            valueUsd,
            currencyCode ?: "",
            adNetwork ?: "Pangle",
            placement ?: ""
        )
    }


    /**
     * 销毁广告
     */
    fun destroyAd() {
        currentAppOpenAd = null
        currentAppOpenRequest = null
        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 "Splash"
        )
        
        // 直接合并传入的参数
        data.putAll(params)

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