package com.remax.bill.ads.bidding

import android.app.Activity
import android.content.Context
import com.remax.base.report.DataReportManager
import com.remax.bill.BuildConfig
import com.remax.bill.ads.RewardedAdController
import com.remax.bill.ads.log.AdLogger
import com.remax.bill.ads.pangle.PangleRewardedAdController
import com.remax.bill.ads.topon.TopOnRewardedAdController
import com.remax.bill.ads.util.AdmobReflectionUtil
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import java.util.Locale

/**
 * 激励广告竞价控制器
 */
object RewardedBiddingManager {

    suspend fun bidding(
        context: Context,
        admobAdUnitId: String = BuildConfig.ADMOB_REWARDED_ID,
        pangleAdUnitId: String = BuildConfig.PANGLE_REWARDED_ID,
        toponPlacementId: String = BuildConfig.TOPON_REWARDED_ID,
    ): BiddingWinner {
        // 检查是否设置了固定的聚合源
        val source = AdSourceController.getCurrentSource()
        if (source != AdSourceController.AdSource.BIDDING) {
            // 如果设置了固定源，直接返回对应的 BiddingWinner
            return when (source) {
                AdSourceController.AdSource.ADMOB -> BiddingWinner.ADMOB
                AdSourceController.AdSource.PANGLE -> BiddingWinner.PANGLE
                AdSourceController.AdSource.TOPON -> BiddingWinner.TOPON
                AdSourceController.AdSource.BIDDING -> {
                    // 不会执行到这里，但为了完整性保留
                    performBidding(context, admobAdUnitId, pangleAdUnitId, toponPlacementId)
                }
            }
        }
        
        // 使用竞价逻辑
        return performBidding(context, admobAdUnitId, pangleAdUnitId, toponPlacementId)
    }

    private suspend fun performBidding(
        context: Context,
        admobAdUnitId: String,
        pangleAdUnitId: String,
        toponPlacementId: String,
    ): BiddingWinner {
        val context = context.applicationContext
        val admobController = RewardedAdController.getInstance()
        val pangleController = PangleRewardedAdController.getInstance()
        val toponController = TopOnRewardedAdController.getInstance()

        // 异步并行加载3个广告
        coroutineScope {
            val admobDeferred = async {
                runCatching {
                    admobController.loadAdToCache(context, admobAdUnitId)
                }.getOrNull()
            }
            val pangleDeferred = async {
                runCatching {
                    pangleController.preloadAd(context, pangleAdUnitId)
                }.getOrNull()
            }
            val toponDeferred = async {
                runCatching {
                    toponController.preloadAd(context, toponPlacementId)
                }.getOrNull()
            }
            // 等待所有加载完成
            admobDeferred.await()
            pangleDeferred.await()
            toponDeferred.await()
        }

        val admobRewardedAd = admobController.peekCachedAd(admobAdUnitId)
        val admobValueUsd = admobRewardedAd?.let { rewardedAd ->
            AdmobReflectionUtil.getRevenue(rewardedAd)?.valueMicros?.toDouble()?.div(1_000_000.0)
        } ?: 0.0

        val pangleRewardedAd = pangleController.getCurrentAd(pangleAdUnitId)
        val pangleValueUsd = pangleRewardedAd?.pagRevenueInfo?.winEcpm?.revenue?.toDoubleOrNull() ?: 0.0

        val toponRewardedAd = toponController.getCurrentAd(toponPlacementId)
        val toponValueUsd = toponRewardedAd?.let { ad ->
            runCatching {
                ad.checkValidAdCaches().firstOrNull()?.publisherRevenue
            }.getOrNull() ?: 0.0
        } ?: 0.0

        val biddingLog = String.format(
            Locale.US,
            "激励竞价结果 -> AdMob: %.8f 美元, Pangle: %.8f 美元, TopOn: %.8f 美元",
            admobValueUsd,
            pangleValueUsd,
            toponValueUsd
        )
        AdLogger.d(biddingLog)
//        ToastUtils.showLong(biddingLog)
        DataReportManager.reportDataByName("ThinkingData","bidding", mapOf("log" to biddingLog))

        val winner = when {
            admobValueUsd >= pangleValueUsd && admobValueUsd >= toponValueUsd -> BiddingWinner.ADMOB
            pangleValueUsd >= toponValueUsd -> BiddingWinner.PANGLE
            else -> BiddingWinner.TOPON
        }

        return winner
    }
}

