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

namespace WPFMA.Vrca
{
    public static class WPFMAParameterRepair
    {
        public static void Repair()
        {
            var controllers = SelectedControllers();
            if (controllers.Count == 0)
            {
                EditorUtility.DisplayDialog("WPFMA-SDK",
                    "Select the exported animator controllers to repair first — the AnimatorController folder " +
                    "inside a rip, or the controllers themselves — then run this again.", "OK");
                return;
            }

            string vrca = EditorUtility.OpenFilePanel("The .vrca these controllers came from", "", "vrca");
            if (string.IsNullOrEmpty(vrca))
                return;

            WPFMASerializedFile cab;
            try
            {
                cab = ReadCab(vrca);
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog("WPFMA-SDK", "Could not read that .vrca:\n\n" + e.Message, "OK");
                return;
            }

            var available = ParametersByControllerName(cab);
            var candidates = PathIdsByControllerName(cab);
            int repaired = 0, added = 0, childrenFixed = 0;
            var untouched = new List<string>();
            var notes = new List<string>();

            foreach (var controller in controllers)
            {
                List<AnimatorControllerParameter> wanted;
                if (!available.TryGetValue(controller.name, out wanted) || wanted.Count == 0)
                {
                    untouched.Add(controller.name + " (no controller of that name in the bundle)");
                    continue;
                }

                var present = new HashSet<string>(controller.parameters.Select(p => p.name), StringComparer.Ordinal);
                int before = added;

                foreach (var parameter in wanted)
                {
                    if (present.Contains(parameter.name))
                        continue;

                    controller.AddParameter(new AnimatorControllerParameter
                    {
                        name = parameter.name,
                        type = parameter.type,
                        defaultBool = parameter.defaultBool,
                        defaultFloat = parameter.defaultFloat,
                        defaultInt = parameter.defaultInt
                    });
                    added++;
                }

                int children = 0;
                List<long> pathIds;
                if (candidates.TryGetValue(controller.name, out pathIds))
                {
                    foreach (var pathId in pathIds)
                    {
                        int result = WPFMAAnimatorGraph.RepairChildSettings(controller, cab, pathId, notes);
                        if (result < 0)
                            continue;

                        children = result;
                        break;
                    }
                }

                childrenFixed += children;

                if (added > before || children > 0)
                {
                    EditorUtility.SetDirty(controller);
                    repaired++;
                }
                else
                {
                    untouched.Add(controller.name + " (already had all " + wanted.Count + " parameters and matching blend trees)");
                }
            }

            AssetDatabase.SaveAssets();

            string summary = "Added " + added + " parameter(s) and fixed " + childrenFixed +
                             " blend-tree child setting(s) across " + repaired + " controller(s).";
            if (notes.Count > 0)
                summary += "\n\n" + string.Join("\n", notes.Distinct().Take(6).ToArray());
            if (untouched.Count > 0)
                summary += "\n\nLeft alone:\n  " + string.Join("\n  ", untouched.Take(12).ToArray()) +
                           (untouched.Count > 12 ? "\n  ..." : string.Empty);

            Debug.Log("[WPFMA-SDK] Parameter repair: " + summary.Replace("\n", " "));
            EditorUtility.DisplayDialog("WPFMA-SDK", summary, "OK");
        }

        private static List<AnimatorController> SelectedControllers()
        {
            var found = new List<AnimatorController>();
            var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var selected in Selection.GetFiltered<UnityEngine.Object>(SelectionMode.Assets))
            {
                string path = AssetDatabase.GetAssetPath(selected);
                if (string.IsNullOrEmpty(path))
                    continue;

                var paths = AssetDatabase.IsValidFolder(path)
                    ? AssetDatabase.FindAssets("t:AnimatorController", new[] { path })
                        .Select(AssetDatabase.GUIDToAssetPath)
                    : new[] { path };

                foreach (var candidate in paths)
                {
                    if (!seen.Add(candidate))
                        continue;

                    var controller = AssetDatabase.LoadAssetAtPath<AnimatorController>(candidate);
                    if (controller != null)
                        found.Add(controller);
                }
            }

            return found;
        }

        private static WPFMASerializedFile ReadCab(string vrcaPath)
        {
            using (var stream = new FileStream(vrcaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var container = WPFMAVrcaBundle.Open(stream);
                foreach (var node in container.Nodes)
                {
                    if ((node.Flags & 4) == 0)
                        continue;

                    return WPFMASerializedFile.Parse(container.ExtractNodeBytes(stream, node));
                }
            }

            throw new WPFMAVrcaException("That file holds no serialized data member.");
        }

        private static Dictionary<string, List<long>> PathIdsByControllerName(WPFMASerializedFile cab)
        {
            var byName = new Dictionary<string, List<long>>(StringComparer.Ordinal);

            foreach (var info in cab.Objects)
            {
                if (info.Type.ClassId != 91)
                    continue;

                string name;
                try
                {
                    var root = cab.ReadObject(info) as Dictionary<string, object>;
                    name = root != null ? root["m_Name"] as string : null;
                }
                catch (Exception)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(name))
                    continue;

                List<long> ids;
                if (!byName.TryGetValue(name, out ids))
                    byName[name] = ids = new List<long>();
                ids.Add(info.PathId);
            }

            return byName;
        }

        private static Dictionary<string, List<AnimatorControllerParameter>> ParametersByControllerName(WPFMASerializedFile cab)
        {
            var byName = new Dictionary<string, List<AnimatorControllerParameter>>(StringComparer.Ordinal);

            foreach (var info in cab.Objects)
            {
                if (info.Type.ClassId != 91)
                    continue;

                string name;
                try
                {
                    var root = cab.ReadObject(info) as Dictionary<string, object>;
                    name = root != null ? root["m_Name"] as string : null;
                }
                catch (Exception)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(name))
                    continue;

                var parameters = WPFMAAnimatorGraph.ReadParameters(cab, name, info.PathId);

                List<AnimatorControllerParameter> existing;
                if (!byName.TryGetValue(name, out existing) || parameters.Count > existing.Count)
                    byName[name] = parameters;
            }

            return byName;
        }
    }
}
#endif
