package com.remax.bill.ads.bidding

import android.app.Activity
import com.remax.base.report.DataReportManager
import com.remax.bill.BuildConfig
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.AppOpenAdController
import com.remax.bill.ads.log.AdLogger
import com.remax.bill.ads.pangle.PangleAppOpenAdController
import com.remax.bill.ads.topon.TopOnSplashAdController
import com.remax.bill.ads.util.AdmobReflectionUtil
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import java.util.Locale

/**
 * 开屏广告竞价控制器
 * 同时加载 AdMob、Pangle 和 TopOn，比较收益后选择展示
 */
object AppOpenBiddingManager {

    suspend fun bidding(
        activity: Activity,
        admobAdUnitId: String = BuildConfig.ADMOB_SPLASH_ID,
        pangleAdUnitId: String = BuildConfig.PANGLE_SPLASH_ID,
        toponPlacementId: String = BuildConfig.TOPON_SPLASH_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(activity, admobAdUnitId, pangleAdUnitId, toponPlacementId)
                }
            }
        }
        
        // 使用竞价逻辑
        return performBidding(activity, admobAdUnitId, pangleAdUnitId, toponPlacementId)
    }

    private suspend fun performBidding(
        activity: Activity,
        admobAdUnitId: String,
        pangleAdUnitId: String,
        toponPlacementId: String,
    ): BiddingWinner {
        val context = activity.applicationContext
        val admobController = AppOpenAdController.getInstance()
        val pangleController = PangleAppOpenAdController.getInstance()
        val toponController = TopOnSplashAdController.getInstance()
        
        // 根据平台配置决定是否参与比价
        val admobEnabled = BiddingPlatformController.isAdmobEnabled(BiddingPlatformController.AdType.APP_OPEN)
        val pangleEnabled = BiddingPlatformController.isPangleEnabled(BiddingPlatformController.AdType.APP_OPEN)
        val toponEnabled = BiddingPlatformController.isToponEnabled(BiddingPlatformController.AdType.APP_OPEN)

        // 异步并行加载启用的广告
        val (admobLoadResult, pangleLoadResult, toponLoadResult) = coroutineScope {
            val admobDeferred = async {
                if (admobEnabled) {
                    runCatching { admobController.preloadAd(context, admobAdUnitId) }.getOrNull()
                } else null
            }
            val pangleDeferred = async {
                if (pangleEnabled) {
                    runCatching { pangleController.preloadAd(context, pangleAdUnitId) }.getOrNull()
                } else null
            }
            val toponDeferred = async {
                if (toponEnabled) {
                    runCatching { toponController.preloadAd(context, toponPlacementId) }.getOrNull()
                } else null
            }
            Triple(admobDeferred.await(), pangleDeferred.await(), toponDeferred.await())
        }

        // 获取 AdMob 收益
        val admobValueUsd = if (admobEnabled && admobLoadResult is AdResult.Success<*>) {
            admobController.getCachedAdPeek(admobAdUnitId)?.ad?.let { ad ->
                AdmobReflectionUtil.getRevenue(ad)?.valueMicros?.toDouble()?.div(1_000_000.0)
            } ?: 0.0
        } else 0.0

        // 获取 Pangle 收益
        val pangleValueUsd = if (pangleEnabled && pangleLoadResult is AdResult.Success<*>) {
            pangleController.getCurrentAd()?.pagRevenueInfo?.winEcpm?.revenue?.toDoubleOrNull() ?: 0.0
        } else 0.0

        // 获取 TopOn 收益
        val toponValueUsd = if (toponEnabled && toponLoadResult is AdResult.Success<*>) {
            toponController.peekCachedAd(toponPlacementId)?.let { splashAd ->
                runCatching { splashAd.checkValidAdCaches().firstOrNull()?.publisherRevenue }.getOrNull() ?: 0.0
            } ?: 0.0
        } else 0.0

        val biddingLog = String.format(
            Locale.US,
            "开屏竞价结果 -> AdMob: %.8f 美元%s, Pangle: %.8f 美元%s, TopOn: %.8f 美元%s",
            admobValueUsd, if (admobEnabled) "" else "(禁用)",
            pangleValueUsd, if (pangleEnabled) "" else "(禁用)",
            toponValueUsd, if (toponEnabled) "" else "(禁用)"
        )
        AdLogger.d(biddingLog)
        DataReportManager.reportDataByName("ThinkingData", "bidding", mapOf("log" to biddingLog))

        // 只在启用的平台中选择胜出者
        val winner = when {
            admobEnabled && admobValueUsd >= pangleValueUsd && admobValueUsd >= toponValueUsd -> BiddingWinner.ADMOB
            pangleEnabled && pangleValueUsd >= toponValueUsd && pangleValueUsd >= admobValueUsd -> BiddingWinner.PANGLE
            toponEnabled -> BiddingWinner.TOPON
            admobEnabled -> BiddingWinner.ADMOB
            pangleEnabled -> BiddingWinner.PANGLE
            else -> BiddingWinner.ADMOB // 默认
        }

        return winner
    }
}
