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

namespace WPFMA.Vrca
{
    public static class WPFMAReUpload
    {
        private const string ToolPathPrefKey = "WPFMA.ReUpload.ToolPath";
        private const string AcknowledgedPrefKey = "WPFMA.ReUpload.Acknowledged";
        private const string SoftwareRenderingPrefKey = "WPFMA.ReUpload.SoftwareRendering";
        private const string WinePathPrefKey = "WPFMA.ReUpload.WinePath";
        private const string WinePrefixPrefKey = "WPFMA.ReUpload.WinePrefix";

        private const string BundledRelativePath = "Assets/WPFMA-SDK/Tools/ReUpload/ReUpload.exe";

        private static string BundledPath
        {
            get
            {
                string root = Directory.GetParent(Application.dataPath).FullName;
                return Path.Combine(root, BundledRelativePath.Replace('/', Path.DirectorySeparatorChar));
            }
        }

        public static string PlatformBundledPath
        {
            get
            {
                string windows = BundledPath;
                if (Application.platform == RuntimePlatform.WindowsEditor)
                    return windows;

                string native = windows.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
                    ? windows.Substring(0, windows.Length - 4)
                    : windows;

                return File.Exists(native) ? native : windows;
            }
        }

        public static bool HasBundledCopy
        {
            get { return File.Exists(PlatformBundledPath); }
        }

        public static string ToolPath
        {
            get
            {
                string configured = EditorPrefs.GetString(ToolPathPrefKey, string.Empty);
                if (!string.IsNullOrEmpty(configured) && File.Exists(configured))
                    return configured;

                return HasBundledCopy ? PlatformBundledPath : configured;
            }
            set { EditorPrefs.SetString(ToolPathPrefKey, value ?? string.Empty); }
        }

        public static bool ForceSoftwareRendering
        {
            get { return EditorPrefs.GetBool(SoftwareRenderingPrefKey, false); }
            set { EditorPrefs.SetBool(SoftwareRenderingPrefKey, value); }
        }

        public static bool UsesOverride
        {
            get
            {
                string configured = EditorPrefs.GetString(ToolPathPrefKey, string.Empty);
                return !string.IsNullOrEmpty(configured) && File.Exists(configured);
            }
        }

        public static void ClearOverride()
        {
            EditorPrefs.DeleteKey(ToolPathPrefKey);
        }

        public static bool IsConfigured
        {
            get
            {
                string path = ToolPath;
                return !string.IsNullOrEmpty(path) && File.Exists(path);
            }
        }

        public static bool Locate()
        {
            string start = IsConfigured ? Path.GetDirectoryName(ToolPath) : string.Empty;
            string filter = Application.platform == RuntimePlatform.WindowsEditor ? "exe" : string.Empty;
            string picked = EditorUtility.OpenFilePanel("Select the re-upload tool", start, filter);

            if (string.IsNullOrEmpty(picked))
                return false;

            ToolPath = picked;
            Debug.Log("[WPFMA-SDK] Re-upload tool set to " + picked);
            return true;
        }

        public static void Launch(string vrcaPath)
        {
            if (!IsConfigured)
            {
                if (!EditorUtility.DisplayDialog("Re-upload tool",
                        "No re-upload tool is set yet.\n\nPick the executable to use.", "Choose…", "Cancel"))
                    return;

                if (!Locate())
                    return;
            }

            if (string.IsNullOrEmpty(vrcaPath) || !File.Exists(vrcaPath))
            {
                EditorUtility.DisplayDialog("Re-upload", "That .vrca is no longer on disk.", "OK");
                return;
            }

            if (!Acknowledge())
                return;

            try
            {
                string tool = ToolPath;

                var info = new ProcessStartInfo { UseShellExecute = true };
                if (!ConfigureStart(info, tool))
                    return;

                EditorGUIUtility.systemCopyBuffer = vrcaPath;
                Process.Start(info);

                Debug.Log("[WPFMA-SDK] Launched " + Path.GetFileName(tool) +
                          ". The archive path is on the clipboard:\n" + vrcaPath);
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("Re-upload", "Could not start the tool:\n\n" + e.Message, "OK");
                Debug.LogError("[WPFMA-SDK] Could not start the re-upload tool: " + e);
            }
        }

        private static string wineCache;
        private static bool wineChecked;

        public static string WineOverride
        {
            get { return EditorPrefs.GetString(WinePathPrefKey, string.Empty); }
            set
            {
                EditorPrefs.SetString(WinePathPrefKey, value ?? string.Empty);
                wineChecked = false;
            }
        }

        public static string WinePrefix
        {
            get { return EditorPrefs.GetString(WinePrefixPrefKey, string.Empty); }
            set { EditorPrefs.SetString(WinePrefixPrefKey, value ?? string.Empty); }
        }

