#if UNITY_EDITOR_OSX
using System.Diagnostics;
using System.IO;
using UnityEditor;
using Debug = UnityEngine.Debug;

namespace Davanci.Nexus.Editor
{
    // Strips the com.apple.quarantine attribute from imported native plugins so
    // Gatekeeper doesn't block Unity from loading them. Runs once per editor session
    // and again after a native plugin is imported.
    [InitializeOnLoad]
    public static class NexusMacQuarantine
    {
        const string SessionKey = "Davanci.Nexus.QuarantineCheckedThisSession";

        static readonly string[] PluginRoots =
        {
            "Assets/Firebase",
            "Assets/GameAnalytics",
            "Assets/AppsFlyer",
            "Assets/Plugins",
        };

        static NexusMacQuarantine()
        {
            if (SessionState.GetBool(SessionKey, false))
                return;
            SessionState.SetBool(SessionKey, true);

            EditorApplication.delayCall += () => Clean(verbose: false);
        }

        // No menu entry; runs automatically on import and is exposed as a button in
        // Nexus Setup's Firebase step.
        public static void CleanMenu() => Clean(verbose: true);

        public static void Clean(bool verbose)
        {
            int cleaned = 0;
            foreach (var root in PluginRoots)
            {
                if (!Directory.Exists(root))
                    continue;

                int flagged = CountQuarantined(root);
                if (flagged == 0)
                    continue;

                RemoveQuarantine(root);
                cleaned += flagged;
                Debug.Log($"[Nexus] Removed macOS quarantine from {flagged} file(s) under {root}.");
            }

            if (cleaned > 0)
                Debug.Log($"[Nexus] macOS quarantine fix complete ({cleaned} file(s)). " +
                          "If a plugin already failed to load, restart Unity.");
            else if (verbose)
                Debug.Log("[Nexus] No quarantined native plugins found, nothing to fix.");
        }

        static int CountQuarantined(string root)
        {
            string output = RunShell($"xattr -r '{root}' 2>/dev/null | grep -c com.apple.quarantine");
            return int.TryParse(output.Trim(), out int n) ? n : 0;
        }

        static void RemoveQuarantine(string root)
            => RunShell($"xattr -r -d com.apple.quarantine '{root}' 2>/dev/null");

        static string RunShell(string command)
        {
            try
            {
                var psi = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = $"-c \"{command.Replace("\"", "\\\"")}\"",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                };

                using var process = Process.Start(psi);
                string stdout = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return stdout;
            }
            catch (System.Exception e)
            {
                Debug.LogWarning($"[Nexus] Could not run the macOS quarantine fix: {e.Message}");
                return string.Empty;
            }
        }
    }

    // Re-runs the quarantine fix when a native plugin is imported mid-session.
    class NexusQuarantinePostprocessor : AssetPostprocessor
    {
        static void OnPostprocessAllAssets(string[] imported, string[] deleted,
                                           string[] moved, string[] movedFrom)
        {
            foreach (var path in imported)
            {
                if (IsNativePlugin(path))
                {
                    NexusMacQuarantine.Clean(verbose: false);
                    return;
                }
            }
        }

        static bool IsNativePlugin(string path)
            => path.EndsWith(".bundle") || path.EndsWith(".dylib") || path.Contains(".framework");
    }
}
#endif
