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

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

namespace WPFMA
{
#if WPFMA_VRC_AVATARS
    /// <summary>
    /// What each PhysBone really costs (bones it moves, colliders it checks against), and the settings that cost
    /// something for nothing: "Is Animated" on bones nothing animates, empty collider slots, PhysBones with no bones
    /// to move, and colliders no PhysBone uses.
    /// </summary>
    internal static class WPFMAPhysBoneOptimizer
    {
        internal sealed class Bone
        {
            public VRCPhysBone Component;
            public int Transforms;
            public int Colliders;
            public int Checks;
            public bool WastedAnimated;
            public int EmptyColliderSlots;
            public bool MovesNothing;
        }

        internal sealed class Report
        {
            public GameObject Root;
            public readonly List<Bone> Bones = new List<Bone>();
            public readonly List<VRCPhysBoneCollider> UnusedColliders = new List<VRCPhysBoneCollider>();

            public int Transforms { get { return Bones.Sum(b => b.Transforms); } }
            public int Checks { get { return Bones.Sum(b => b.Checks); } }
            public int WastedAnimated { get { return Bones.Count(b => b.WastedAnimated); } }
            public int EmptySlots { get { return Bones.Sum(b => b.EmptyColliderSlots); } }
            public int MovesNothing { get { return Bones.Count(b => b.MovesNothing); } }

            public int Fixable
            {
                get { return WastedAnimated + (EmptySlots > 0 ? Bones.Count(b => b.EmptyColliderSlots > 0) : 0) + MovesNothing + UnusedColliders.Count; }
            }
        }

        internal sealed class Fixes
        {
            public bool Animated = true;
            public bool EmptySlots = true;
            public bool MovesNothing = true;
            public bool UnusedColliders = true;
        }

        internal static Report Analyze(GameObject root)
        {
            var report = new Report { Root = root };
            if (root == null)
                return report;

            var physBones = root.GetComponentsInChildren<VRCPhysBone>(true);
            var animated = AnimatedTransforms(root);

            foreach (var physBone in physBones)
            {
                var start = physBone.GetRootTransform();
                var chain = Chain(start, physBone.ignoreTransforms);
                bool endpoint = physBone.endpointPosition != Vector3.zero;
                int leaves = endpoint ? chain.Count(t => t.childCount == 0 || t.Cast<Transform>().All(c => !chain.Contains(c))) : 0;

                var bone = new Bone
                {
                    Component = physBone,
                    Transforms = chain.Count + leaves,
                    Colliders = physBone.colliders != null ? physBone.colliders.Count(c => c != null) : 0,
                    EmptyColliderSlots = physBone.colliders != null ? physBone.colliders.Count(c => c == null) : 0,
                    MovesNothing = chain.Count <= 1 && !endpoint
                };
                bone.Checks = bone.Transforms * bone.Colliders;
                bone.WastedAnimated = physBone.isAnimated && !chain.Any(animated.Contains);
                report.Bones.Add(bone);
            }

            var used = new HashSet<VRCPhysBoneColliderBase>(physBones.Where(p => p.colliders != null).SelectMany(p => p.colliders).Where(c => c != null));
            var addOnRefs = AddOnReferences(root);
            foreach (var collider in root.GetComponentsInChildren<VRCPhysBoneCollider>(true))
                if (!used.Contains(collider) && !addOnRefs.Contains(collider))
                    report.UnusedColliders.Add(collider);

            report.Bones.Sort((a, b) => b.Checks != a.Checks ? b.Checks.CompareTo(a.Checks) : b.Transforms.CompareTo(a.Transforms));
            return report;
        }

        /// <summary>The bones a PhysBone moves: its root and everything below, minus the ignored branches.</summary>
        private static HashSet<Transform> Chain(Transform start, List<Transform> ignored)
        {
            var chain = new HashSet<Transform>();
            if (start == null)
                return chain;

            var skip = new HashSet<Transform>((ignored ?? new List<Transform>()).Where(t => t != null));
            var stack = new Stack<Transform>();
            stack.Push(start);
            while (stack.Count > 0)
            {
                var current = stack.Pop();
                if (skip.Contains(current))
                    continue;
                chain.Add(current);
                foreach (Transform child in current)
                    stack.Push(child);
            }
            return chain;
        }

