package com.remax.bill.ads.bidding

import android.content.Context
import com.remax.bill.BuildConfig
import com.remax.bill.ads.AdException
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.AdMobManager
import com.remax.bill.ads.log.AdLogger
import com.remax.bill.ads.pangle.PangleManager
import com.remax.bill.ads.topon.TopOnManager
import kotlin.getOrElse
import kotlin.runCatching

/**
 * App Open 竞价初始化控制器
 * 负责初始化参与竞价的3个网络（AdMob 与 Pangle 与Topon）
 */
object AppOpenBiddingInitializer {

    private const val TAG = "AppOpenBiddingInit"

    suspend fun initialize(context: Context,icon:Int): AdResult<Unit> {
        AdLogger.d("$TAG 开始初始化")

        val admobResult = runCatching {
            AdMobManager.initialize(context)
        }.getOrElse { throwable ->
            AdLogger.e("$TAG AdMob 初始化异常", throwable)
            return AdResult.Failure(
                AdException(
                    code = AdException.ERROR_INTERNAL,
                    message = "AdMob 初始化异常: ${throwable.message}",
                    cause = throwable
                )
            )
        }

        if (admobResult is AdResult.Failure) {
            AdLogger.d("$TAG AdMob 初始化失败: ${admobResult.error.message}")
            return admobResult
        }

        val pangleResult = runCatching {
            PangleManager.initialize(
                context = context,
                appId = BuildConfig.PANGLE_APPLICATION_ID,
                appIconId = icon
            )
        }.getOrElse { throwable ->
            AdLogger.e("$TAG Pangle 初始化异常", throwable)
            return AdResult.Failure(
                AdException(
                    code = AdException.ERROR_INTERNAL,
                    message = "Pangle 初始化异常: ${throwable.message}",
                    cause = throwable
                )
            )
        }

        if (pangleResult is AdResult.Failure) {
            AdLogger.d("$TAG Pangle 初始化失败: ${pangleResult.error.message}")
            return pangleResult
        }

        val toponResult = runCatching {
            TopOnManager.initialize(
                context = context,
                appId = BuildConfig.TOPON_APPLICATION_ID,
                appKey = BuildConfig.TOPON_APP_KEY
            )
        }.getOrElse { throwable ->
            AdLogger.e("$TAG TopOn 初始化异常", throwable)
            return AdResult.Failure(
                AdException(
                    code = AdException.ERROR_INTERNAL,
                    message = "TopOn 初始化异常: ${throwable.message}",
                    cause = throwable
                )
            )
        }

        if (toponResult is AdResult.Failure) {
            AdLogger.d("$TAG TopOn 初始化失败: ${toponResult.error.message}")
            return toponResult
        }

        AdLogger.d("$TAG 初始化完成")
        return AdResult.Success(Unit)
    }
}

