// 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 WPFMAFaceTrackingChecker
    {
        internal sealed class Standard
        {
            public string Name;
            public string Template;
            public string[] Shapes;
        }

        internal sealed class Coverage
        {
            public Standard Standard;
            public SkinnedMeshRenderer Mesh;
            public readonly List<string> Found = new List<string>();
            public readonly List<string> WrongCase = new List<string>();
            public readonly List<string> Missing = new List<string>();

            public float Percent
            {
                get { return Standard.Shapes.Length == 0 ? 0f : Found.Count * 100f / Standard.Shapes.Length; }
            }
        }

        internal sealed class Report
        {
            public GameObject Root;
            public readonly List<Coverage> Coverage = new List<Coverage>();
            public bool HasFaceTrackingParameters;
            public int FaceTrackingParameters;
            public readonly Dictionary<string, int> BrokenShapes = new Dictionary<string, int>();
            public int CheckedClips;

            public Coverage Best
            {
                get { return Coverage.OrderByDescending(c => c.Percent).FirstOrDefault(); }
            }
        }

        internal static readonly Standard ARKit = new Standard
        {
            Name = "ARKit (Perfect Sync)",
            Template = "an ARKit face tracking template",
            Shapes = new[]
            {
                "eyeBlinkLeft", "eyeLookDownLeft", "eyeLookInLeft", "eyeLookOutLeft", "eyeLookUpLeft", "eyeSquintLeft", "eyeWideLeft",
                "eyeBlinkRight", "eyeLookDownRight", "eyeLookInRight", "eyeLookOutRight", "eyeLookUpRight", "eyeSquintRight", "eyeWideRight",
                "jawForward", "jawLeft", "jawRight", "jawOpen",
                "mouthClose", "mouthFunnel", "mouthPucker", "mouthLeft", "mouthRight",
                "mouthSmileLeft", "mouthSmileRight", "mouthFrownLeft", "mouthFrownRight",
                "mouthDimpleLeft", "mouthDimpleRight", "mouthStretchLeft", "mouthStretchRight",
                "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper",
                "mouthPressLeft", "mouthPressRight", "mouthLowerDownLeft", "mouthLowerDownRight",
                "mouthUpperUpLeft", "mouthUpperUpRight",
                "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight",
                "cheekPuff", "cheekSquintLeft", "cheekSquintRight", "noseSneerLeft", "noseSneerRight", "tongueOut"
            }
        };

        internal static readonly Standard Unified = new Standard
        {
            Name = "Unified Expressions",
            Template = "a Unified Expressions template (VRCFT v5+)",
            Shapes = new[]
            {
                "EyeLookOutRight", "EyeLookInRight", "EyeLookUpRight", "EyeLookDownRight",
                "EyeLookOutLeft", "EyeLookInLeft", "EyeLookUpLeft", "EyeLookDownLeft",
                "EyeClosedRight", "EyeClosedLeft", "EyeSquintRight", "EyeSquintLeft", "EyeWideRight", "EyeWideLeft",
                "EyeDilationRight", "EyeDilationLeft", "EyeConstrictRight", "EyeConstrictLeft",
                "BrowPinchRight", "BrowPinchLeft", "BrowLowererRight", "BrowLowererLeft",
                "BrowInnerUpRight", "BrowInnerUpLeft", "BrowOuterUpRight", "BrowOuterUpLeft",
                "NoseSneerRight", "NoseSneerLeft", "NasalDilationRight", "NasalDilationLeft",
                "NasalConstrictRight", "NasalConstrictLeft",
                "CheekSquintRight", "CheekSquintLeft", "CheekPuffRight", "CheekPuffLeft", "CheekSuckRight", "CheekSuckLeft",
                "JawOpen", "MouthClosed", "JawRight", "JawLeft", "JawForward", "JawBackward", "JawClench", "JawMandibleRaise",
                "LipSuckUpperRight", "LipSuckUpperLeft", "LipSuckLowerRight", "LipSuckLowerLeft",
                "LipSuckCornerRight", "LipSuckCornerLeft",
                "LipFunnelUpperRight", "LipFunnelUpperLeft", "LipFunnelLowerRight", "LipFunnelLowerLeft",
                "LipPuckerUpperRight", "LipPuckerUpperLeft", "LipPuckerLowerRight", "LipPuckerLowerLeft",
                "MouthUpperUpRight", "MouthUpperUpLeft", "MouthLowerDownRight", "MouthLowerDownLeft",
                "MouthUpperDeepenRight", "MouthUpperDeepenLeft",
                "MouthUpperRight", "MouthUpperLeft", "MouthLowerRight", "MouthLowerLeft",
                "MouthCornerPullRight", "MouthCornerPullLeft", "MouthCornerSlantRight", "MouthCornerSlantLeft",
                "MouthFrownRight", "MouthFrownLeft", "MouthStretchRight", "MouthStretchLeft",
                "MouthDimpleRight", "MouthDimpleLeft", "MouthRaiserUpper", "MouthRaiserLower",
                "MouthPressRight", "MouthPressLeft", "MouthTightenerRight", "MouthTightenerLeft",
                "TongueOut", "TongueUp", "TongueDown", "TongueRight", "TongueLeft", "TongueRoll",
                "TongueBendDown", "TongueCurlUp", "TongueSquish", "TongueFlat", "TongueTwistRight", "TongueTwistLeft",
                "SoftPalateClose", "ThroatSwallow", "NeckFlexRight", "NeckFlexLeft"
            }
        };

        internal static readonly Standard SRanipal = new Standard
        {
            Name = "SRanipal (Vive)",
            Template = "an SRanipal face tracking template",
            Shapes = new[]
            {
                "Eye_Left_Blink", "Eye_Left_Wide", "Eye_Left_Right", "Eye_Left_Left", "Eye_Left_Up", "Eye_Left_Down",
                "Eye_Right_Blink", "Eye_Right_Wide", "Eye_Right_Right", "Eye_Right_Left", "Eye_Right_Up", "Eye_Right_Down",
                "Eye_Frown", "Eye_Left_Squeeze", "Eye_Right_Squeeze",
                "Jaw_Right", "Jaw_Left", "Jaw_Forward", "Jaw_Open", "Mouth_Ape_Shape",
                "Mouth_Upper_Right", "Mouth_Upper_Left", "Mouth_Lower_Right", "Mouth_Lower_Left",
                "Mouth_Upper_Overturn", "Mouth_Lower_Overturn", "Mouth_Pout",
                "Mouth_Smile_Right", "Mouth_Smile_Left", "Mouth_Sad_Right", "Mouth_Sad_Left",
                "Cheek_Puff_Right", "Cheek_Puff_Left", "Cheek_Suck",
                "Mouth_Upper_UpRight", "Mouth_Upper_UpLeft", "Mouth_Lower_DownRight", "Mouth_Lower_DownLeft",
                "Mouth_Upper_Inside", "Mouth_Lower_Inside", "Mouth_Lower_Overlay",
                "Tongue_LongStep1", "Tongue_LongStep2", "Tongue_Down", "Tongue_Up", "Tongue_Right", "Tongue_Left",
                "Tongue_Roll", "Tongue_UpLeft_Morph", "Tongue_UpRight_Morph", "Tongue_DownLeft_Morph", "Tongue_DownRight_Morph"
            }
        };

        internal static readonly Standard[] Standards = { Unified, ARKit, SRanipal };

        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 Report Check(GameObject root)
        {
            var report = new Report { Root = root };
            if (root == null)
                return report;

            var renderers = root.GetComponentsInChildren<SkinnedMeshRenderer>(true)
                .Where(r => r.sharedMesh != null && r.sharedMesh.blendShapeCount > 0)
                .ToList();

            foreach (var standard in Standards)
            {
                Coverage best = null;

                foreach (var renderer in renderers)
                {
                    var names = Names(renderer.sharedMesh);
                    var lower = new Dictionary<string, string>();
                    foreach (var name in names)
                    {
                        string key = name.ToLowerInvariant();
                        if (!lower.ContainsKey(key))
                            lower.Add(key, name);
                    }

                    var coverage = new Coverage { Standard = standard, Mesh = renderer };
                    foreach (var shape in standard.Shapes)
                    {
                        string actual;
                        if (names.Contains(shape))
                            coverage.Found.Add(shape);
                        else if (lower.TryGetValue(shape.ToLowerInvariant(), out actual))
                            coverage.WrongCase.Add(actual + " → " + shape);
                        else
                            coverage.Missing.Add(shape);
                    }

                    if (best == null || coverage.Found.Count + coverage.WrongCase.Count > best.Found.Count + best.WrongCase.Count)
                        best = coverage;
                }

                if (best != null && best.Found.Count + best.WrongCase.Count > 0)
                    report.Coverage.Add(best);
            }

#if WPFMA_VRC_AVATARS
            var descriptor = root.GetComponent<VRCAvatarDescriptor>();
            if (descriptor != null && descriptor.expressionParameters != null && descriptor.expressionParameters.parameters != null)
            {
                report.FaceTrackingParameters = descriptor.expressionParameters.parameters
                    .Count(p => p != null && p.name != null && (p.name.StartsWith("v2/") || p.name.StartsWith("FT/v2/")));
                report.HasFaceTrackingParameters = report.FaceTrackingParameters > 0;
            }

            CheckAnimatedShapes(root, descriptor, report);
#endif

            return report;
        }

#if WPFMA_VRC_AVATARS
        private static void CheckAnimatedShapes(GameObject root, VRCAvatarDescriptor descriptor, Report report)
        {
            // The avatar's layers and Modular Avatar merges, each read from the object its paths start from.
            var sources = WPFMAAvatarAnimations.Sources(root, true).Where(s => s.Controller != null || s.Motion != null).ToList();
            report.CheckedClips = sources.SelectMany(s => s.Clips).Distinct().Count();

            var shapeCache = new Dictionary<string, HashSet<string>>();

            foreach (var source in sources)
            foreach (var clip in source.Clips)
            {
                foreach (var binding in AnimationUtility.GetCurveBindings(clip))
                {
                    if (binding.type != typeof(SkinnedMeshRenderer) || !binding.propertyName.StartsWith("blendShape."))
                        continue;

                    HashSet<string> shapes;
                    string key = source.Base.GetInstanceID() + "|" + binding.path;
                    if (!shapeCache.TryGetValue(key, out shapes))
                    {
                        var target = source.Base.Find(binding.path);
                        var renderer = target != null ? target.GetComponent<SkinnedMeshRenderer>() : null;
                        shapes = renderer != null && renderer.sharedMesh != null ? Names(renderer.sharedMesh) : null;
                        shapeCache[key] = shapes;
                    }

                    if (shapes == null)
                        continue;

                    string shape = binding.propertyName.Substring("blendShape.".Length);
                    if (shapes.Contains(shape))
                        continue;

                    int count;
                    report.BrokenShapes.TryGetValue(shape, out count);
                    report.BrokenShapes[shape] = count + 1;
                }
            }
        }
#endif

        private static HashSet<string> Names(Mesh mesh)
        {
            var names = new HashSet<string>(StringComparer.Ordinal);
            for (int i = 0; i < mesh.blendShapeCount; i++)
                names.Add(mesh.GetBlendShapeName(i));
            return names;
        }
    }

    internal static class WPFMAFaceTrackingSection
    {
        private const string PrefKey = "WPFMA.Tools.FaceTrackingExpanded";

        private static WPFMAFaceTrackingChecker.Report report;
        private static readonly HashSet<string> openLists = new HashSet<string>();

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

            WPFMAToolSection.Draw(sectionStyle, "Face tracking checker", Detail(), PrefKey, Body);
        }

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

            var best = report.Best;
            return best == null ? "no face tracking shapes" : best.Standard.Name + " " + Mathf.RoundToInt(best.Percent) + "%";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Check face tracking blendshapes.", "Checks which face tracking standard the avatar's blendshapes follow, how complete it is, and which " + "names are off. Templates are case-sensitive, so a wrong capital letter breaks a shape."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAFaceTrackingChecker.ResolveRoot(Selection.activeGameObject);
            if (root == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

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

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

            if (report.Coverage.Count == 0)
            {
                EditorGUILayout.LabelField(new GUIContent("No face tracking shapes found.", "No ARKit, Unified Expressions or SRanipal blendshapes found. This avatar needs face tracking shapes " + "made in Blender before any template will work."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            }

            foreach (var coverage in report.Coverage.OrderByDescending(c => c.Percent))
                DrawCoverage(coverage);

            var best = report.Best;
            if (best != null && best.Percent >= 60f)
            {
                EditorGUILayout.LabelField(
                    "Best fit: " + best.Standard.Template + ", on '" + best.Mesh.name + "'.",
                    WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            }

            EditorGUILayout.Space(4f);
            EditorGUILayout.LabelField(
                report.HasFaceTrackingParameters
                    ? "Face tracking parameters are on the avatar (" + report.FaceTrackingParameters + " found), so a template is already installed."
                    : "No face tracking parameters on the avatar yet, so no template is installed.",
                WPFMAToolSection.Hint(report.HasFaceTrackingParameters ? WPFMAToolSection.OkGreen : WPFMAToolSection.FaintText));

            if (report.BrokenShapes.Count > 0)
            {
                EditorGUILayout.Space(4f);
                EditorGUILayout.LabelField(
                    report.BrokenShapes.Count + " blendshapes are animated but do not exist on their mesh - those " +
                    "animations do nothing. Common after a rip or a mesh re-export.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                DrawList("broken", "Show them", report.BrokenShapes
                    .OrderByDescending(p => p.Value)
                    .Select(p => p.Key + "  (" + p.Value + (p.Value == 1 ? " curve)" : " curves)"))
                    .ToList());
            }
            else if (report.CheckedClips > 0)
            {
                EditorGUILayout.LabelField("Every animated blendshape exists on its mesh (" + report.CheckedClips + " clips checked).",
                    WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            }
        }

        private static void DrawCoverage(WPFMAFaceTrackingChecker.Coverage coverage)
        {
            EditorGUILayout.Space(3f);

            float percent = coverage.Percent;
            var color = percent >= 95f ? WPFMAToolSection.OkGreen
                : percent >= 60f ? WPFMAToolSection.AccentBlue
                : WPFMAToolSection.WarnAmber;

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(coverage.Standard.Name, EditorStyles.boldLabel, GUILayout.Width(170f));
                var bar = GUILayoutUtility.GetRect(0f, 14f, GUILayout.ExpandWidth(true));
                bar.y += 3f;
                EditorGUI.DrawRect(bar, WPFMAToolSection.ToolbarBackground);
                EditorGUI.DrawRect(new Rect(bar.x, bar.y, bar.width * percent / 100f, bar.height), color);
                EditorGUILayout.LabelField(coverage.Found.Count + " / " + coverage.Standard.Shapes.Length,
                    WPFMAToolSection.Hint(color), GUILayout.Width(70f));
            }

            EditorGUILayout.LabelField("On '" + coverage.Mesh.name + "'.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (coverage.WrongCase.Count > 0)
            {
                EditorGUILayout.LabelField(
                    coverage.WrongCase.Count + " have the right name but the wrong capitals, so templates will not find them.",
                    WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                DrawList(coverage.Standard.Name + "case", "Show them", coverage.WrongCase);
            }

            if (coverage.Missing.Count > 0 && coverage.Missing.Count < coverage.Standard.Shapes.Length)
                DrawList(coverage.Standard.Name + "missing", "Missing (" + coverage.Missing.Count + ")", coverage.Missing);
        }

        private static void DrawList(string key, string label, List<string> items)
        {
            bool open = openLists.Contains(key);
            bool now = EditorGUILayout.Foldout(open, label, true);
            if (now != open)
            {
                if (now)
                    openLists.Add(key);
                else
                    openLists.Remove(key);
            }

            if (!now)
                return;

            EditorGUILayout.SelectableLabel(string.Join(", ", items.ToArray()),
                new GUIStyle(EditorStyles.wordWrappedMiniLabel) { normal = { textColor = WPFMAToolSection.MetaText } },
                GUILayout.MinHeight(16f * Mathf.Max(1, Mathf.CeilToInt(items.Count / 4f))));
        }
    }
}
#endif
