package com.remax.bill.ads.topon

import android.content.Context
import com.remax.bill.ads.AdException
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.log.AdLogger
import com.thinkup.core.api.TUNetworkConfig
import com.thinkup.core.api.TUSDK
import com.thinkup.core.api.TUSDKInitListener
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * TopOn SDK 管理器
 * 负责SDK初始化和全局配置
 */
object TopOnManager {

    private const val TAG = "TopOnManager"

    private val _initializationState = MutableStateFlow<AdResult<Unit>>(AdResult.Loading)
    val initializationState: StateFlow<AdResult<Unit>> = _initializationState.asStateFlow()

    @Volatile
    private var isInitialized = false

    /**
     * 初始化 TopOn SDK
     * @param context 上下文
     * @param appId TopOn App ID
     * @param appKey TopOn App Key
     */
    suspend fun initialize(context: Context, appId: String, appKey: String): AdResult<Unit> {
        if (isInitialized) {
            return AdResult.Success(Unit)
        }

        val applicationContext = context.applicationContext

        return suspendCancellableCoroutine { continuation ->
            _initializationState.value = AdResult.Loading

            try {
                TUSDK.setNetworkLogDebug(AdLogger.isLogEnabled())

                TUSDK.init(
                    applicationContext,
                    appId,
                    appKey,
                    TUNetworkConfig(),
                    object : TUSDKInitListener {
                        override fun onSuccess() {
                            AdLogger.d("TopOn SDK初始化完成，版本: ${runCatching { TUSDK.getSDKVersionName() }.getOrElse { "unknown" }}")
                            isInitialized = true
                            val result = AdResult.Success(Unit)
                            _initializationState.value = result
                            if (continuation.isActive) {
                                continuation.resume(result)
                            }
                        }

                        override fun onFail(errorMsg: String) {
                            val message = errorMsg.ifBlank { "未知错误" }
                            AdLogger.e("TopOn SDK初始化失败: %s", message)
                            val result = AdResult.Failure(
                                AdException(
                                    code = AdException.ERROR_INTERNAL,
                                    message = "SDK初始化失败: $message"
                                )
                            )
                            _initializationState.value = result
                            if (continuation.isActive) {
                                continuation.resume(result)
                            }
                        }
                    }
                )
            } catch (e: Exception) {
                AdLogger.e("TopOn SDK初始化过程中发生异常", e)
                val result = AdResult.Failure(
                    AdException(
                        code = AdException.ERROR_INTERNAL,
                        message = "SDK初始化异常: ${e.message}",
                        cause = e
                    )
                )
                _initializationState.value = result
                if (continuation.isActive) {
                    continuation.resume(result)
                }
            }
        }
    }

    /**
     * 检查SDK是否已初始化
     */
    fun isInitialized(): Boolean {
        return isInitialized
    }

    /**
     * 获取当前初始化状态
     */
    fun getCurrentInitializationState(): AdResult<Unit> {
        return _initializationState.value
    }

    /**
     * 获取TopOn广告控制器
     */
    object Controllers {
        val interstitial: TopOnInterstitialAdController
            get() = TopOnInterstitialAdController.getInstance()
            
        val rewarded: TopOnRewardedAdController
            get() = TopOnRewardedAdController.getInstance()
            
        val native: TopOnNativeAdController
            get() = TopOnNativeAdController.getInstance()
            
        val splash: TopOnSplashAdController
            get() = TopOnSplashAdController.getInstance()
            
        val fullScreenNative: TopOnFullScreenNativeAdController
            get() = TopOnFullScreenNativeAdController.getInstance()
            
        val banner: TopOnBannerAdController
            get() = TopOnBannerAdController.getInstance()
    }

    /**
     * 清理所有控制器资源
     */
    fun destroyAll() {
        Controllers.interstitial.destroy()
        Controllers.rewarded.destroy()
        Controllers.native.destroy()
        Controllers.splash.destroy()
        Controllers.fullScreenNative.destroy()
        Controllers.banner.destroy()
        AdLogger.d("TopOn广告控制器已清理")
    }
}

