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

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
#endif

namespace WPFMA
{
    internal static class WPFMAAnimationPathFixer
    {
        internal const string RemoveChoice = "Remove these curves";

        internal sealed class Broken
        {
            public string Path;
            public int Curves;
            public readonly HashSet<AnimationClip> Clips = new HashSet<AnimationClip>();
            public List<string> Candidates = new List<string>();
            public int Choice;
            public Transform Manual;
            public bool Apply;
            public bool LockedOnly;
            /// <summary>What these paths start from: the avatar, or the object a Modular Avatar merge is set to.</summary>
            public Transform Base;
            /// <summary>Empty for the avatar's own animations; otherwise where they come from.</summary>
            public string From = string.Empty;
        }

        internal sealed class ScanResult
        {
            public GameObject Root;
            public int Controllers;
            public int Clips;
            public int LockedClips;
            public readonly List<Broken> Broken = new List<Broken>();
        }

        internal static GameObject ResolveRoot(GameObject selected)
        {
            if (selected == null || EditorUtility.IsPersistent(selected))
                return null;

#if WPFMA_VRC_AVATARS
            var descriptor = selected.GetComponentInParent<VRCAvatarDescriptor>();
            if (descriptor != null)
                return descriptor.gameObject;
#endif

            var animator = selected.GetComponentInParent<Animator>();
            return animator != null ? animator.gameObject : null;
        }

        internal static ScanResult Scan(GameObject root)
        {
            var result = new ScanResult { Root = root };
            if (root == null)
                return result;

            // Modular Avatar merges count too, each checked from the object its paths start from.
            var sources = WPFMAAvatarAnimations.Sources(root, true);
            result.Controllers = sources.Count;
            result.Clips = sources.SelectMany(s => s.Clips).Distinct().Count();

            var groups = new Dictionary<string, Broken>();
            var counted = new HashSet<AnimationClip>();

            foreach (var source in sources)
            {
                foreach (var clip in source.Clips)
                {
                    bool locked = IsLocked(clip);
                    if (locked && counted.Add(clip))
                        result.LockedClips++;

                    foreach (var binding in Bindings(clip))
                    {
                        if (string.IsNullOrEmpty(binding.path) || source.Base.Find(binding.path) != null)
                            continue;

                        string path = TopMissing(source.Base, binding.path);
                        string key = source.Base.GetInstanceID() + "|" + path;

                        Broken broken;
                        if (!groups.TryGetValue(key, out broken))
                        {
                            broken = new Broken { Path = path, LockedOnly = true, Base = source.Base, From = source.From };
                            groups.Add(key, broken);
                        }

                        broken.Curves++;
                        broken.Clips.Add(clip);
                        if (!locked)
                            broken.LockedOnly = false;
                    }
                }
            }

            foreach (var broken in groups.Values.OrderBy(b => b.From).ThenBy(b => b.Path))
            {
                broken.Candidates = Suggest(broken.Base, broken.Path);
                broken.Choice = broken.Candidates.Count > 0 ? 1 : 0;
                broken.Apply = broken.Candidates.Count > 0 && !broken.LockedOnly;
                result.Broken.Add(broken);
            }

            return result;
        }

        internal static string Fix(ScanResult scan, out int changedClips)
        {
            changedClips = 0;
            var root = scan.Root;
            if (root == null)
                return "The avatar is gone.";

            // Each clip gets the moves of the broken paths it has (a path only means something from its own start object).
            var movesFor = new Dictionary<AnimationClip, List<KeyValuePair<string, string>>>();
            foreach (var broken in scan.Broken.Where(b => b.Apply))
            {
                string target = Target(root.transform, broken);
                if (target == null)
                    continue;

                foreach (var clip in broken.Clips.Where(c => !IsLocked(c)))
                {
                    List<KeyValuePair<string, string>> list;
                    if (!movesFor.TryGetValue(clip, out list))
                        movesFor[clip] = list = new List<KeyValuePair<string, string>>();
                    list.Add(new KeyValuePair<string, string>(broken.Path, target));
                }
            }

            if (movesFor.Count == 0)
                return "Nothing ticked to fix.";

            var clips = movesFor.Keys.ToList();
            int curves = 0;

            Undo.RecordObjects(clips.Cast<UnityEngine.Object>().ToArray(), "Fix animation paths");

            foreach (var clip in clips)
            {
                bool changed = false;
                var moves = movesFor[clip];

                foreach (var binding in AnimationUtility.GetCurveBindings(clip))
                {
                    string moved;
                    if (!Move(binding.path, moves, out moved))
                        continue;

                    var curve = AnimationUtility.GetEditorCurve(clip, binding);
                    AnimationUtility.SetEditorCurve(clip, binding, null);
                    if (moved != null)
                    {
                        var renamed = binding;
                        renamed.path = moved;
                        AnimationUtility.SetEditorCurve(clip, renamed, curve);
                    }

                    changed = true;
                    curves++;
                }

                foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings(clip))
                {
                    string moved;
                    if (!Move(binding.path, moves, out moved))
                        continue;

                    var keys = AnimationUtility.GetObjectReferenceCurve(clip, binding);
                    AnimationUtility.SetObjectReferenceCurve(clip, binding, null);
                    if (moved != null)
                    {
                        var renamed = binding;
                        renamed.path = moved;
                        AnimationUtility.SetObjectReferenceCurve(clip, renamed, keys);
                    }

                    changed = true;
                    curves++;
                }

                if (changed)
                {
                    EditorUtility.SetDirty(clip);
                    changedClips++;
                }
            }

