// 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
#if WPFMA_VRC_AVATARS
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Avatars.ScriptableObjects;

namespace WPFMA
{
    internal static class WPFMAAvatarSetup
    {
        internal sealed class Request
        {
            public GameObject Root;
            public string Folder;
            public bool ReplaceExisting;
            public bool ViewFromEyes = true;
            public bool LipSync = true;
            public bool EyeLook = true;
        }

        internal sealed class Result
        {
            public bool Success;
            public string Message;
            public readonly List<string> Notes = new List<string>();
            public VRCAvatarDescriptor Descriptor;
        }

        private static readonly VRCAvatarDescriptor.AnimLayerType[] BaseLayers =
        {
            VRCAvatarDescriptor.AnimLayerType.Base,
            VRCAvatarDescriptor.AnimLayerType.Additive,
            VRCAvatarDescriptor.AnimLayerType.Gesture,
            VRCAvatarDescriptor.AnimLayerType.Action,
            VRCAvatarDescriptor.AnimLayerType.FX
        };

        private static readonly VRCAvatarDescriptor.AnimLayerType[] SpecialLayers =
        {
            VRCAvatarDescriptor.AnimLayerType.Sitting,
            VRCAvatarDescriptor.AnimLayerType.TPose,
            VRCAvatarDescriptor.AnimLayerType.IKPose
        };

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

            var existing = selected.GetComponentInParent<VRCAvatarDescriptor>();
            if (existing != null)
                return existing.gameObject;

            var outermost = PrefabUtility.GetOutermostPrefabInstanceRoot(selected);
            return outermost != null ? outermost : selected;
        }

        internal static ModelImporter SourceModel(GameObject root)
        {
            if (root == null)
                return null;

            var source = EditorUtility.IsPersistent(root) ? root : PrefabUtility.GetCorrespondingObjectFromOriginalSource(root);
            string path = source != null ? AssetDatabase.GetAssetPath(source) : null;
            return string.IsNullOrEmpty(path) ? null : AssetImporter.GetAtPath(path) as ModelImporter;
        }

        internal static bool IsHumanoid(GameObject root)
        {
            var animator = root != null ? root.GetComponent<Animator>() : null;
            return animator != null && animator.avatar != null && animator.isHuman;
        }

        internal static bool HasEyes(GameObject root)
        {
            if (!IsHumanoid(root))
                return false;

            var animator = root.GetComponent<Animator>();
            return animator.GetBoneTransform(HumanBodyBones.LeftEye) != null &&
                   animator.GetBoneTransform(HumanBodyBones.RightEye) != null;
        }

        /// <summary>
        /// Where the view position goes: between the eyes and a little in front of them, about where the eyelids are.
        /// Exactly between the eye bones is the middle of the eyeballs, inside the head. Null without eye bones.
        /// </summary>
        internal static Vector3? EyeViewPoint(GameObject root)
        {
            if (!HasEyes(root))
                return null;

            var animator = root.GetComponent<Animator>();
            var left = animator.GetBoneTransform(HumanBodyBones.LeftEye).position;
            var right = animator.GetBoneTransform(HumanBodyBones.RightEye).position;
            var forward = root.transform.forward * (Vector3.Distance(left, right) * 0.2f);
            // VRChat measures the view position from the avatar's root in meters, not scaled with the root (the SDK's own
            // handle draws it that way), so this is the plain offset - right on avatars whose root isn't at size 1 too.
            return (left + right) * 0.5f + forward - root.transform.position;
        }

        internal static void MakeHumanoid(ModelImporter importer)
        {
            importer.animationType = ModelImporterAnimationType.Human;
            importer.avatarSetup = ModelImporterAvatarSetup.CreateFromThisModel;
            importer.SaveAndReimport();
        }

        internal static string DefaultFolder(GameObject root)
        {
            string name = WPFMAPaths.SafeFileName(root != null ? root.name : "Avatar");

            var importer = SourceModel(root);
            if (importer != null && importer.assetPath.StartsWith("Assets/"))
            {
                string modelFolder = Path.GetDirectoryName(importer.assetPath).Replace('\\', '/');
                return modelFolder + "/" + name + " VRC";
            }

            return "Assets/Avatars/" + name;
        }

