// 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.IO;
using System.IO.Compression;
using UnityEditor;
using UnityEngine;

namespace WPFMA.Editor
{
    [InitializeOnLoad]
    internal static class WPFMAInstaller
    {
        private const string PackageSourcesPath = "Assets/WPFMA-SDK/PackageSources";
        private const string PromoFolderPath = "Assets/!GET_MORE_ASSETS_FOR_FREE";
        private const string PromoMetaPath = "Assets/!GET_MORE_ASSETS_FOR_FREE.meta";
        private const string StartupSetupKey = "WPFMA.StartupSetupComplete";

        internal enum ProjectKind
        {
            Undecided,
            Avatars,
            Worlds
        }

        private static readonly string[] AvatarOnlyPackages =
        {
            "com.vrchat.avatars",
            "nadena.dev.ndmf",
            "nadena.dev.modular-avatar",
            "dev.limitex.avatar-compressor",
            "com.facs01.facs_utilities",
            "vrchat.blackstartx.gesture-manager"
        };

        private static readonly string[] WorldOnlyPackages =
        {
            "com.vrchat.worlds"
        };

        private static double readyAt = -1;

        static WPFMAInstaller()
        {
            EditorApplication.update += WaitForIdle;
        }

        /// <summary>
        /// Runs the startup setup once Unity has finished importing and compiling. Right after WPFMA-SDK is
        /// imported Unity is still busy, and a question window opened then can close unseen.
        /// </summary>
        private static void WaitForIdle()
        {
            if (EditorApplication.isCompiling || EditorApplication.isUpdating || EditorApplication.isPlayingOrWillChangePlaymode)
            {
                readyAt = -1;
                return;
            }
            if (readyAt < 0)
                readyAt = EditorApplication.timeSinceStartup + 1.5;
            if (EditorApplication.timeSinceStartup < readyAt)
                return;
            EditorApplication.update -= WaitForIdle;
            RunStartupSetup();
        }

        /// <summary>The Tools tab's avatar/world choice, for projects that haven't decided yet.</summary>
        internal static void Choose(ProjectKind kind)
        {
            if (kind == ProjectKind.Undecided)
                return;
            WriteProjectValue("kind", kind.ToString());
            cachedKindAt = -1;
            Debug.Log("[WPFMA-SDK] Set up as a " + (kind == ProjectKind.Avatars ? "avatar" : "world") + " project.");
            InstallPackages();
        }

        private static void RunStartupSetup()
        {
            if (SessionState.GetBool(StartupSetupKey, false))
                return;
            SessionState.SetBool(StartupSetupKey, true);

            RepairWpfmaPackageJson();
            UseBothInputSystems();
            RemovePromoAssets();
            RepairMissingLocalDependencies();
            InstallPackages();
            WPFMAHierarchyIcons.ApplyIfEnabled();
        }

        /// <summary>
        /// WPFMA's own package used to list the VRChat avatar SDK as a dependency. World projects don't have it, so
        /// Unity failed to resolve packages and kept asking to restart. VCC installs the VRChat SDK; nothing here needs it listed.
        /// </summary>
        private static void RepairWpfmaPackageJson()
        {
            const string path = "Packages/com.wpfma.sdk/package.json";
            if (!File.Exists(path))
                return;
            string json = File.ReadAllText(path);
            string fixedJson = System.Text.RegularExpressions.Regex.Replace(json, @",\s*""dependencies""\s*:\s*\{[^}]*\}", string.Empty);
            if (fixedJson == json)
                return;
            File.WriteAllText(path, fixedJson);
            Debug.Log("[WPFMA-SDK] Removed the VRChat SDK dependency from WPFMA's package file (it broke world projects).");
            UnityEditor.PackageManager.Client.Resolve();
        }

