// 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 UnityEditor;
using UnityEngine;

namespace WPFMA.Vrca
{
    [InitializeOnLoad]
    internal static class WPFMAFacsAutoFix
    {
        private const string DonePrefPrefix = "WPFMA.FacsAutoFix.Done.";
        private const string ExportFolderPrefKey = "WPFMA.VrcaRipper.ExportFolder";
        private const string DefaultExportFolder = "Assets/WPFMA-SDK/Rips";
        private const string ApiTypeName = "FACS01.Utilities.FixAnimationsApi";

        private static readonly HashSet<int> Pending = new HashSet<int>();
        private static bool warnedMissing;

        static WPFMAFacsAutoFix()
        {
            ObjectChangeEvents.changesPublished += OnChangesPublished;
        }

        private static void OnChangesPublished(ref ObjectChangeEventStream stream)
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode)
                return;

            bool queued = false;
            for (int i = 0; i < stream.length; i++)
            {
                if (stream.GetEventType(i) != ObjectChangeKind.CreateGameObjectHierarchy)
                    continue;

                CreateGameObjectHierarchyEventArgs created;
                stream.GetCreateGameObjectHierarchyEvent(i, out created);
                if (Pending.Add(created.instanceId))
                    queued = true;
            }

            if (queued)
                EditorApplication.delayCall += ProcessPending;
        }

        private static void ProcessPending()
        {
            var ids = Pending.ToArray();
            Pending.Clear();

            foreach (var id in ids)
            {
                var go = EditorUtility.InstanceIDToObject(id) as GameObject;
                if (go == null || !IsRippedAvatar(go))
                    continue;

                string guid = PrefabGuid(go);
                if (string.IsNullOrEmpty(guid) || EditorPrefs.GetBool(DonePrefPrefix + guid, false))
                    continue;

                if (Run(go, false))
                    EditorPrefs.SetBool(DonePrefPrefix + guid, true);
            }
        }

        private static bool IsRippedAvatar(GameObject go)
        {
            if (!PrefabUtility.IsAnyPrefabInstanceRoot(go))
                return false;

            string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go);
            if (string.IsNullOrEmpty(assetPath))
                return false;

            string exportFolder = EditorPrefs.GetString(ExportFolderPrefKey, DefaultExportFolder);
            if (string.IsNullOrEmpty(exportFolder))
                exportFolder = DefaultExportFolder;
            exportFolder = exportFolder.Replace('\\', '/').TrimEnd('/') + "/";

            if (!assetPath.Replace('\\', '/').StartsWith(exportFolder, StringComparison.OrdinalIgnoreCase))
                return false;

            return HasAvatarDescriptor(go) || go.GetComponent<Animator>() != null;
        }

        private static bool HasAvatarDescriptor(GameObject go)
        {
            return go.GetComponents<Component>().Any(c => c != null && c.GetType().Name == "VRCAvatarDescriptor");
        }

        private static GameObject AvatarRootOf(GameObject go)
        {
            for (var t = go.transform; t != null; t = t.parent)
            {
                if (HasAvatarDescriptor(t.gameObject))
                    return t.gameObject;
            }
            return null;
        }

        private static string PrefabGuid(GameObject go)
        {
            string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go);
            return string.IsNullOrEmpty(assetPath) ? null : AssetDatabase.AssetPathToGUID(assetPath);
        }

        private static bool Run(GameObject avatar, bool manual)
        {
            var api = FindApi();
            if (api == null)
            {
                if (manual || !warnedMissing)
                    Debug.LogWarning("[WPFMA-SDK] Fix Animations was skipped: the bundled FACS Utilities copy is not installed.");
                warnedMissing = true;
                return false;
            }

            try
            {
                var results = api.Invoke(null, new object[] { avatar }) as string;
                Debug.Log("[WPFMA-SDK] Fix Animations ran on '" + avatar.name + "'" +
                          (string.IsNullOrEmpty(results) ? ": nothing to scan." : "." + results) +
                          " Details are in the FACS messages above.", avatar);
                return true;
            }
            catch (Exception e)
            {
                var inner = e.InnerException ?? e;
                Debug.LogError("[WPFMA-SDK] Fix Animations failed on '" + avatar.name + "': " + inner, avatar);
                return false;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        private static System.Reflection.MethodInfo FindApi()
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var type = assembly.GetType(ApiTypeName, false);
                if (type == null)
                    continue;

                var method = type.GetMethod("Run", new[] { typeof(GameObject) });
                if (method != null)
                    return method;
            }
            return null;
        }
    }
}
#endif