        internal static RuntimeAnimatorController CurrentFx(VRCAvatarDescriptor descriptor)
        {
            if (descriptor == null || !descriptor.customizeAnimationLayers || descriptor.baseAnimationLayers == null)
                return null;

            foreach (var layer in descriptor.baseAnimationLayers)
            {
                if (layer.type == VRCAvatarDescriptor.AnimLayerType.FX && !layer.isDefault)
                    return layer.animatorController;
            }

            return null;
        }

        internal static VRCExpressionsMenu CurrentMenu(VRCAvatarDescriptor descriptor)
        {
            return descriptor != null && descriptor.customExpressions ? descriptor.expressionsMenu : null;
        }

        internal static VRCExpressionParameters CurrentParameters(VRCAvatarDescriptor descriptor)
        {
            return descriptor != null && descriptor.customExpressions ? descriptor.expressionParameters : null;
        }

        internal static List<string> Validate(Request request)
        {
            var problems = new List<string>();

            if (request.Root == null)
            {
                problems.Add("Select the model in the Hierarchy. If it is only in the Project, place it in the scene first.");
                return problems;
            }

            if (request.Root.GetComponent<Animator>() == null)
                problems.Add("'" + request.Root.name + "' has no Animator, so it is probably not the model's top object.");

            if (string.IsNullOrEmpty(request.Folder) ||
                !(request.Folder == "Assets" || request.Folder.StartsWith("Assets/")))
                problems.Add("The folder for the new files has to be inside Assets.");

            return problems;
        }

        internal static Result Run(Request request)
        {
            var result = new Result();

            var problems = Validate(request);
            if (problems.Count > 0)
            {
                result.Message = problems[0];
                return result;
            }

            var root = request.Root;
            Undo.SetCurrentGroupName("WPFMA avatar setup");
            int group = Undo.GetCurrentGroup();

            var descriptor = root.GetComponent<VRCAvatarDescriptor>();
            if (descriptor == null)
            {
                descriptor = Undo.AddComponent<VRCAvatarDescriptor>(root);
                result.Notes.Add("Added the VRC Avatar Descriptor.");
            }

            if (root.GetComponent<VRC.Core.PipelineManager>() == null)
                Undo.AddComponent<VRC.Core.PipelineManager>(root);

            result.Descriptor = descriptor;
            string name = WPFMAPaths.SafeFileName(root.name);
            EnsureFolder(request.Folder);

            var fx = request.ReplaceExisting ? null : CurrentFx(descriptor) as AnimatorController;
            var menu = request.ReplaceExisting ? null : CurrentMenu(descriptor);
            var parameters = request.ReplaceExisting ? null : CurrentParameters(descriptor);

            if (fx == null)
            {
                string path = AssetDatabase.GenerateUniqueAssetPath(request.Folder + "/" + name + " FX.controller");
                fx = AnimatorController.CreateAnimatorControllerAtPath(path);
                result.Notes.Add("Created " + Path.GetFileName(path) + ".");
            }
            else
            {
                result.Notes.Add("Kept the FX controller already set (" + fx.name + ").");
            }

            if (parameters == null)
            {
                parameters = ScriptableObject.CreateInstance<VRCExpressionParameters>();
                parameters.parameters = new VRCExpressionParameters.Parameter[0];
                string path = AssetDatabase.GenerateUniqueAssetPath(request.Folder + "/" + name + " Parameters.asset");
                AssetDatabase.CreateAsset(parameters, path);
                result.Notes.Add("Created " + Path.GetFileName(path) + ".");
            }
            else
            {
                result.Notes.Add("Kept the Expression Parameters already set (" + parameters.name + ").");
            }

            if (menu == null)
            {
                menu = ScriptableObject.CreateInstance<VRCExpressionsMenu>();
                menu.controls = new List<VRCExpressionsMenu.Control>();
                menu.Parameters = parameters;
                string path = AssetDatabase.GenerateUniqueAssetPath(request.Folder + "/" + name + " Menu.asset");
                AssetDatabase.CreateAsset(menu, path);
                result.Notes.Add("Created " + Path.GetFileName(path) + ".");
            }
            else
            {
                result.Notes.Add("Kept the Expressions Menu already set (" + menu.name + ").");
                if (menu.Parameters == null)
                {
                    Undo.RecordObject(menu, "WPFMA avatar setup");
                    menu.Parameters = parameters;
                    EditorUtility.SetDirty(menu);
                }
            }

            Undo.RecordObject(descriptor, "WPFMA avatar setup");

            bool humanoid = IsHumanoid(root);
            EnsureLayers(descriptor, humanoid);
            AssignFx(descriptor, fx);

            descriptor.customizeAnimationLayers = true;
            descriptor.customExpressions = true;
            descriptor.expressionsMenu = menu;
            descriptor.expressionParameters = parameters;

            if (request.ViewFromEyes && HasEyes(root))
            {
                descriptor.ViewPosition = EyeViewPoint(root).Value;
                result.Notes.Add("View position set between the eyes, just in front of them.");
            }
            else if (request.ViewFromEyes)
            {
                result.Notes.Add("No eye bones found, so the view position was left alone. Set it with View > Edit on the descriptor.");
            }

            if (request.LipSync)
                SetupLipSync(descriptor, root, request.ReplaceExisting, result);

            if (request.EyeLook)
                SetupEyeLook(descriptor, root, request.ReplaceExisting, result);

            if (!humanoid)
                result.Notes.Add("The rig is not Humanoid, so Additive and Gesture are left out, the same as the VRChat SDK does.");

            EditorUtility.SetDirty(descriptor);
            PrefabUtility.RecordPrefabInstancePropertyModifications(descriptor);
            Undo.CollapseUndoOperations(group);

            AssetDatabase.SaveAssets();

            result.Success = true;
            result.Message = "'" + root.name + "' is set up. Files are in " + request.Folder + ".";
            return result;
        }

