using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Unity LevelPlay (ironSource) ships as a .unitypackage (not UPM). We bundle it in
    // InstallerPackages/ like the other SDKs and import it in-place from Nexus Setup. Detected by
    // the LevelPlay entry type; importing sets the DAVANCI_LEVELPLAY define. Unlike AppLovin, the
    // app key is passed at runtime (from NexusConfig), so there's no settings asset to write.
    public static class NexusLevelPlayInstaller
    {
        public const string Define = "DAVANCI_LEVELPLAY";

        // LevelPlay's unified entry-point type (com.unity3d.mediation.LevelPlay); scanned by short name.
        const string DetectType = "LevelPlay";

        public const string DocsUrl =
            "https://developers.is.com/ironsource-mobile/unity/unity-plugin/";

        public static bool Installed => NexusInstaller.TypeExists(DetectType);
        public static bool DefineSet => NexusInstaller.HasDefine(Define);

        // The bundled LevelPlay / ironSource .unitypackage, found by prefix so a version bump is fine.
        public static string PackagePath
        {
            get
            {
                if (!Directory.Exists(NexusInstaller.PackagesFolder)) return null;
                return Directory.GetFiles(NexusInstaller.PackagesFolder, "*.unitypackage")
                    .Where(f =>
                    {
                        var n = Path.GetFileName(f);
                        return n.IndexOf("LevelPlay", System.StringComparison.OrdinalIgnoreCase) >= 0
                            || n.IndexOf("IronSource", System.StringComparison.OrdinalIgnoreCase) >= 0;
                    })
                    .OrderByDescending(f => f).FirstOrDefault();
            }
        }

        public static bool PackageBundled => !string.IsNullOrEmpty(PackagePath) && File.Exists(PackagePath);

        public static void Import()
        {
            string path = PackagePath;
            if (string.IsNullOrEmpty(path) || !File.Exists(path))
            {
                EditorUtility.DisplayDialog("DavanciNexus",
                    "LevelPlay package not found in " + NexusInstaller.PackagesFolder +
                    ".\nDrop the LevelPlay (ironSource) .unitypackage there.", "OK");
                return;
            }
            SetDefine(true);
            NexusPackageUpdater.ImportTracked("levelplay", path, NexusPackageCatalog.Get("levelplay")?.version);
        }

        // Folders the LevelPlay / ironSource package and its bundled mediation adapters create.
        // Deleted on Remove so no native frameworks linger to be linked into the Xcode build.
        static readonly string[] InstallFolders =
        {
            "Assets/LevelPlay",
            "Assets/IronSource",
            "Assets/UnityAds",
        };

        // Mirror of NexusInstaller.Remove for the (non-registry) LevelPlay package: delete its
        // folders and clear the define together, so a leftover define can't keep referencing a
        // plugin that's gone — the exact mismatch that produces "Undefined symbol" at link time.
        public static void Remove()
        {
            bool ok = EditorUtility.DisplayDialog("DavanciNexus",
                "Remove the LevelPlay / ironSource SDK (and bundled adapters) and clear DAVANCI_LEVELPLAY?\n\n" +
                "Your App Key / ad unit IDs in NexusConfig are kept.",
                "Remove LevelPlay", "Cancel");
            if (!ok) return;

            foreach (var folder in InstallFolders)
                if (AssetDatabase.IsValidFolder(folder))
                    AssetDatabase.DeleteAsset(folder);

            SetDefine(false);
            AssetDatabase.Refresh();
        }

        public static void OpenDocs() => Application.OpenURL(DocsUrl);

        public static void OpenNetworkManager()
        {
            var t = System.Type.GetType("LevelPlayDependenciesManager, Unity.LevelPlay.Editor");
            if (t == null)
            {
                foreach (var asm in System.AppDomain.CurrentDomain.GetAssemblies())
                {
                    t = asm.GetType("LevelPlayDependenciesManager");
                    if (t != null) break;
                }
            }
            var m = t?.GetMethod("ShowDependenciesManager",
                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            if (m != null) m.Invoke(null, null);
            else Debug.LogWarning("[Nexus] LevelPlay Network Manager not found — import LevelPlay first.");
        }

        public static void SetDefine(bool enabled) => NexusInstaller.SetDefine(Define, enabled);
    }
}
