using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
#if DAVANCI_GA
using GameAnalyticsSDK;
using GASettings = GameAnalyticsSDK.Setup.Settings;
#endif

namespace Davanci.Nexus.Editor
{
    // Writes GameAnalytics keys straight into GA's own Settings asset so the user
    // never has to add platforms manually. Guarded by DAVANCI_GA.
    public static class NexusGameAnalyticsSetup
    {
        public static bool IsAvailable =>
#if DAVANCI_GA
            true;
#else
            false;
#endif

        // Adds iOS/Android platforms (if missing) and sets their keys.
        public static string Apply(string iosGameKey, string iosSecretKey,
                                   string androidGameKey, string androidSecretKey)
        {
#if DAVANCI_GA
            var s = GameAnalytics.SettingsGA;
            if (s == null)
                return "GameAnalytics settings asset could not be loaded.";

            // GameAnalytics forbids two platforms sharing the same key, so catch it early.
            bool iosFilled = !string.IsNullOrEmpty(iosGameKey) || !string.IsNullOrEmpty(iosSecretKey);
            bool androidFilled = !string.IsNullOrEmpty(androidGameKey) || !string.IsNullOrEmpty(androidSecretKey);
            if (iosFilled && androidFilled)
            {
                if (iosGameKey == androidGameKey)
                    return "iOS and Android Game Keys are identical. GameAnalytics requires a UNIQUE key per platform, use the real, different keys from each platform on your GA dashboard.";
                if (iosSecretKey == androidSecretKey)
                    return "iOS and Android Secret Keys are identical. GameAnalytics requires a UNIQUE secret key per platform.";
            }

            int applied = 0;
            applied += SetPlatform(s, RuntimePlatform.IPhonePlayer, iosGameKey, iosSecretKey) ? 1 : 0;
            applied += SetPlatform(s, RuntimePlatform.Android, androidGameKey, androidSecretKey) ? 1 : 0;

            EditorUtility.SetDirty(s);
            AssetDatabase.SaveAssets();
            // Don't call AssetDatabase.Refresh(), it can detach the live settings
            // object from an open GameAnalytics inspector. Repaint views instead.
            InternalEditorUtility.RepaintAllViews();

            return applied == 0
                ? "No keys entered, nothing applied."
                : $"Applied keys to {applied} platform(s) in GameAnalytics settings.";
#else
            return "GameAnalytics SDK is not installed.";
#endif
        }

        // Registers a starter set of resource currencies and item types so GA accepts
        // CurrencyEarned/CurrencySpent. Safe to call repeatedly.
        public static string RegisterEconomyDefaults()
        {
#if DAVANCI_GA
            var s = GameAnalytics.SettingsGA;
            if (s == null)
                return "GameAnalytics settings asset could not be loaded.";

            string[] currencies = { "coins", "cash", "gems" };
            string[] itemTypes =
            {
                "gameplay", "offline", "rewarded_ad", "reward",
                "purchase", "upgrade", "unlock", "boost", "reset",
            };

            int added = 0;
            added += AddMissing(s.ResourceCurrencies, currencies);
            added += AddMissing(s.ResourceItemTypes, itemTypes);

            if (added > 0)
            {
                EditorUtility.SetDirty(s);
                AssetDatabase.SaveAssets();
                InternalEditorUtility.RepaintAllViews();
            }

            return added == 0
                ? "Economy resource types already registered in GameAnalytics."
                : $"Registered {added} new resource currency/item type(s) in GameAnalytics.";
#else
            return "GameAnalytics SDK is not installed.";
#endif
        }

#if DAVANCI_GA
        static int AddMissing(System.Collections.Generic.List<string> target, string[] values)
        {
            if (target == null) return 0;
            int added = 0;
            foreach (var v in values)
            {
                if (!target.Contains(v))
                {
                    target.Add(v);
                    added++;
                }
            }
            return added;
        }

        static bool SetPlatform(GASettings s, RuntimePlatform platform, string gameKey, string secretKey)
        {
            if (string.IsNullOrEmpty(gameKey) && string.IsNullOrEmpty(secretKey))
                return false;

            if (!s.Platforms.Contains(platform))
                s.AddPlatform(platform);

            int idx = s.Platforms.IndexOf(platform);
            if (idx < 0) return false;

            GASettings.UpdateKeys(idx, gameKey, secretKey);
            return true;
        }
#endif
    }
}