        private static readonly string[] BlinkNames =
        {
            "vrc.blink", "blink", "blink_both", "blink both", "eye_blink", "eyeblink", "eyes_blink", "\u307E\u3070\u305F\u304D"
        };

        internal static void SetupLipSync(VRCAvatarDescriptor descriptor, GameObject root, bool replace, Result result)
        {
            if (!replace && descriptor.lipSync != VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.Default)
            {
                result.Notes.Add("Kept the lip sync already set (" + descriptor.lipSync + ").");
                return;
            }

            int count = (int)VRC.SDKBase.VRC_AvatarDescriptor.Viseme.Count;
            SkinnedMeshRenderer best = null;
            string[] bestShapes = null;
            int bestFound = 0;

            foreach (var renderer in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                var mesh = renderer.sharedMesh;
                if (mesh == null || mesh.blendShapeCount == 0)
                    continue;

                var names = Enumerable.Range(0, mesh.blendShapeCount).Select(mesh.GetBlendShapeName).ToList();
                var shapes = new string[count];
                int found = 0;

                for (int v = 0; v < count; v++)
                {
                    string match = MatchViseme(names, ((VRC.SDKBase.VRC_AvatarDescriptor.Viseme)v).ToString().ToLowerInvariant());
                    if (match == null)
                        continue;

                    shapes[v] = match;
                    found++;
                }

                if (found <= 2)
                {
                    int mmd = MatchMmd(names, shapes);
                    if (mmd > found)
                        found = mmd;
                }

                if (found > bestFound)
                {
                    best = renderer;
                    bestShapes = shapes;
                    bestFound = found;
                }
            }

            if (best != null && bestFound > 2)
            {
                descriptor.lipSync = VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.VisemeBlendShape;
                descriptor.VisemeSkinnedMesh = best;
                descriptor.VisemeBlendShapes = bestShapes;
                descriptor.lipSyncJawBone = null;

                var missing = Enumerable.Range(0, count).Where(v => bestShapes[v] == null)
                    .Select(v => ((VRC.SDKBase.VRC_AvatarDescriptor.Viseme)v).ToString()).ToList();
                result.Notes.Add("Lip sync: " + bestFound + " of " + count + " visemes found on '" + best.name + "'." +
                                 (missing.Count > 0 ? " Not found: " + string.Join(", ", missing) + " - pick those by hand." : string.Empty));
                return;
            }

            var animator = root.GetComponent<Animator>();
            var jaw = animator != null && animator.isHuman ? animator.GetBoneTransform(HumanBodyBones.Jaw) : null;
            if (jaw != null)
            {
                descriptor.lipSync = VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.JawFlapBone;
                descriptor.lipSyncJawBone = jaw;
                descriptor.VisemeSkinnedMesh = null;
                result.Notes.Add("Lip sync: no viseme blendshapes found, so it uses the jaw bone instead.");
                return;
            }

            result.Notes.Add("Lip sync: no viseme blendshapes or jaw bone found, so it was left alone.");
        }