        /// <summary>
        /// VRChat's world SDK uses Unity's new input system next to the old one, and VRChat's world projects use
        /// "Both". Left on old-only, Unity asks on every new world project to switch to new-only (and restart),
        /// which can break things still on the old system. Only changes old-only; takes effect after a restart.
        /// </summary>
        private static void UseBothInputSystems()
        {
            if (!Directory.Exists("Packages/com.vrchat.worlds"))
                return;
            var settings = System.Linq.Enumerable.FirstOrDefault(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset"));
            if (settings == null)
                return;
            var serialized = new SerializedObject(settings);
            var handler = serialized.FindProperty("activeInputHandler");
            if (handler == null || handler.intValue != 0)
                return;
            handler.intValue = 2;
            serialized.ApplyModifiedPropertiesWithoutUndo();
            AssetDatabase.SaveAssets();
            Debug.Log("[WPFMA-SDK] Set Active Input Handling to Both, like VRChat's world projects. It takes effect next time Unity starts.");
        }

        private static void RepairMissingLocalDependencies()
        {
            var fallbackVersions = new System.Collections.Generic.Dictionary<string, string>
            {
                { "com.vrchat.base", "3.10.4" },
                { "com.vrchat.avatars", "3.10.4" },
                { "com.unity.timeline", "1.7.1" },
                { "com.unity.formats.fbx", "4.2.1" },
                { "com.autodesk.fbx", "4.2.1" }
            };

            var manifestPath = "Packages/manifest.json";
            if (!File.Exists(manifestPath))
                return;

            var manifest = File.ReadAllText(manifestPath);
            foreach (var fallback in fallbackVersions)
            {
                var packagePath = Path.Combine("Packages", fallback.Key, "package.json");
                var localReference = "\"file:" + fallback.Key + "\"";
                if (File.Exists(packagePath) || !manifest.Contains(localReference))
                    continue;

                manifest = manifest.Replace(localReference, "\"" + fallback.Value + "\"");
                Debug.LogWarning($"[WPFMA-SDK] Local package missing; restored registry dependency for {fallback.Key}.");
            }

            File.WriteAllText(manifestPath, manifest);
        }

        private static void RemovePromoAssets()
        {
            bool removedAny = false;

            if (Directory.Exists(PromoFolderPath))
            {
                FileUtil.DeleteFileOrDirectory(PromoFolderPath);
                removedAny = true;
            }

            if (File.Exists(PromoMetaPath))
            {
                FileUtil.DeleteFileOrDirectory(PromoMetaPath);
                removedAny = true;
            }

            if (!removedAny)
                return;

            AssetDatabase.Refresh();
            Debug.Log("[WPFMA-SDK] Removed promotional assets folder.");
        }

        private static void InstallPackages()
        {
            if (!Directory.Exists(PackageSourcesPath)) return;

            var packagesDir = Path.GetFullPath("Packages");
            var kind = DecideProjectKind();
            if (kind == ProjectKind.Undecided)
                return;

            var zipFiles = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Where(
                Directory.GetFiles(PackageSourcesPath, "*.zip"), zip => Belongs(zip, kind)));

            var pending = new System.Collections.Generic.List<string>();
            foreach (var zipPath in zipFiles)
            {
                if (WouldInstall(zipPath, packagesDir) && NeedsNewerUnity(zipPath) == null)
                    pending.Add(Path.GetFileNameWithoutExtension(zipPath));
            }

            if (!ConfirmInstall(pending))
                return;
            var installedPackages = new System.Collections.Generic.List<string>();
            var failed = new System.Collections.Generic.List<string>();
            bool needsRefresh = false;
            RemoveLeftoverStaging(packagesDir);

            int stagingIndex = 0;
            foreach (var zipPath in zipFiles)
            {
                var packageName = Path.GetFileNameWithoutExtension(zipPath);
                var targetPath = Path.Combine(packagesDir, packageName);

                // One package that can't be added must never stop the others (it used to stop the whole setup, which
                // left projects with only some of the VRChat SDK and none of it registered).
                try
                {
                if (!HasPackageJson(zipPath))
                {
                    Debug.LogError($"[WPFMA-SDK] Skipping invalid package archive without package.json: {zipPath}");
                    continue;
                }

                if (File.Exists(Path.Combine(targetPath, "package.json")))
                {
                    installedPackages.Add(packageName);
                    continue;
                }

                if (IsInstalledUnderAnotherFolder(packagesDir, packageName))
                    continue;

                if (IsResolvedFromRegistry(packageName))
                    continue;

                // A package made for a newer Unity than this one would only fail to load (or break the project).
                string required = NeedsNewerUnity(zipPath);
                if (required != null)
                {
                    SkippedForUnity[packageName] = required;
                    Debug.LogWarning("[WPFMA-SDK] Did not add " + packageName + ": it needs Unity " + required + " or newer, and this project is on " +
                                     Application.unityVersion + ". Switch the project to " + required + " in the Creator Companion to get it.");
                    continue;
                }

                // Unpacked next to its final folder under a name that's never longer than it, then moved into place.
                // (The old ".lc-sdk-install-<name>" folder was 16 characters longer, which pushed deep VRChat SDK files
                // past Windows' 260-character path limit in projects with ordinary paths.)
                string stagingPath = Path.Combine(packagesDir, ".wpfma-" + (++stagingIndex));
                if (Directory.Exists(stagingPath))
                    Directory.Delete(stagingPath, true);

                string tooLong;
                if (!Extract(zipPath, stagingPath, targetPath, out tooLong))
                {
                    if (Directory.Exists(stagingPath))
                        Directory.Delete(stagingPath, true);
                    failed.Add(packageName + " (its deepest file would need a " + tooLong + "-character path; Windows allows " + MaxPath + ")");
                    Debug.LogError("[WPFMA-SDK] Could not add " + packageName + ": this project's folder path is too long for it. " +
                                   "Its deepest file would need a " + tooLong + "-character path and Windows allows " + MaxPath + ". " +
                                   "Move the project to a shorter folder (like C:\\VRChat\\MyProject) and open it again.");
                    continue;
                }
                if (!File.Exists(Path.Combine(stagingPath, "package.json")))
                {
                    Directory.Delete(stagingPath, true);
                    Debug.LogError($"[WPFMA-SDK] Package extraction failed; package.json is missing: {stagingPath}");
                    continue;
                }

                if (Directory.Exists(targetPath))
                    Directory.Delete(targetPath, true);

                Directory.Move(stagingPath, targetPath);

                installedPackages.Add(packageName);
                needsRefresh = true;
                Debug.Log($"[WPFMA-SDK] Extracted {packageName} into Packages/");
                }
                catch (System.Exception e)
                {
                    failed.Add(packageName + " (" + e.GetType().Name + ": " + e.Message + ")");
                    Debug.LogError("[WPFMA-SDK] Could not add " + packageName + ": " + e.Message);
                    try
                    {
                        RemoveLeftoverStaging(packagesDir);
                    }
                    catch (System.Exception)
                    {
                    }
                }
            }

            foreach (var packageName in installedPackages)
                EnsureManifestDependency(packageName);

            if (installedPackages.Contains("com.vrchat.worlds"))
                UseBothInputSystems();

            if (needsRefresh)
            {
                AssetDatabase.Refresh();
                Debug.Log(failed.Count == 0
                    ? "[WPFMA-SDK] VRChat SDK & WPFMA-SDK packages unpacked successfully."
                    : "[WPFMA-SDK] Some packages were added, but " + failed.Count + " could not be.");
            }

            if (failed.Count > 0)
                ReportFailed(failed);
        }