            AssetDatabase.SaveAssets();
            return "Fixed " + curves + (curves == 1 ? " curve" : " curves") + " in " + changedClips +
                   (changedClips == 1 ? " clip." : " clips.");
        }

        internal static string Target(Transform root, Broken broken)
        {
            if (broken.Base != null)
                root = broken.Base;

            if (broken.Manual != null)
                return broken.Manual.IsChildOf(root) ? AnimationUtility.CalculateTransformPath(broken.Manual, root) : null;

            int index = broken.Choice - 1;
            if (index >= 0 && index < broken.Candidates.Count)
                return broken.Candidates[index];

            return broken.Choice == broken.Candidates.Count + 1 ? string.Empty : null;
        }

        internal static bool IsLocked(AnimationClip clip)
        {
            string path = AssetDatabase.GetAssetPath(clip);
            return string.IsNullOrEmpty(path) || AssetImporter.GetAtPath(path) is ModelImporter ||
                   (clip.hideFlags & HideFlags.NotEditable) != 0;
        }

        private static bool Move(string path, List<KeyValuePair<string, string>> moves, out string moved)
        {
            foreach (var move in moves)
            {
                if (path == move.Key)
                {
                    moved = move.Value == string.Empty ? null : move.Value;
                    return true;
                }

                if (path.StartsWith(move.Key + "/", StringComparison.Ordinal))
                {
                    moved = move.Value == string.Empty ? null : move.Value + path.Substring(move.Key.Length);
                    return true;
                }
            }

            moved = null;
            return false;
        }

        /// <summary>The avatar's own controllers (its Animator and descriptor layers), without the add-ons'.</summary>
        internal static List<RuntimeAnimatorController> Controllers(GameObject root)
        {
            return WPFMAAvatarAnimations.Sources(root, false).Select(s => s.Controller).Where(c => c != null).Distinct().ToList();
        }

