using System.IO;
using UnityEditor;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Unity Mobile Notifications ships as a UPM package (com.unity.mobile.notifications). Nexus gates
    // the AuthorizationManager prompt behind DAVANCI_NOTIFICATIONS — install the package first, then
    // set the define so iOS/Android notification permission code compiles.
    public static class NexusNotificationsInstaller
    {
        public const string PackageId = "com.unity.mobile.notifications";
        public const string Define = "DAVANCI_NOTIFICATIONS";

        const string DetectType = "Unity.Notifications.iOS.AuthorizationRequest, Unity.Notifications.iOS";

        // Manifest entry is the source of truth — TypeExists alone failed when the type name was wrong.
        public static bool Installed => PackageInManifest();
        public static bool DefineSet => NexusInstaller.HasDefine(Define);
        public static bool InstallInProgress => _add != null && !_add.IsCompleted;

        static AddRequest _add;

        public static void Install()
        {
            if (InstallInProgress || Installed) return;
            _add = Client.Add(PackageId);
            EditorApplication.update += Poll;
        }

        static void Poll()
        {
            if (_add == null) return;
            if (!_add.IsCompleted)
            {
                NexusSetupWindow.RefreshIfOpen();
                NexusDoctorWindow.RefreshIfOpen();
                return;
            }
            EditorApplication.update -= Poll;

            if (_add.Status == StatusCode.Success)
            {
                SetDefine(true);
                AssetDatabase.Refresh();
                string ver = NexusPackageCatalog.Get("mobile_notifications")?.version
                    ?? NexusPackageCatalog.GetStatus("mobile_notifications").InstalledVersion;
                if (!string.IsNullOrEmpty(ver))
                    NexusPackageCatalog.StampInstalled("mobile_notifications", ver);
                Debug.Log("[Nexus] Unity Mobile Notifications installed. DAVANCI_NOTIFICATIONS set.");
                NotifyUiRefresh();
            }
            else
            {
                Debug.LogWarning($"[Nexus] Mobile Notifications install failed: {_add.Error?.message}. " +
                                 "Install from Window → Package Manager (Mobile Notifications), then press Enable.");
                NotifyUiRefresh();
            }
            _add = null;
        }

        static void NotifyUiRefresh()
        {
            EditorApplication.delayCall += () =>
            {
                NexusSetupWindow.RefreshIfOpen();
                NexusDoctorWindow.RefreshIfOpen();
            };
        }

        static bool PackageInManifest()
        {
            try
            {
                string path = Path.Combine(Directory.GetParent(Application.dataPath).FullName, "Packages", "manifest.json");
                return File.Exists(path) && File.ReadAllText(path).Contains($"\"{PackageId}\"");
            }
            catch
            {
                return NexusInstaller.TypeExists(DetectType);
            }
        }

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