        // Windows' classic limit for a file's whole path (folders 248), unless long paths are turned on.
        private const int MaxPath = 259;
        private const int MaxFolderPath = 247;

        // Unity never loads these from a package, so they can be left out if they don't fit.
        private static readonly string[] OptionalFolders = { "Samples~/", "Documentation~/", "Tests~/" };

        private static bool HasPackageJson(string zipPath)
        {
            using (var archive = ZipFile.OpenRead(zipPath))
                return archive.GetEntry("package.json") != null;
        }

        /// <summary>
        /// Unpacks a package into the staging folder. First checks that every file will fit at its final place;
        /// optional folders (samples, docs, tests) that don't are left out, anything else means the package can't
        /// be added here and nothing is unpacked (tooLong says how long the path would be).
        /// </summary>
        private static bool Extract(string zipPath, string stagingPath, string finalPath, out string tooLong)
        {
            tooLong = null;
            string staging = Path.GetFullPath(stagingPath);
            string final = Path.GetFullPath(finalPath);
            // Unity's file code keeps Windows' old path limit even when long paths are turned on in Windows.
            bool limited = Application.platform == RuntimePlatform.WindowsEditor;

            using (var archive = ZipFile.OpenRead(zipPath))
            {
                var skip = new System.Collections.Generic.HashSet<ZipArchiveEntry>();
                int longest = 0;
                foreach (var entry in archive.Entries)
                {
                    string relative = entry.FullName.Replace('\\', '/');
                    bool folder = relative.EndsWith("/");
                    int length = final.Length + 1 + relative.TrimEnd('/').Length;
                    if (!limited || length <= (folder ? MaxFolderPath : MaxPath))
                        continue;
                    if (System.Linq.Enumerable.Any(OptionalFolders, f => relative.StartsWith(f, System.StringComparison.Ordinal)))
                    {
                        skip.Add(entry);
                        continue;
                    }
                    longest = System.Math.Max(longest, length);
                }
                if (longest > 0)
                {
                    tooLong = longest.ToString();
                    return false;
                }

                Directory.CreateDirectory(staging);
                foreach (var entry in archive.Entries)
                {
                    if (skip.Contains(entry))
                        continue;
                    string relative = entry.FullName.Replace('\\', '/');
                    string target = Path.GetFullPath(Path.Combine(staging, relative));
                    // Never write outside the package's own folder.
                    if (!target.StartsWith(staging, System.StringComparison.OrdinalIgnoreCase))
                        continue;
                    if (relative.EndsWith("/"))
                    {
                        Directory.CreateDirectory(target);
                        continue;
                    }
                    Directory.CreateDirectory(Path.GetDirectoryName(target));
                    entry.ExtractToFile(target, true);
                }
                if (skip.Count > 0)
                    Debug.Log("[WPFMA-SDK] Left " + skip.Count + " sample/test file(s) out of " + Path.GetFileName(final) +
                              " because this project's folder path is too long for them. Nothing Unity uses is missing.");
            }
            return true;
        }