        // The MMD mouth shapes (a, i, u, e, o) for VRChat's aa, ih, ou, E and oh - the same pairing VRChat's own auto-detect uses.
        private static readonly KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>[] MmdVisemes =
        {
            new KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>(VRC.SDKBase.VRC_AvatarDescriptor.Viseme.aa, "\u3042"),
            new KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>(VRC.SDKBase.VRC_AvatarDescriptor.Viseme.ih, "\u3044"),
            new KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>(VRC.SDKBase.VRC_AvatarDescriptor.Viseme.ou, "\u3046"),
            new KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>(VRC.SDKBase.VRC_AvatarDescriptor.Viseme.E, "\u3048"),
            new KeyValuePair<VRC.SDKBase.VRC_AvatarDescriptor.Viseme, string>(VRC.SDKBase.VRC_AvatarDescriptor.Viseme.oh, "\u304A")
        };

        /// <summary>Fills in the visemes the MMD shapes cover (the others stay as found). Returns how many are set.</summary>
        private static int MatchMmd(List<string> names, string[] shapes)
        {
            var mmd = new string[shapes.Length];
            int found = 0;
            foreach (var pair in MmdVisemes)
            {
                string match = names.FirstOrDefault(n => n.Trim() == pair.Value);
                if (match == null)
                    continue;
                mmd[(int)pair.Key] = match;
                found++;
            }

            if (found < 3)
                return 0;

            for (int v = 0; v < shapes.Length; v++)
                if (shapes[v] == null && mmd[v] != null)
                    shapes[v] = mmd[v];
            return shapes.Count(s => s != null);
        }

        private static string MatchViseme(List<string> names, string viseme)
        {
            foreach (var name in names)
                if (name.ToLowerInvariant() == "vrc.v_" + viseme)
                    return name;

            foreach (var name in names)
                if (name.ToLowerInvariant() == "v_" + viseme)
                    return name;

            foreach (var name in names)
            {
                string lower = name.ToLowerInvariant();
                if (lower.EndsWith("_" + viseme) || lower.EndsWith("." + viseme) || lower.EndsWith(" " + viseme))
                    return name;
            }

            return null;
        }

        internal static void SetupEyeLook(VRCAvatarDescriptor descriptor, GameObject root, bool replace, Result result)
        {
            if (!HasEyes(root))
            {
                result.Notes.Add("Eye look: no eye bones in the rig, so it was left off.");
                return;
            }

            if (!replace && descriptor.enableEyeLook)
            {
                result.Notes.Add("Kept the eye look already set.");
                return;
            }

            var animator = root.GetComponent<Animator>();
            var settings = descriptor.customEyeLookSettings;
            settings.leftEye = animator.GetBoneTransform(HumanBodyBones.LeftEye);
            settings.rightEye = animator.GetBoneTransform(HumanBodyBones.RightEye);

            SkinnedMeshRenderer blinkMesh;
            int blink = FindBlink(root, descriptor.VisemeSkinnedMesh, out blinkMesh);
            if (blink >= 0)
            {
                settings.eyelidType = VRCAvatarDescriptor.EyelidType.Blendshapes;
                settings.eyelidsSkinnedMesh = blinkMesh;
                settings.eyelidsBlendshapes = new[] { blink, -1, -1 };
                result.Notes.Add("Eye look: eyes set, blink uses '" + blinkMesh.sharedMesh.GetBlendShapeName(blink) + "'.");
            }
            else
            {
                result.Notes.Add("Eye look: eyes set. No blink blendshape found - pick one on the descriptor if the model has one.");
            }

            descriptor.customEyeLookSettings = settings;
            descriptor.enableEyeLook = true;
        }

