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

namespace Davanci.Nexus.Editor
{
    // Keeps Firebase's editor-only desktop native libs out of git. The x86_64 folder ships
    // with the SDK but contains .bundle/.so files that often exceed GitHub's 100 MB limit.
    // Mobile iOS/Android builds do not need them; each dev gets them locally via SDK import.
    public static class NexusGitignore
    {
        public const string Marker = "# DavanciNexus: Firebase desktop plugins";

        static readonly string[] Entries =
        {
            "/[Aa]ssets/[Ff]irebase/[Pp]lugins/x86_64/",
        };

        public static bool IsFirebaseDesktopIgnored()
        {
            string path = GitignorePath();
            return path != null && File.Exists(path) && File.ReadAllText(path).Contains(Marker);
        }

        public static void EnsureFirebaseDesktopIgnored()
        {
            string path = GitignorePath();
            if (path == null || !File.Exists(path)) return;

            string content = File.ReadAllText(path);
            if (content.Contains(Marker)) return;

            var block = new StringBuilder();
            if (content.Length > 0 && !content.EndsWith("\n"))
                block.AppendLine();
            block.AppendLine();
            block.AppendLine(Marker);
            block.AppendLine("# Editor-only native libs. Not needed for iOS/Android builds; often >100 MB.");
            foreach (string entry in Entries)
                block.AppendLine(entry);

            File.AppendAllText(path, block.ToString());
            Debug.Log("[Nexus] Added Assets/Firebase/Plugins/x86_64/ to .gitignore.");
        }

        static string GitignorePath()
        {
            string root = Directory.GetParent(Application.dataPath)?.FullName;
            return root == null ? null : Path.Combine(root, ".gitignore");
        }

        static bool FirebaseInstalled() =>
            NexusInstaller.Sdks.Any(s => s.Id == "firebase" && s.IsInstalled);

        [InitializeOnLoad]
        static class Bootstrap
        {
            static Bootstrap() => EditorApplication.delayCall += () =>
            {
                if (FirebaseInstalled()) EnsureFirebaseDesktopIgnored();
            };
        }

        class Postprocessor : AssetPostprocessor
        {
            static void OnPostprocessAllAssets(string[] imported, string[] deleted,
                string[] moved, string[] movedFrom)
            {
                foreach (string path in imported)
                {
                    if (path.StartsWith("Assets/Firebase/Plugins/x86_64/", System.StringComparison.OrdinalIgnoreCase))
                    {
                        EnsureFirebaseDesktopIgnored();
                        return;
                    }
                }
            }
        }
    }
}