        /// <summary>Unpacking folders left behind by an earlier setup that was interrupted.</summary>
        private static void RemoveLeftoverStaging(string packagesDir)
        {
            foreach (var folder in Directory.GetDirectories(packagesDir))
            {
                string name = Path.GetFileName(folder);
                if (name.StartsWith(".lc-sdk-install-", System.StringComparison.Ordinal) || name.StartsWith(".wpfma-", System.StringComparison.Ordinal))
                {
                    try
                    {
                        Directory.Delete(folder, true);
                    }
                    catch (System.Exception)
                    {
                    }
                }
            }
        }

        private static void ReportFailed(System.Collections.Generic.List<string> failed)
        {
            string path = Path.GetFullPath(".");
            string message = "WPFMA-SDK could not add these packages:\n\n   " + string.Join("\n   ", failed.ToArray()) +
                             "\n\nThis project is in:\n   " + path + "  (" + path.Length + " characters)\n\n" +
                             "The VRChat SDK has very deep folders, and with the project this deep they go past Windows' path limit. " +
                             "Move the project to a short folder, like C:\\VRChat\\" + Path.GetFileName(path) + ", open it from there, " +
                             "and the missing packages are added by themselves.";
            Debug.LogError("[WPFMA-SDK] " + message.Replace("\n\n", " ").Replace("\n", " "));
            if (!Application.isBatchMode)
                EditorUtility.DisplayDialog("WPFMA-SDK: setup isn't finished", message, "OK");
        }

        private static bool WouldInstall(string zipPath, string packagesDir)
        {
            var packageName = Path.GetFileNameWithoutExtension(zipPath);

            if (File.Exists(Path.Combine(Path.Combine(packagesDir, packageName), "package.json")))
                return false;

            if (IsInstalledUnderAnotherFolder(packagesDir, packageName))
                return false;

            if (IsResolvedFromRegistry(packageName))
                return false;

            try
            {
                using (var archive = ZipFile.OpenRead(zipPath))
                {
                    if (archive.GetEntry("package.json") == null)
                        return false;
                }
            }
            catch (System.Exception)
            {
                return false;
            }

            return true;
        }

        private static bool ConfirmInstall(System.Collections.Generic.List<string> pending)
        {
            if (pending.Count == 0)
                return true;

            if (!ProjectHasOwnSdk())
                return true;

            if (PromptDeclined)
            {
                Debug.Log("[WPFMA-SDK] Skipping the bundled packages; this project was set to never add them. " +
                          "Use Settings > Package import > Ask again in the WPFMA-SDK panel to change that.");
                return false;
            }

            int choice = ShowInstallPrompt(pending);

            if (choice == 0)
                return true;

            if (choice == 2)
            {
                WriteProjectValue("declined", "true");
                Debug.Log("[WPFMA-SDK] The bundled packages will not be added to this project again.");
            }

            return false;
        }