        private static int FindBlink(GameObject root, SkinnedMeshRenderer preferred, out SkinnedMeshRenderer mesh)
        {
            var renderers = root.GetComponentsInChildren<SkinnedMeshRenderer>(true)
                .Where(r => r.sharedMesh != null && r.sharedMesh.blendShapeCount > 0)
                .OrderBy(r => r == preferred ? 0 : 1)
                .ToList();

            foreach (var wanted in BlinkNames)
            {
                foreach (var renderer in renderers)
                {
                    for (int i = 0; i < renderer.sharedMesh.blendShapeCount; i++)
                    {
                        if (renderer.sharedMesh.GetBlendShapeName(i).ToLowerInvariant() == wanted)
                        {
                            mesh = renderer;
                            return i;
                        }
                    }
                }
            }

            foreach (var renderer in renderers)
            {
                int best = -1;
                for (int i = 0; i < renderer.sharedMesh.blendShapeCount; i++)
                {
                    string name = renderer.sharedMesh.GetBlendShapeName(i).ToLowerInvariant();
                    if (!name.Contains("blink") || OneSided(name))
                        continue;

                    if (best < 0 || name.Length < renderer.sharedMesh.GetBlendShapeName(best).Length)
                        best = i;
                }

                if (best >= 0)
                {
                    mesh = renderer;
                    return best;
                }
            }

            mesh = null;
            return -1;
        }

        private static bool OneSided(string name)
        {
            return name.Contains("left") || name.Contains("right") ||
                   name.EndsWith("_l") || name.EndsWith("_r") || name.EndsWith(".l") || name.EndsWith(".r") ||
                   name.EndsWith(" l") || name.EndsWith(" r");
        }

        private static void EnsureLayers(VRCAvatarDescriptor descriptor, bool humanoid)
        {
            var wanted = BaseLayers.Where(t => humanoid ||
                (t != VRCAvatarDescriptor.AnimLayerType.Additive && t != VRCAvatarDescriptor.AnimLayerType.Gesture));

            descriptor.baseAnimationLayers = Merge(descriptor.baseAnimationLayers, wanted);
            descriptor.specialAnimationLayers = Merge(descriptor.specialAnimationLayers, SpecialLayers);
        }

        private static VRCAvatarDescriptor.CustomAnimLayer[] Merge(VRCAvatarDescriptor.CustomAnimLayer[] current,
            IEnumerable<VRCAvatarDescriptor.AnimLayerType> wanted)
        {
            var existing = current ?? new VRCAvatarDescriptor.CustomAnimLayer[0];
            var merged = new List<VRCAvatarDescriptor.CustomAnimLayer>();

            foreach (var type in wanted)
            {
                int index = System.Array.FindIndex(existing, l => l.type == type);
                merged.Add(index >= 0
                    ? existing[index]
                    : new VRCAvatarDescriptor.CustomAnimLayer { type = type, isDefault = true });
            }

            return merged.ToArray();
        }

        private static void AssignFx(VRCAvatarDescriptor descriptor, AnimatorController fx)
        {
            var layers = descriptor.baseAnimationLayers;
            for (int i = 0; i < layers.Length; i++)
            {
                if (layers[i].type != VRCAvatarDescriptor.AnimLayerType.FX)
                    continue;

                layers[i].isDefault = false;
                layers[i].animatorController = fx;
                layers[i].mask = fx.layers.Length > 0 ? fx.layers[0].avatarMask : null;
            }

            descriptor.baseAnimationLayers = layers;
        }

        private static void EnsureFolder(string folder)
        {
            if (AssetDatabase.IsValidFolder(folder))
                return;

            string parent = Path.GetDirectoryName(folder).Replace('\\', '/');
            if (!AssetDatabase.IsValidFolder(parent))
                EnsureFolder(parent);

            AssetDatabase.CreateFolder(parent, Path.GetFileName(folder));
        }
    }
}
#endif
#endif