        /// <summary>Transforms something moves besides PhysBones: animations (the avatar's and the add-ons') and constraints.</summary>
        private static HashSet<Transform> AnimatedTransforms(GameObject root)
        {
            var moved = new HashSet<Transform>();

            foreach (var source in WPFMAAvatarAnimations.Sources(root, true))
                foreach (var clip in source.Clips)
                    AddMoved(source.Base, clip, moved);

            foreach (var clip in WPFMAAvatarAnimations.Use(root).Clips)
                AddMoved(root.transform, clip, moved);

            foreach (var constraint in root.GetComponentsInChildren<UnityEngine.Animations.IConstraint>(true))
                moved.Add(((Component)constraint).transform);
            foreach (var constraint in root.GetComponentsInChildren<VRCConstraintBase>(true))
                moved.Add(constraint.transform);

            return moved;
        }

        private static void AddMoved(Transform start, AnimationClip clip, HashSet<Transform> moved)
        {
            foreach (var binding in AnimationUtility.GetCurveBindings(clip))
            {
                if (binding.type != typeof(Transform))
                    continue;
                var target = start.Find(binding.path);
                if (target != null)
                    moved.Add(target);
            }
        }

        private static HashSet<Object> AddOnReferences(GameObject root)
        {
            var refs = new HashSet<Object>();
            foreach (var component in root.GetComponentsInChildren<Component>(true))
            {
                if (!WPFMAAvatarAnimations.IsAddOn(component))
                    continue;
                var property = new SerializedObject(component).GetIterator();
                int guard = 0;
                while (property.Next(true) && guard++ < 20000)
                    if (property.propertyType == SerializedPropertyType.ObjectReference && property.objectReferenceValue != null)
                        refs.Add(property.objectReferenceValue);
            }
            return refs;
        }

        internal static string Apply(Report report, Fixes fixes)
        {
            Undo.SetCurrentGroupName("Optimize PhysBones");
            int group = Undo.GetCurrentGroup();
            int animated = 0, slots = 0, removed = 0, colliders = 0;

            foreach (var bone in report.Bones)
            {
                var physBone = bone.Component;
                if (physBone == null)
                    continue;

                if (fixes.MovesNothing && bone.MovesNothing)
                {
                    Undo.DestroyObjectImmediate(physBone);
                    removed++;
                    continue;
                }

                if (fixes.Animated && bone.WastedAnimated)
                {
                    Undo.RecordObject(physBone, "Optimize PhysBones");
                    physBone.isAnimated = false;
                    animated++;
                }

                if (fixes.EmptySlots && bone.EmptyColliderSlots > 0)
                {
                    Undo.RecordObject(physBone, "Optimize PhysBones");
                    slots += physBone.colliders.RemoveAll(c => c == null);
                }

                if (physBone != null)
                {
                    EditorUtility.SetDirty(physBone);
                    PrefabUtility.RecordPrefabInstancePropertyModifications(physBone);
                }
            }

            if (fixes.UnusedColliders)
            {
                foreach (var collider in report.UnusedColliders)
                {
                    if (collider == null)
                        continue;
                    Undo.DestroyObjectImmediate(collider);
                    colliders++;
                }
            }

            Undo.CollapseUndoOperations(group);

            var done = new List<string>();
            if (animated > 0)
                done.Add("turned off Is Animated on " + animated);
            if (slots > 0)
                done.Add("removed " + slots + " empty collider slot(s)");
            if (removed > 0)
                done.Add("removed " + removed + " PhysBone(s) that moved nothing");
            if (colliders > 0)
                done.Add("removed " + colliders + " unused collider(s)");
            return done.Count == 0 ? "Nothing to fix." : "PhysBones: " + string.Join(", ", done.ToArray()) + ".";
        }
    }
#endif

    internal static class WPFMAPhysBoneOptimizerSection
    {
        private const string PrefKey = "WPFMA.Tools.PhysBoneOptimizerExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;

            WPFMAToolSection.Draw(sectionStyle, "PhysBone optimizer", Detail(), PrefKey, Body);
        }

#if !WPFMA_VRC_AVATARS
        private static string Detail()
        {
            return "needs the avatar SDK";
        }

        private static void Body()
        {
            EditorGUILayout.HelpBox("This needs the VRChat avatar SDK, which is not in this project yet.", MessageType.Info);
        }
#else
        private static WPFMAPhysBoneOptimizer.Report report;
        private static readonly WPFMAPhysBoneOptimizer.Fixes Fixes = new WPFMAPhysBoneOptimizer.Fixes();
        private static string status;
        private static Vector2 scroll;