        public static string Wine
        {
            get
            {
                if (wineChecked)
                    return wineCache;

                wineChecked = true;
                if (Application.platform == RuntimePlatform.WindowsEditor)
                    return wineCache = null;

                string chosen = ExpandPath(WineOverride);
                if (!string.IsNullOrEmpty(chosen))
                    return wineCache = File.Exists(chosen) ? chosen : null;

                foreach (var directory in SearchPath())
                {
                    foreach (var name in new[] { "wine64", "wine" })
                    {
                        try
                        {
                            string candidate = Path.Combine(directory, name);
                            if (File.Exists(candidate))
                                return wineCache = candidate;
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                return wineCache = null;
            }
        }

        internal static string ExpandPath(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                return string.Empty;

            path = Environment.ExpandEnvironmentVariables(path.Trim());

            if (path == "~" || path.StartsWith("~/", StringComparison.Ordinal) ||
                path.StartsWith("~" + Path.DirectorySeparatorChar, StringComparison.Ordinal))
            {
                string home = Environment.GetEnvironmentVariable("HOME");
                if (string.IsNullOrEmpty(home))
                    home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                if (!string.IsNullOrEmpty(home))
                    path = path.Length == 1 ? home : Path.Combine(home, path.Substring(2));
            }

            if (path.Contains("$HOME"))
            {
                string home = Environment.GetEnvironmentVariable("HOME");
                if (!string.IsNullOrEmpty(home))
                    path = path.Replace("$HOME", home);
            }

            return path;
        }

        private static IEnumerable<string> SearchPath()
        {
            string path = Environment.GetEnvironmentVariable("PATH");
            if (!string.IsNullOrEmpty(path))
                foreach (var directory in path.Split(Path.PathSeparator))
                    if (!string.IsNullOrEmpty(directory))
                        yield return directory;

            yield return "/usr/bin";
            yield return "/usr/local/bin";
            yield return "/opt/wine-stable/bin";
            yield return "/opt/wine-staging/bin";
            yield return "/opt/wine-cachyos/bin";

        }

        public static bool RunsThroughWine(string tool)
        {
            return Application.platform != RuntimePlatform.WindowsEditor &&
                   !string.IsNullOrEmpty(tool) &&
                   tool.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
        }

        public static bool ConfigureStart(ProcessStartInfo info, string tool)
        {
            if (info == null || string.IsNullOrEmpty(tool))
                return false;

            info.WorkingDirectory = Path.GetDirectoryName(tool);

            if (!RunsThroughWine(tool))
            {
                info.FileName = tool;
                MakeExecutable(tool);

                if (Application.platform != RuntimePlatform.WindowsEditor)
                    info.UseShellExecute = false;

                return true;
            }

            string wine = Wine;
            if (wine == null)
            {
                string configured = WineOverride;
                if (!string.IsNullOrEmpty(configured))
                {
                    EditorUtility.DisplayDialog("Re-upload",
                        "The Wine build set in Settings does not exist:\n\n" + configured + "\n\n" +
                        "Fix the path, or clear it to search PATH again.",
                        "OK");
                    return false;
                }

                EditorUtility.DisplayDialog("Re-upload",
                    "Only the Windows build of the re-upload tool is here, and this system has no Wine to run " +
                    "it with.\n\n" +
                    "Install Wine and it gets used automatically, or put a native build beside the .exe named " +
                    "\"ReUpload\" with no extension.",
                    "OK");
                return false;
            }

            info.FileName = wine;
            info.ArgumentList.Add(tool);

            info.UseShellExecute = false;
            info.Environment["WINEDEBUG"] = "fixme-all";

            string prefix = ExpandPath(WinePrefix);
            if (!string.IsNullOrEmpty(prefix))
            {
                if (!Path.IsPathRooted(prefix))
                {
                    EditorUtility.DisplayDialog("Re-upload",
                        "The Wine prefix has to be a full path starting at /, not a relative one:" + "\n\n" +
                        prefix + "\n\n" +
                        "For example /home/you/.wine",
                        "OK");
                    return false;
                }

                info.Environment["WINEPREFIX"] = prefix;
            }

            return true;
        }

        public static void MakeExecutable(string tool)
        {
            if (Application.platform == RuntimePlatform.WindowsEditor ||
                string.IsNullOrEmpty(tool) || !File.Exists(tool))
                return;

            try
            {
                using (var chmod = Process.Start(new ProcessStartInfo
                {
                    FileName = "/bin/chmod",
                    Arguments = "+x \"" + tool + "\"",
                    UseShellExecute = false,
                    CreateNoWindow = true
                }))
                {
                    if (chmod != null)
                        chmod.WaitForExit(2000);
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not mark the re-upload tool executable: " + e.Message);
            }
        }

        private static bool Acknowledge()
        {
            if (EditorPrefs.GetBool(AcknowledgedPrefKey, false))
                return true;

            bool ok = EditorUtility.DisplayDialog("Re-upload",
                "This opens an external tool that can publish the avatar to VRChat under the account you sign " +
                "into there.\n\n" +
                "Only do this with avatars you made. Re-uploading someone else's work is not yours to publish, " +
                "and it is the account signing in that carries the consequences.\n\n" +
                "WPFMA-SDK does not sign in, store credentials, or upload anything itself — the tool handles all of " +
                "that in its own window.",
                "I understand", "Cancel");

            if (ok)
                EditorPrefs.SetBool(AcknowledgedPrefKey, true);

            return ok;
        }
    }
}
#endif