        internal static int ShowInstallPrompt(System.Collections.Generic.IList<string> pending)
        {
            if (Application.isBatchMode)
                return WPFMAInstallPromptWindow.NotNowChoice;

            try
            {
                return WPFMAInstallPromptWindow.Ask(pending);
            }
            catch (System.Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Install window failed, using a plain dialog instead: " + e.Message);
            }

            var list = string.Join("\n   ", System.Linq.Enumerable.ToArray(pending));
            return EditorUtility.DisplayDialogComplex("WPFMA-SDK",
                "This project already has its own VRChat SDK.\n\n" +
                "WPFMA-SDK ships copies of the packages it needs, and these are missing here:\n\n   " + list +
                "\n\nNothing already installed is replaced - only what is missing would be added. If this " +
                "project is managed by the Creator Companion, you may prefer to add them there instead.",
                "Add what is missing", "Not now", "Never for this project");
        }

        internal const string PanelKindKeyPrefix = "WPFMA.Dev.PanelKind.";

        private static ProjectKind cachedKind;
        private static double cachedKindAt = -1;

        internal static ProjectKind PanelKind
        {
            get
            {
                int forced = EditorPrefs.GetInt(PanelKindKeyPrefix + ProjectKey(), 0);
                if (forced == (int)ProjectKind.Avatars || forced == (int)ProjectKind.Worlds)
                    return (ProjectKind)forced;

                double now = EditorApplication.timeSinceStartup;
                if (cachedKindAt < 0 || now - cachedKindAt > 3.0 || now < cachedKindAt)
                {
                    cachedKind = CurrentKind;
                    cachedKindAt = now;
                }

                return cachedKind;
            }
        }

        internal static ProjectKind PanelKindOverride
        {
            get
            {
                int forced = EditorPrefs.GetInt(PanelKindKeyPrefix + ProjectKey(), 0);
                return forced == (int)ProjectKind.Avatars || forced == (int)ProjectKind.Worlds ? (ProjectKind)forced : ProjectKind.Undecided;
            }
            set
            {
                if (value == ProjectKind.Undecided)
                    EditorPrefs.DeleteKey(PanelKindKeyPrefix + ProjectKey());
                else
                    EditorPrefs.SetInt(PanelKindKeyPrefix + ProjectKey(), (int)value);
                cachedKindAt = -1;
            }
        }

        internal static ProjectKind CurrentKind
        {
            get
            {
                if (HasPackage("com.vrchat.avatars"))
                    return ProjectKind.Avatars;

                if (HasPackage("com.vrchat.worlds"))
                    return ProjectKind.Worlds;

                ProjectKind saved;
                return System.Enum.TryParse(ReadProjectValue("kind"), out saved) ? saved : ProjectKind.Undecided;
            }
        }

        private static ProjectKind DecideProjectKind()
        {
            var kind = CurrentKind;
            if (kind != ProjectKind.Undecided)
                return kind;

            if (Application.isBatchMode)
                return ProjectKind.Undecided;

            try
            {
                kind = WPFMAProjectKindWindow.Ask();
            }
            catch (System.Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Setup window failed, using a plain dialog instead: " + e.Message);
                int choice = EditorUtility.DisplayDialogComplex("WPFMA-SDK",
                    "Is this an avatar project or a world project?\n\n" +
                    "VRChat keeps the two apart, so WPFMA-SDK only installs what fits.",
                    "Avatars", "Worlds", "Decide later");
                kind = choice == 0 ? ProjectKind.Avatars : choice == 1 ? ProjectKind.Worlds : ProjectKind.Undecided;
            }

            if (kind == ProjectKind.Undecided)
            {
                Debug.Log("[WPFMA-SDK] No VRChat SDK installed yet. It will ask again next time Unity starts.");
                return ProjectKind.Undecided;
            }
            WriteProjectValue("kind", kind.ToString());
            Debug.Log("[WPFMA-SDK] Set up as a " + (kind == ProjectKind.Avatars ? "avatar" : "world") + " project.");
            return kind;
        }

        private static bool Belongs(string zipPath, ProjectKind kind)
        {
            string name = Path.GetFileNameWithoutExtension(zipPath);

            bool avatarOnly = System.Array.IndexOf(AvatarOnlyPackages, name) >= 0 || DependsOn(zipPath, "com.vrchat.avatars");
            bool worldOnly = System.Array.IndexOf(WorldOnlyPackages, name) >= 0 || DependsOn(zipPath, "com.vrchat.worlds");

            if (avatarOnly)
                return kind == ProjectKind.Avatars;

            if (worldOnly)
                return kind == ProjectKind.Worlds;

            return true;
        }