        private static string Detail()
        {
            if (report == null || report.Root == null)
                return "not checked yet";
            return report.Bones.Count + " PhysBone(s), " + report.Checks.ToString("N0") + " collision checks";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("PhysBone cost, and quick fixes.", "Shows what each PhysBone really costs - the bones it moves and the collision checks it does every frame - " + "and fixes the settings that cost something for nothing."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var active = Selection.activeGameObject;
            var avatar = active != null && !EditorUtility.IsPersistent(active) ? active.GetComponentInParent<VRCAvatarDescriptor>() : null;
            if (avatar == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Avatar", avatar.name, EditorStyles.boldLabel);
                if (GUILayout.Button(report != null && report.Root == avatar.gameObject ? "Check again" : "Check", GUILayout.Width(110f)))
                {
                    var target = avatar.gameObject;
                    EditorApplication.delayCall += () =>
                    {
                        report = WPFMAPhysBoneOptimizer.Analyze(target);
                        status = null;
                    };
                }
            }

            if (report == null || report.Root != avatar.gameObject)
                return;

            EditorGUILayout.LabelField(
                report.Bones.Count + " PhysBone(s) moving about " + report.Transforms + " bones, about " + report.Checks.ToString("N0") +
                " collision checks a frame.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (report.Bones.Count > 0)
            {
                EditorGUILayout.Space(2f);
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField("PhysBone", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                    EditorGUILayout.LabelField("Bones", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(44f));
                    EditorGUILayout.LabelField("Checks", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(52f));
                    GUILayout.Space(54f);
                }

                scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(200f));
                foreach (var bone in report.Bones)
                {
                    if (bone.Component == null)
                        continue;
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        string flags = (bone.MovesNothing ? "  moves nothing" : string.Empty) +
                                       (bone.WastedAnimated ? "  Is Animated not needed" : string.Empty) +
                                       (bone.EmptyColliderSlots > 0 ? "  empty collider slots" : string.Empty);
                        EditorGUILayout.LabelField(new GUIContent(bone.Component.name + flags, bone.Component.name),
                            WPFMAToolSection.Hint(flags.Length > 0 ? WPFMAToolSection.WarnAmber : WPFMAToolSection.MetaText));
                        EditorGUILayout.LabelField(bone.Transforms.ToString(), WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(44f));
                        EditorGUILayout.LabelField(bone.Checks.ToString("N0"), WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(52f));
                        if (GUILayout.Button("Select", EditorStyles.miniButton, GUILayout.Width(50f)))
                        {
                            Selection.activeObject = bone.Component.gameObject;
                            EditorGUIUtility.PingObject(bone.Component.gameObject);
                        }
                    }
                }
                EditorGUILayout.EndScrollView();
            }

            EditorGUILayout.Space(4f);
            if (report.Fixable == 0)
            {
                EditorGUILayout.LabelField(new GUIContent("Nothing wasted.", "No wasted PhysBone settings found. To cut more, lower the bone count or the colliders on the heaviest ones."), WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            }
            else
            {
                if (report.WastedAnimated > 0)
                    Fixes.Animated = EditorGUILayout.ToggleLeft(new GUIContent("Turn off unneeded Is Animated (" + report.WastedAnimated + ")",
                        "Nothing animates these PhysBones' bones, and Is Animated makes them work harder every frame."), Fixes.Animated);
                if (report.EmptySlots > 0)
                    Fixes.EmptySlots = EditorGUILayout.ToggleLeft("Remove " + report.EmptySlots + " empty collider slot(s)", Fixes.EmptySlots);
                if (report.MovesNothing > 0)
                    Fixes.MovesNothing = EditorGUILayout.ToggleLeft("Remove " + report.MovesNothing + " PhysBone(s) with no bones to move", Fixes.MovesNothing);
                if (report.UnusedColliders.Count > 0)
                    Fixes.UnusedColliders = EditorGUILayout.ToggleLeft("Remove " + report.UnusedColliders.Count + " collider(s) no PhysBone uses", Fixes.UnusedColliders);

                if (GUILayout.Button("Fix ticked", GUILayout.Height(26f)))
                {
                    var current = report;
                    EditorApplication.delayCall += () =>
                    {
                        status = WPFMAChangeLog.Run("PhysBone optimizer", "Optimize PhysBones on '" + current.Root.name + "'", null, true,
                            () => WPFMAPhysBoneOptimizer.Apply(current, Fixes));
                        Debug.Log("[WPFMA-SDK] " + status);
                        report = WPFMAPhysBoneOptimizer.Analyze(current.Root);
                    };
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Close to VRChat's count.", "Bones and checks are close to VRChat's count, not exact. Performance rank shows VRChat's own numbers."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }
#endif
    }
}
#endif
