
namespace Guru
{
	using System;
	using Firebase;
	using Firebase.Analytics;
	using Firebase.Extensions;
	using Firebase.RemoteConfig;
	using Random = UnityEngine.Random;
	using UnityEngine;
	
	public static partial class FirebaseUtil
	{
		private static readonly string LOG_TAG = "Firebase";
		private static bool _isReady = false;
		public static bool IsReady => _isReady;
		
		public static DependencyStatus DependencyStatus = DependencyStatus.UnavailableOther;
		public static bool IsFirebaseInitialized => DependencyStatus == DependencyStatus.Available;
		public static Action<bool> onInitComplete;

		public static Action<bool> OnFirebaseAuthResult;
		public static Action<bool> OnUserAuthResult;
		private static Action<string> _onDeeplinkCallback;

		/// <summary>
		/// 初始化 Firebase 组件
		/// </summary>
		/// <param name="callback"></param>
		/// <param name="onDeeplinkCallback"></param>
		public static void InitFirebase(Action callback, Action<string> onDeeplinkCallback = null)
		{
			_isReady = false;
			_onDeeplinkCallback = onDeeplinkCallback;
			Analytics.InitAnalytics();
			
			// 初始化 Fireabse 依赖
			FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
				DependencyStatus = task.Result;
				if (DependencyStatus == DependencyStatus.Available)
				{
					_isReady = true;
					InitializeFirebaseComp();
					callback?.Invoke();
				} 
				else 
				{
					Log.E(LOG_TAG, "Could not resolve all Firebase dependencies: " + DependencyStatus);
				}
				onInitComplete?.Invoke(_isReady);
			});
		}
		private static void InitializeFirebaseComp()
		{
			Analytics.OnFirebaseCompleted(); // Firebase 初始化回调
			InitCrashlytics();  // 老项目沿用此逻辑
			InitRemoteConfig();	// 老项目沿用此逻辑
			InitAssetByFirebaseIdAsync(); // 获取到 FirebaseID 后异步执行逻辑
			
			if (IPMConfig.IPM_UID.IsNullOrEmpty())
			{
				Log.I(LOG_TAG, "没有存储UID时，从中台获取匿名认证授权");
				//没有存储UID时，从中台获取匿名认证授权
				new AuthUserRequest()
					.SetRetryTimes(-1)
					.SetSuccessCallBack(() =>
					{
						OnUserAuthResult?.Invoke(true);
						AuthUser(InitializeMessage);
					}).SetFailCallBack(() =>
					{
						OnUserAuthResult?.Invoke(false);
					})
					.Send();
			}
			else
			{
				InitializeMessage();
				int currentTimeStamp = TimeUtil.GetCurrentTimeStampSecond();
				if(currentTimeStamp - IPMConfig.IPM_TOKEN_TIME >= IPMConfig.TOKEN_VALID_TIME)
				{
					//中台Token失效，从中台重新获取Token
					new RefreshTokenRequest().SetRetryTimes(-1).Send();
				}
				
				if(currentTimeStamp - IPMConfig.IPM_FIREBASE_TOKEN_TIME >= IPMConfig.FIREBASE_TOKEN_VALID_TIME)
				{
					//中台firebaseToken失效，从中台重新获取firebaseToken
					new RefreshFirebaseTokenRequest()
						.SetRetryTimes(-1)
						.SetSuccessCallBack(()=> AuthUser(InitializeMessage))
						.Send();
				}
				else
				{
					AuthUser(InitializeMessage);
				}
			}
		}


		private static void InitAssetByFirebaseIdAsync()
		{
			Debug.Log($"[SDK] --- InitAssetByFirebaseIdAsync");
			// 异步获取 FirebaseID
			FirebaseAnalytics.GetAnalyticsInstanceIdAsync()
				.ContinueWithOnMainThread(task =>
				{
					string fid = task.Result;
					if (task.IsCompleted && !string.IsNullOrEmpty(fid))
					{
						// 保存本地ID备份
						IPMConfig.FIREBASE_ID = fid; // 保存FirebaseID
						Debug.Log($"[SDK] --- Get FirebaseID: {fid}");
						GuruAnalytics.SetFirebaseId(fid);
					}
					else
					{
						Debug.LogError($"[SDK] --- Fetch FirebaseID failed on start!");
					}

					//--- 结束后启动相关的服务 ---
					InitAdjustService(_onDeeplinkCallback); // 启动 AdjustService
				});
		}
		

		#region 启动 Adjust 服务
		
		/// <summary>
		/// 启动 Adjust 服务
		/// </summary>
		private static void InitAdjustService(Action<string> onDeeplinkCallback)
		{
			// 启动 AdjustService
			string appToken = GuruSettings.Instance.AdjustSetting?.GetAppToken() ?? "";
			string fbAppId = GuruSettings.Instance.IPMSetting.FacebookAppId;
			AdjustService.StartService(appToken, fbAppId, onDeeplinkCallback);
		}
		

		#endregion

		
		
	}
}