        /// <summary>Bundled packages left out because this Unity is older than they need (name -> version needed).</summary>
        internal static readonly System.Collections.Generic.Dictionary<string, string> SkippedForUnity =
            new System.Collections.Generic.Dictionary<string, string>();

        /// <summary>
        /// The Unity version a bundled package says it needs ("unity" plus "unityRelease" in its package.json), when
        /// that is newer than this editor; null when this editor is fine.
        /// </summary>
        internal static string NeedsNewerUnity(string zipPath)
        {
            try
            {
                using (var archive = ZipFile.OpenRead(zipPath))
                {
                    var entry = archive.GetEntry("package.json");
                    if (entry == null)
                        return null;
                    using (var reader = new StreamReader(entry.Open()))
                    {
                        string json = reader.ReadToEnd();
                        var unity = System.Text.RegularExpressions.Regex.Match(json, "\"unity\"\\s*:\\s*\"([^\"]+)\"");
                        if (!unity.Success)
                            return null;
                        var release = System.Text.RegularExpressions.Regex.Match(json, "\"unityRelease\"\\s*:\\s*\"([^\"]+)\"");
                        string required = unity.Groups[1].Value.Trim() + (release.Success ? "." + release.Groups[1].Value.Trim() : string.Empty);
                        return CompareUnityVersions(Application.unityVersion, required) < 0 ? required : null;
                    }
                }
            }
            catch (System.Exception)
            {
                return null;
            }
        }

        /// <summary>Compares Unity versions like "2022.3.6f1" and "2022.3" (missing parts count as the lowest).</summary>
        internal static int CompareUnityVersions(string a, string b)
        {
            var x = UnityVersionParts(a);
            var y = UnityVersionParts(b);
            for (int i = 0; i < x.Length; i++)
                if (x[i] != y[i])
                    return x[i].CompareTo(y[i]);
            return 0;
        }

        private static int[] UnityVersionParts(string version)
        {
            var match = System.Text.RegularExpressions.Regex.Match(version ?? string.Empty, "^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?([abfpcx])?(\\d+)?");
            var parts = new int[5];
            for (int i = 0; i < 3; i++)
                int.TryParse(match.Groups[i + 1].Value, out parts[i]);
            // Alpha < beta < final < patch.
            string type = match.Groups[4].Value;
            parts[3] = type == "a" ? 1 : type == "b" ? 2 : type == "f" || type == "c" ? 3 : type == "p" || type == "x" ? 4 : 0;
            int.TryParse(match.Groups[5].Value, out parts[4]);
            return parts;
        }

        private static bool DependsOn(string zipPath, string package)
        {
            try
            {
                using (var archive = ZipFile.OpenRead(zipPath))
                {
                    var entry = archive.GetEntry("package.json");
                    if (entry == null)
                        return false;

                    using (var reader = new StreamReader(entry.Open()))
                    {
                        string json = reader.ReadToEnd();

                        int at = json.IndexOf("\"vpmDependencies\"", System.StringComparison.Ordinal);
                        if (at < 0)
                            return false;

                        int open = json.IndexOf('{', at);
                        int close = open < 0 ? -1 : json.IndexOf('}', open);
                        if (open < 0 || close < 0)
                            return false;

                        return json.Substring(open, close - open).Contains("\"" + package + "\"");
                    }
                }
            }
            catch (System.Exception)
            {
                return false;
            }
        }

        private static bool HasPackage(string name)
        {
            if (Directory.Exists(Path.Combine("Packages", name)))
                return true;

            if (IsResolvedFromRegistry(name))
                return true;

            var manifestPath = "Packages/manifest.json";
            return File.Exists(manifestPath) && File.ReadAllText(manifestPath).Contains("\"" + name + "\"");
        }

        // Avatar/world choice and "never for this project", kept in the project itself. (They used to be kept
        // per folder path on this PC, so a new project made where an old one was deleted got the old answer.)
        private const string ProjectValuesFile = "ProjectSettings/WPFMAProject.txt";

        private static string ReadProjectValue(string key)
        {
            if (!File.Exists(ProjectValuesFile))
                return null;
            foreach (var line in File.ReadAllLines(ProjectValuesFile))
            {
                int colon = line.IndexOf(':');
                if (colon > 0 && line.Substring(0, colon).Trim() == key)
                    return line.Substring(colon + 1).Trim();
            }
            return null;
        }