        private static IEnumerable<EditorCurveBinding> Bindings(AnimationClip clip)
        {
            return AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip));
        }

        private static string TopMissing(Transform root, string path)
        {
            var parts = path.Split('/');
            string current = string.Empty;

            foreach (var part in parts)
            {
                current = current.Length == 0 ? part : current + "/" + part;
                if (root.Find(current) == null)
                    return current;
            }

            return path;
        }

        private static List<string> Suggest(Transform root, string missingPath)
        {
            int slash = missingPath.LastIndexOf('/');
            string leaf = slash >= 0 ? missingPath.Substring(slash + 1) : missingPath;
            string parentPath = slash >= 0 ? missingPath.Substring(0, slash) : string.Empty;

            var all = root.GetComponentsInChildren<Transform>(true).Where(t => t != root).ToList();

            var exact = all.Where(t => t.name == leaf).ToList();
            var matches = exact.Count > 0
                ? exact
                : all.Where(t => Normalize(t.name) == Normalize(leaf)).ToList();

            return matches
                .Select(t => AnimationUtility.CalculateTransformPath(t, root))
                .OrderBy(p => p.StartsWith(parentPath + "/", StringComparison.Ordinal) ? 0 : 1)
                .ThenBy(p => p.Count(c => c == '/'))
                .Take(6)
                .ToList();
        }

        private static string Normalize(string name)
        {
            return new string(name.ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray());
        }
    }

    internal static class WPFMAAnimationPathFixerSection
    {
        private const string PrefKey = "WPFMA.Tools.PathFixerExpanded";

        private static WPFMAAnimationPathFixer.ScanResult scan;
        private static string status;
        private static bool statusIsError;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Animation path fixer", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            if (scan == null || scan.Root == null)
                return "not scanned yet";

            return scan.Broken.Count == 0 ? "no broken paths" : scan.Broken.Count + " broken";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Fix animations that lost their target.", "Finds animations that point at objects that were renamed or moved, so they silently stopped " + "working, and points them at the right object again."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAAnimationPathFixer.ResolveRoot(Selection.activeGameObject);
            if (root == null)
            {
                EditorGUILayout.LabelField(new GUIContent("Select an avatar.", "Select the avatar (or any model with an Animator) in the Hierarchy."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Avatar", root.name, EditorStyles.boldLabel);
                if (GUILayout.Button(scan != null && scan.Root == root ? "Scan again" : "Scan", GUILayout.Width(110f)))
                {
                    var target = root;
                    EditorApplication.delayCall += () =>
                    {
                        scan = WPFMAAnimationPathFixer.Scan(target);
                        status = null;
                    };
                }
            }

            if (scan == null || scan.Root != root)
                return;

            EditorGUILayout.LabelField(
                "Checked " + scan.Clips + " clips in " + scan.Controllers + " controllers." +
                (scan.LockedClips > 0 ? " " + scan.LockedClips + " are inside model files and cannot be changed." : string.Empty),
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (scan.Broken.Count == 0)
            {
                EditorGUILayout.LabelField("Every animated path points at something that exists.",
                    WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
                return;
            }

            foreach (var broken in scan.Broken)
                DrawBroken(root, broken);

            EditorGUILayout.Space(4f);
            int ticked = scan.Broken.Count(b => b.Apply && WPFMAAnimationPathFixer.Target(root.transform, b) != null);

            using (new EditorGUI.DisabledScope(ticked == 0))
            {
                if (GUILayout.Button("Fix " + ticked + " ticked", GUILayout.Height(26f)))
                {
                    var current = scan;
                    EditorApplication.delayCall += () =>
                    {
                        int clips = 0;
                        var touched = WPFMAChangeLog.AssetPaths(current.Broken.Where(b => b.Apply).SelectMany(b => b.Clips)
                            .Where(c => !WPFMAAnimationPathFixer.IsLocked(c)).Distinct().Cast<UnityEngine.Object>()).ToList();
                        status = WPFMAChangeLog.Run("Animation path fixer", "Fix broken paths on '" + current.Root.name + "'", touched, false,
                            () => WPFMAAnimationPathFixer.Fix(current, out clips));
                        statusIsError = clips == 0;
                        Debug.Log("[WPFMA-SDK] Animation path fixer: " + status);
                        scan = WPFMAAnimationPathFixer.Scan(current.Root);
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(statusIsError ? WPFMAToolSection.WarnAmber : WPFMAToolSection.OkGreen));
        }

        private static void DrawBroken(GameObject root, WPFMAAnimationPathFixer.Broken broken)
        {
            EditorGUILayout.Space(3f);

            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(broken.LockedOnly))
                    broken.Apply = EditorGUILayout.Toggle(broken.Apply, GUILayout.Width(16f));

                EditorGUILayout.LabelField(
                    new GUIContent(broken.Path, string.Join("\n", broken.Clips.Select(c => c.name).Take(20).ToArray())),
                    EditorStyles.boldLabel);
            }

            if (!string.IsNullOrEmpty(broken.From))
                EditorGUILayout.LabelField("   from " + broken.From, WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            EditorGUI.indentLevel++;

            EditorGUILayout.LabelField(
                broken.Curves + (broken.Curves == 1 ? " curve" : " curves") + " in " + broken.Clips.Count +
                (broken.Clips.Count == 1 ? " clip" : " clips") +
                (broken.LockedOnly ? " - all inside model files, so they cannot be changed" : string.Empty),
                WPFMAToolSection.Hint(broken.LockedOnly ? WPFMAToolSection.WarnAmber : WPFMAToolSection.FaintText));

            if (!broken.LockedOnly)
            {
                var options = new List<string> { broken.Candidates.Count == 0 ? "No match found - pick below" : "Choose..." };
                options.AddRange(broken.Candidates.Select(c => c.Replace("/", " › ")));
                options.Add(WPFMAAnimationPathFixer.RemoveChoice);

                using (new EditorGUI.DisabledScope(broken.Manual != null))
                {
                    int picked = EditorGUILayout.Popup("Point it at", broken.Choice, options.ToArray());
                    if (picked != broken.Choice)
                    {
                        broken.Choice = picked;
                        broken.Apply = picked > 0;
                    }
                }

                var manual = (Transform)EditorGUILayout.ObjectField("Or this object", broken.Manual, typeof(Transform), true);
                if (manual != broken.Manual)
                {
                    var start = broken.Base != null ? broken.Base : root.transform;
                    broken.Manual = manual != null && manual.IsChildOf(start) ? manual : null;
                    broken.Apply = broken.Manual != null || broken.Choice > 0;
                }
            }

            EditorGUI.indentLevel--;
        }
    }
}
#endif
