// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace WPFMA.Team
{
    [Serializable]
    internal sealed class TeamProjectInfo
    {
        public string unity;
        public string[] packages;
        public string[] shaders;
        public string[] layers;
        public string[] tags;
        public string collision;
    }

    internal sealed class TeamMissing
    {
        public string Kind;
        public string Name;
        public string Detail;
        public string Url;
        public string LinkLabel;
    }

    /// <summary>
    /// Compares the two projects: Unity version, packages, the shaders the shared materials use, and layers and
    /// tags. Paid packages and shaders are never sent between editors; this lists what is missing with where to
    /// get it, so each person installs their own copy.
    /// </summary>
    [InitializeOnLoad]
    internal static class TeamProject
    {
        private static readonly Regex ShaderRef = new Regex(@"m_Shader:\s*\{fileID:\s*-?\d+,\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled);
        private static readonly Regex Dependency = new Regex("\"([a-z0-9][a-z0-9._-]+)\"\\s*:\\s*\"([^\"]+)\"", RegexOptions.Compiled);

        private static readonly string[][] KnownLinks =
        {
            
            new[] { "liltoon", "https://lilxyzw.github.io/lilToon/", "lilToon" },
            new[] { "lilxyzw", "https://lilxyzw.github.io/lilToon/", "lilToon" },
            new[] { "silent", "https://gitlab.com/s-ilent/SCSS", "Silent's Cel Shading" },
            new[] { "orels", "https://shaders.orels.sh/", "orels1 shaders" },
            new[] { "mochie", "https://github.com/MochiesCode/Mochies-Unity-Shaders", "Mochie's shaders" },
            new[] { "unitychan", "https://github.com/unity3d-jp/UnityChanToonShader2", "UnityChan Toon Shader" },
            new[] { "nadena.dev.modular-avatar", "https://modular-avatar.nadena.dev/", "Modular Avatar" },
            new[] { "nadena.dev.ndmf", "https://ndmf.nadena.dev/", "NDMF" },
            new[] { "com.vrcfury.vrcfury", "https://vrcfury.com/", "VRCFury" },
            new[] { "red.sim.lightvolumes", "https://github.com/REDSIM/VRCLightVolumes", "VRC Light Volumes" },
            new[] { "com.llealloo.audiolink", "https://github.com/llealloo/vrc-udon-audio-link", "AudioLink" },
            new[] { "vrchat.blackstartx.gesture-manager", "https://github.com/BlackStartx/VRC-Gesture-Manager", "Gesture Manager" },
            new[] { "com.vrchat.", "https://vrchat.com/home/download", "VRChat Creator Companion" },
            new[] { "jp.lilxyzw.", "https://lilxyzw.github.io/", "lilxyzw tools" },
            new[] { "dev.hai-vr.", "https://docs.hai-vr.dev/", "Haï tools" },
            new[] { "com.anatawa12.", "https://vpm.anatawa12.com/", "anatawa12 tools" }
        };

        /// <summary>Free packages that can be installed from their public VPM listing in one click.</summary>
        private static readonly Dictionary<string, string> FreeListings = new Dictionary<string, string>
        {
            { "com.vrcfury.vrcfury", "https://vcc.vrcfury.com" },
            { "nadena.dev.modular-avatar", "https://vpm.nadena.dev/vpm.json" },
            { "nadena.dev.ndmf", "https://vpm.nadena.dev/vpm.json" },
            { "jp.lilxyzw.liltoon", "https://lilxyzw.github.io/vpm-repos/vpm.json" },
            { "vrchat.blackstartx.gesture-manager", "https://blackstartx.github.io/vrc-gesture-manager/index.json" },
            { "com.llealloo.audiolink", "https://vpm.llealloo.net/index.json" },
            { "red.sim.lightvolumes", "https://redsim.github.io/vpmlisting/index.json" }
        };

        private static readonly Dictionary<string, string[]> Needs = new Dictionary<string, string[]>
        {
            { "nadena.dev.modular-avatar", new[] { "nadena.dev.ndmf" } }
        };

        /// <summary>Install progress per package name, shown in the Team tab.</summary>
        internal static readonly Dictionary<string, string> InstallStatus = new Dictionary<string, string>();
        private static readonly Queue<string> installQueue = new Queue<string>();
        private static bool installing;

        internal static bool CanInstall(TeamMissing item)
        {
            return item.Kind == "Package" && FreeListings.ContainsKey(item.Name);
        }

        internal static void Install(string name)
        {
            string[] first;
            if (Needs.TryGetValue(name, out first))
                foreach (var dependency in first)
                    if (!Packages().ContainsKey(dependency) && !installQueue.Contains(dependency))
                        Enqueue(dependency);
            Enqueue(name);
            if (!installing)
                NextInstall();
        }

        private static void Enqueue(string name)
        {
            if (installQueue.Contains(name))
                return;
            installQueue.Enqueue(name);
            InstallStatus[name] = "Waiting...";
        }

        private static void NextInstall()
        {
            if (installQueue.Count == 0)
            {
                installing = false;
                return;
            }

            installing = true;
            string name = installQueue.Dequeue();
            string listing;
            if (!FreeListings.TryGetValue(name, out listing))
            {
                InstallStatus[name] = "No public listing known.";
                NextInstall();
                return;
            }

            InstallStatus[name] = "Finding it...";
            TeamSession.Raise();
            var repository = new WPFMAVpmRepository();
            repository.Fetch(listing, (packages, error) =>
            {
                var package = packages != null ? packages.FirstOrDefault(p => p.Name == name) : null;
                if (package == null)
                {
                    InstallStatus[name] = "Could not find it: " + (error ?? "not in the listing");
                    TeamSession.Raise();
                    NextInstall();
                    return;
                }

                InstallStatus[name] = "Downloading " + package.Version + "...";
                TeamSession.Raise();
                repository.Download(package, (path, downloadError) =>
                {
                    if (path == null)
                    {
                        InstallStatus[name] = "Download failed: " + downloadError;
                        TeamSession.Raise();
                        NextInstall();
                        return;
                    }

                    try
                    {
                        WPFMAVpmRepository.Install(package);
                        InstallStatus[name] = "Installed " + package.Version + ". Unity will reload.";
                        TeamSession.AddSystem("Installed " + name + " " + package.Version + ".");
                    }
                    catch (Exception e)
                    {
                        InstallStatus[name] = "Install failed: " + e.Message;
                    }
                    TeamSession.Raise();
                    NextInstall();
                });
            });
        }

        /// <summary>Chosen in the setup window: install the free packages the host uses automatically.</summary>
        internal static bool AutoInstall
        {
            get { return EditorPrefs.GetBool("WPFMA.Team.AutoInstall", true); }
            set { EditorPrefs.SetBool("WPFMA.Team.AutoInstall", value); }
        }

        internal static TeamProjectInfo Remote { get; private set; }

        /// <summary>Shaders that are part of the shared files (like locked Poiyomi shaders) and haven't arrived yet.</summary>
        internal static int ArrivingShaders { get; private set; }

        /// <summary>The user hid the "needs" lines for this session.</summary>
        internal static bool Hidden;

        private static double recheckAt = -1;

        /// <summary>Files arrived: the lists are worked out again shortly (they were made before anything arrived).</summary>
        internal static void Recheck()
        {
            if (Remote != null)
                recheckAt = EditorApplication.timeSinceStartup + 2.0;
        }
        internal static readonly List<TeamMissing> Missing = new List<TeamMissing>();
        internal static readonly List<string> Warnings = new List<string>();
        internal static bool LayersDiffer { get; private set; }
        private static readonly HashSet<string> missingScripts = new HashSet<string>();
        private static Task<string[]> shaderScan;

        // Host: each guest's name and Unity version (the host is only warned about version differences).
        private static readonly Dictionary<string, KeyValuePair<string, string>> guestUnity = new Dictionary<string, KeyValuePair<string, string>>();

        static TeamProject()
        {
            TeamSession.LinkUp += OnLinkUp;
            TeamSession.Received += OnReceived;
            TeamSession.Ended += () =>
            {
                Remote = null;
                Hidden = false;
                ArrivingShaders = 0;
                Missing.Clear();
                Warnings.Clear();
                missingScripts.Clear();
                guestUnity.Clear();
            };
            TeamSession.PeerLeft += () =>
            {
                if (TeamSession.Sender != null && guestUnity.Remove(TeamSession.Sender.Id))
                    Compare();
            };
            EditorApplication.update += Update;
        }

        private static void OnLinkUp(bool resumed)
        {
            var excluded = TeamFiles.Excluded.ToArray();
            shaderScan = Task.Run(() => ShaderGuids(excluded));
        }

        private static double lastSettingsCheck;
        private static string lastSettingsSent;

        /// <summary>Layers, tags and which layers collide: the host's are the reference.</summary>
        private static string SettingsSignature()
        {
            return string.Join("|", Enumerable.Range(0, 32).Select(LayerMask.LayerToName).ToArray()) + "#" +
                   string.Join("|", UnityEditorInternal.InternalEditorUtility.tags) + "#" + Collision();
        }

        private static string Collision()
        {
            var bits = new System.Text.StringBuilder(528);
            for (int a = 0; a < 32; a++)
                for (int b = a; b < 32; b++)
                    bits.Append(Physics.GetIgnoreLayerCollision(a, b) ? '1' : '0');
            return bits.ToString();
        }

        private static void Update()
        {
            if (recheckAt >= 0 && EditorApplication.timeSinceStartup >= recheckAt)
            {
                recheckAt = -1;
                Compare();
            }

            // The host shares changes to layers, tags and collisions as they happen; the guest takes them.
            if (TeamSession.IsLinked && TeamSession.IsHost && EditorApplication.timeSinceStartup - lastSettingsCheck > 5.0)
            {
                lastSettingsCheck = EditorApplication.timeSinceStartup;
                string signature = SettingsSignature();
                if (lastSettingsSent != null && signature != lastSettingsSent)
                    TeamSession.Send(new TeamMessage
                    {
                        t = "psettings",
                        a = Enumerable.Range(0, 32).Select(LayerMask.LayerToName).ToArray(),
                        paths = UnityEditorInternal.InternalEditorUtility.tags,
                        m = Collision()
                    });
                lastSettingsSent = signature;
            }

            if (shaderScan == null || !shaderScan.IsCompleted)
                return;

            var finished = shaderScan;
            shaderScan = null;
            if (!TeamSession.IsLinked)
                return;

            var shaders = new List<string>();
            if (finished.Status == TaskStatus.RanToCompletion)
            {
                foreach (var guid in finished.Result)
                {
                    string path = AssetDatabase.GUIDToAssetPath(guid);
                    if (string.IsNullOrEmpty(path))
                        continue;
                    var shader = AssetDatabase.LoadAssetAtPath<Shader>(path);
                    shaders.Add(guid + "|" + (shader != null ? shader.name : Path.GetFileNameWithoutExtension(path)) + "|" + path);
                }
            }

            var info = new TeamProjectInfo
            {
                unity = Application.unityVersion,
                packages = Packages().Select(p => p.Key + "@" + p.Value).ToArray(),
                shaders = shaders.ToArray(),
                layers = Enumerable.Range(0, 32).Select(LayerMask.LayerToName).ToArray(),
                tags = UnityEditorInternal.InternalEditorUtility.tags,
                collision = Collision()
            };
            lastSettingsSent = SettingsSignature();
            TeamSession.Send(new TeamMessage { t = "proj", json = JsonUtility.ToJson(info) });
        }

        private static void OnReceived(TeamMessage message, byte[] blob)
        {
            if (message.t == "psettings" && Remote != null && !TeamSession.IsHost)
            {
                Remote.layers = message.a;
                Remote.tags = message.paths;
                Remote.collision = message.m;
                MatchHostSettings();
                Compare();
                return;
            }
            if (message.t != "proj" || string.IsNullOrEmpty(message.json))
                return;
            TeamProjectInfo info;
            try
            {
                info = JsonUtility.FromJson<TeamProjectInfo>(message.json);
            }
            catch (Exception)
            {
                return;
            }
            if (TeamSession.IsHost)
            {
                if (TeamSession.Sender != null)
                    guestUnity[TeamSession.Sender.Id] = new KeyValuePair<string, string>(TeamSession.Sender.Name, info.unity);
                Compare();
                return;
            }
            Remote = info;
            if (!TeamSession.IsHost)
                MatchHostSettings();
            Compare();

            // Free packages the host uses are installed straight away when that was chosen in the setup window.
            if (!TeamSession.IsHost && AutoInstall)
                foreach (var item in Missing.Where(CanInstall).ToList())
                    if (!InstallStatus.ContainsKey(item.Name))
                        Install(item.Name);

            int paid = Missing.Count(m => !CanInstall(m));
            if (paid > 0)
                TeamSession.AddSystem(TeamSession.RemoteName + "'s project uses " + paid + " thing(s) you need to get yourself (see the Team tab).");
        }

        internal static void NoteMissingScript(string typeName)
        {
            string name = typeName.Split(',')[0].Trim();
            if (!missingScripts.Add(name))
                return;
            Missing.Add(MakeMissing("Script", name, "A component " + TeamSession.RemoteName +
                " added uses this script, which is not in your project yet" + (TeamFiles.Pending.Count > 0 ? " (scripts are waiting for you to trust them)." : ".")));
            TeamSession.Raise();
        }

        private static TeamMissing MakeMissing(string kind, string name, string detail)
        {
            var item = new TeamMissing { Kind = kind, Name = name, Detail = detail };
            Link(item, name);
            return item;
        }

        /// <summary>Recomputes what the teammate's project has that this one lacks.</summary>
        internal static void Compare()
        {
            Missing.RemoveAll(m => m.Kind != "Script");
            Warnings.Clear();
            ArrivingShaders = 0;

            // The host's project is the reference: the host is only told about Unity version differences.
            if (TeamSession.IsHost)
            {
                foreach (var guest in guestUnity.Values)
                    if (!string.IsNullOrEmpty(guest.Value) && guest.Value != Application.unityVersion)
                        Warnings.Add("You are on Unity " + Application.unityVersion + " and " + guest.Key + " is on " + guest.Value +
                                     ". Use the same version so scenes and assets open the same way.");
                TeamSession.Raise();
                return;
            }
            if (Remote == null)
                return;

            if (!string.IsNullOrEmpty(Remote.unity) && Remote.unity != Application.unityVersion)
                Warnings.Add("You are on Unity " + Application.unityVersion + " and " + TeamSession.RemoteName + " is on " + Remote.unity +
                             ". Use the same version so scenes and assets open the same way.");

            // The host's project is the reference: the host isn't told what the guest's own project uses.
            if (TeamSession.IsHost)
            {
                TeamSession.Raise();
                return;
            }

            var mine = Packages();
            foreach (var entry in Remote.packages ?? new string[0])
            {
                int at = entry.LastIndexOf('@');
                if (at <= 0)
                    continue;
                string name = entry.Substring(0, at);
                string version = entry.Substring(at + 1);
                if (name.StartsWith("com.unity.modules.", StringComparison.Ordinal))
                    continue;

                string have;
                if (!mine.TryGetValue(name, out have))
                    Missing.Add(MakeMissing("Package", name, "Version " + version + ". Add it with the Creator Companion (or ALCOM) the same way your teammate did."));
                else if (have != version && name.StartsWith("com.vrchat.", StringComparison.Ordinal))
                    Warnings.Add(name + ": you have " + have + ", " + TeamSession.RemoteName + " has " + version + ". Match VRChat SDK versions to avoid upload differences.");
            }

            var families = new Dictionary<string, int>();
            foreach (var entry in Remote.shaders ?? new string[0])
            {
                var parts = entry.Split('|');
                if (parts.Length < 3)
                    continue;
                string path = AssetDatabase.GUIDToAssetPath(parts[0]);
                if (!string.IsNullOrEmpty(path) && File.Exists(path))
                    continue;

                // Shader files in shared folders (locked Poiyomi shaders, project shaders) come with the files.
                if (TeamFiles.Shared(parts[2]))
                {
                    ArrivingShaders++;
                    continue;
                }

                string family = Family(parts[1]);
                int count;
                families.TryGetValue(family, out count);
                families[family] = count + 1;
            }
            foreach (var pair in families)
                Missing.Add(MakeMissing("Shader", pair.Key, pair.Value == 1
                    ? "Used by shared materials. They look pink (or show a stand-in) until you install your own copy."
                    : pair.Value + " of its shaders are used by shared materials. Install your own copy."));

            var layers = Enumerable.Range(0, 32).Select(LayerMask.LayerToName).ToArray();
            LayersDiffer = Remote.layers != null && Remote.layers.Length == 32 && !layers.SequenceEqual(Remote.layers);
            if (LayersDiffer)
                Warnings.Add("Your layers differ from " + TeamSession.RemoteName + "'s. Objects can end up on the wrong layer.");
            TeamSession.Raise();
        }

        /// <summary>The guest takes the host's layers, tags and collision settings, so objects behave the same.</summary>
        private static void MatchHostSettings()
        {
            if (Remote == null || Remote.layers == null || Remote.layers.Length != 32)
                return;
            bool layersDiffer = !Enumerable.Range(0, 32).Select(LayerMask.LayerToName).SequenceEqual(Remote.layers);
            bool tagsMissing = (Remote.tags ?? new string[0]).Except(UnityEditorInternal.InternalEditorUtility.tags).Any();
            bool collisionDiffers = !string.IsNullOrEmpty(Remote.collision) && Remote.collision.Length == 528 && Remote.collision != Collision();
            if (!layersDiffer && !tagsMissing && !collisionDiffers)
                return;

            if (layersDiffer || tagsMissing)
                UseRemoteLayersAndTags();
            if (collisionDiffers)
            {
                int index = 0;
                for (int a = 0; a < 32; a++)
                    for (int b = a; b < 32; b++)
                        Physics.IgnoreLayerCollision(a, b, Remote.collision[index++] == '1');
            }
            TeamSession.AddSystem("Matched " + TeamSession.RemoteName + "'s layers, tags and collision settings (the host's are used).");
        }

        /// <summary>Copies the teammate's layers and adds their tags to this project.</summary>
        internal static void UseRemoteLayersAndTags()
        {
            if (Remote == null)
                return;

            var assets = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset");
            if (assets == null || assets.Length == 0)
                return;

            var manager = new SerializedObject(assets[0]);
            var layers = manager.FindProperty("layers");
            for (int i = 8; layers != null && i < 32 && i < Remote.layers.Length; i++)
            {
                var layer = layers.GetArrayElementAtIndex(i);
                if (layer.stringValue != Remote.layers[i])
                    layer.stringValue = Remote.layers[i];
            }

            var tags = manager.FindProperty("tags");
            var existing = UnityEditorInternal.InternalEditorUtility.tags;
            foreach (var tag in Remote.tags ?? new string[0])
            {
                if (existing.Contains(tag) || tags == null)
                    continue;
                tags.InsertArrayElementAtIndex(tags.arraySize);
                tags.GetArrayElementAtIndex(tags.arraySize - 1).stringValue = tag;
            }

            manager.ApplyModifiedProperties();
            AssetDatabase.SaveAssets();
            Compare();
        }

        /// <summary>"Hidden/Locked/.poiyomi/Poiyomi Pro/abc123" and ".poiyomi/Poiyomi Pro" both become "Poiyomi Pro".</summary>
        private static string Family(string shaderName)
        {
            string name = shaderName ?? string.Empty;
            if (name.StartsWith("Hidden/Locked/", StringComparison.Ordinal))
            {
                name = name.Substring("Hidden/Locked/".Length);
                int last = name.LastIndexOf('/');
                if (last > 0)
                    name = name.Substring(0, last);
            }
            name = name.TrimStart('.');
            int slash = name.IndexOf('/');
            return slash >= 0 && slash < name.Length - 1 ? name.Substring(slash + 1) : name;
        }

        private static void Link(TeamMissing item, string name)
        {
            string lower = name.ToLowerInvariant();
            foreach (var known in KnownLinks)
            {
                if (lower.Contains(known[0].ToLowerInvariant()) || name.Contains(known[0]))
                {
                    item.Url = known[1];
                    item.LinkLabel = known[2];
                    return;
                }
            }
        }

        private static Dictionary<string, string> Packages()
        {
            var result = new Dictionary<string, string>();
            try
            {
                if (File.Exists("Packages/manifest.json"))
                {
                    string text = File.ReadAllText("Packages/manifest.json");
                    int start = text.IndexOf("\"dependencies\"", StringComparison.Ordinal);
                    int end = start >= 0 ? text.IndexOf('}', start) : -1;
                    if (start >= 0 && end > start)
                        foreach (Match match in Dependency.Matches(text.Substring(start, end - start)))
                            result[match.Groups[1].Value] = match.Groups[2].Value;
                }

                foreach (var folder in Directory.GetDirectories("Packages"))
                {
                    string file = Path.Combine(folder, "package.json");
                    if (!File.Exists(file))
                        continue;
                    string text = File.ReadAllText(file);
                    var name = Regex.Match(text, "\"name\"\\s*:\\s*\"([^\"]+)\"");
                    var version = Regex.Match(text, "\"version\"\\s*:\\s*\"([^\"]+)\"");
                    if (name.Success)
                        result[name.Groups[1].Value] = version.Success ? version.Groups[1].Value : "?";
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        private static string[] ShaderGuids(string[] excluded)
        {
            var guids = new HashSet<string>();
            foreach (var file in Directory.EnumerateFiles("Assets", "*.mat", SearchOption.AllDirectories))
            {
                string path = file.Replace('\\', '/');
                if (excluded.Any(f => path.StartsWith(f + "/", StringComparison.Ordinal)))
                    continue;
                try
                {
                    using (var reader = new StreamReader(path))
                    {
                        var buffer = new char[8192];
                        int read = reader.Read(buffer, 0, buffer.Length);
                        var match = ShaderRef.Match(new string(buffer, 0, read));
                        if (match.Success && !match.Groups[1].Value.StartsWith("0000000000000000", StringComparison.Ordinal))
                            guids.Add(match.Groups[1].Value);
                    }
                }
                catch (Exception)
                {
                }
            }
            return guids.ToArray();
        }
    }
}
#endif