        /// <summary>Sets a value; null removes it.</summary>
        private static void WriteProjectValue(string key, string value)
        {
            var lines = File.Exists(ProjectValuesFile)
                ? System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where(File.ReadAllLines(ProjectValuesFile), l => !l.StartsWith(key + ":", System.StringComparison.Ordinal)))
                : new System.Collections.Generic.List<string> { "# WPFMA-SDK setup choices for this project." };
            if (value != null)
                lines.Add(key + ": " + value);
            File.WriteAllLines(ProjectValuesFile, lines);
        }

        private static string ProjectKey()
        {
            unchecked
            {
                uint hash = 2166136261;
                foreach (var c in Application.dataPath.ToLowerInvariant())
                {
                    hash ^= c;
                    hash *= 16777619;
                }

                return hash.ToString("x8");
            }
        }

        private static bool ProjectHasOwnSdk()
        {
            if (Directory.Exists("Packages/com.vrchat.base") || Directory.Exists("Packages/com.vrchat.avatars"))
                return true;

            if (IsResolvedFromRegistry("com.vrchat.base") || IsResolvedFromRegistry("com.vrchat.avatars"))
                return true;

            var manifestPath = "Packages/manifest.json";
            return File.Exists(manifestPath) && File.ReadAllText(manifestPath).Contains("com.vrchat.base");
        }


        internal static bool PromptDeclined
        {
            get { return ReadProjectValue("declined") == "true"; }
        }

        internal static void ResetPrompt()
        {
            WriteProjectValue("declined", null);
            WriteProjectValue("kind", null);
            SessionState.SetBool(StartupSetupKey, false);
            EditorUtility.DisplayDialog("WPFMA-SDK",
                "This project will be asked about the bundled packages again the next time Unity starts.", "OK");
        }

        private static void EnsureManifestDependency(string packageName)
        {
            var manifestPath = "Packages/manifest.json";
            if (!File.Exists(manifestPath))
                return;

            var manifest = File.ReadAllText(manifestPath);
            manifest = RemoveStaleManifestDependency(manifest, packageName);
            if (manifest.Contains("\"" + packageName + "\":"))
                return;

            var version = ReadInstalledPackageVersion(packageName);
            if (string.IsNullOrEmpty(version))
                return;

            var dependenciesMarker = "  \"dependencies\": {\n";
            manifest = manifest.Replace(dependenciesMarker, dependenciesMarker +
                "    \"" + packageName + "\": \"" + version + "\",\n");

            File.WriteAllText(manifestPath, manifest);
        }

        private static string RemoveStaleManifestDependency(string manifest, string packageName)
        {
            if (string.IsNullOrEmpty(manifest))
                return manifest;

            var pattern = "\\s*\"" + System.Text.RegularExpressions.Regex.Escape(packageName) + "\"\\s*:\\s*\"(?:file:)?" + System.Text.RegularExpressions.Regex.Escape(packageName) + "\"\\s*,?\\r?\\n?";
            return System.Text.RegularExpressions.Regex.Replace(manifest, pattern, "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        }

        private static bool IsResolvedFromRegistry(string packageName)
        {
            const string cache = "Library/PackageCache";
            return Directory.Exists(cache) && Directory.GetDirectories(cache, packageName + "@*").Length > 0;
        }

        private static bool IsInstalledUnderAnotherFolder(string packagesDir, string packageName)
        {
            var namePattern = "\"name\"\\s*:\\s*\"" + System.Text.RegularExpressions.Regex.Escape(packageName) + "\"";
            foreach (var folder in Directory.GetDirectories(packagesDir))
            {
                var manifest = Path.Combine(folder, "package.json");
                if (File.Exists(manifest) && System.Text.RegularExpressions.Regex.IsMatch(File.ReadAllText(manifest), namePattern))
                    return true;
            }

            return false;
        }

        private static string ReadInstalledPackageVersion(string packageName)
        {
            var packageJsonPath = Path.Combine("Packages", packageName, "package.json");
            if (!File.Exists(packageJsonPath))
                return null;

            var text = File.ReadAllText(packageJsonPath);
            var match = System.Text.RegularExpressions.Regex.Match(text, "\"version\"\\s*:\\s*\"([^\"]+)\"");
            return match.Success ? match.Groups[1].Value : null;
        }
    }
}
#endif
