// 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 UnityEditor.Animations;
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Avatars.ScriptableObjects;
using VRC.SDKBase.Validation.Performance;
using VRC.SDKBase.Validation.Performance.Stats;
#endif

namespace WPFMA
{
    internal static class WPFMAPreUploadCheck
    {
        internal enum Severity
        {
            Error,
            Warning,
            Info,
            Pass
        }

        internal sealed class Issue
        {
            public Severity Severity;
            public string Title;
            public string Detail;
            public string FixLabel;
            public Action Fix;
            public UnityEngine.Object[] Show;
            public int ToolPage = -1;
            public string ToolKey;
            public string[] Assets;
            public bool Scene = true;
        }

#if WPFMA_VRC_AVATARS
        internal static List<Issue> Run(GameObject root)
        {
            var issues = new List<Issue>();
            var descriptor = root != null ? root.GetComponent<VRCAvatarDescriptor>() : null;

            if (descriptor == null)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = "No VRC Avatar Descriptor",
                    Detail = "VRChat cannot upload this without one. Avatar setup adds it along with the FX controller, menu and parameters.",
                    ToolPage = 0,
                    ToolKey = "WPFMA.Tools.AvatarSetupExpanded"
                });
                return issues;
            }

            // The checks below ask for the same scans (add-ons, animations, parameters) many times; work each out once.
            using (WPFMAAvatarAnimations.Cache())
                RunChecks(root, descriptor, issues);
            return issues.OrderBy(i => i.Severity).ToList();
        }

        private static void RunChecks(GameObject root, VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            Guard(issues, "Missing scripts", () => MissingScripts(root, issues));
            Guard(issues, "Materials", () => Materials(root, issues));
            Guard(issues, "Rig", () => Rig(root, issues));
            Guard(issues, "View position", () => ViewPosition(root, descriptor, issues));
            Guard(issues, "Expressions", () => Expressions(descriptor, issues));
            Guard(issues, "Animation layers", () => Layers(descriptor, issues));
            Guard(issues, "Write defaults", () => WriteDefaults(descriptor, issues));
            Guard(issues, "Animation paths", () => AnimationPaths(root, issues));
            Guard(issues, "Face tracking", () => FaceTracking(root, issues));
            Guard(issues, "Lip sync and eyes", () => LipSyncAndEyes(root, descriptor, issues));
            runPc = runQuest = null;
            Guard(issues, "Performance", () => Performance(descriptor, issues));
            Guard(issues, "Textures", () => Textures(root, descriptor, issues));
            Guard(issues, "Quest shaders", () => QuestShaders(root, issues));
            Guard(issues, "Toggle layers", () => ToggleLayers(descriptor, issues));
            Guard(issues, "PhysBones", () => PhysBones(root, issues));
            Guard(issues, "Lighting", () => Lighting(root, issues));
            Guard(issues, "Upload ID", () => Blueprint(root, issues));
        }

        private static void Guard(List<Issue> issues, string name, Action check)
        {
            try
            {
                check();
            }
            catch (Exception e)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Info,
                    Title = name + " could not be checked",
                    Detail = e.Message
                });
            }
        }

        private static void MissingScripts(GameObject root, List<Issue> issues)
        {
            var broken = root.GetComponentsInChildren<Transform>(true)
                .Where(t => GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(t.gameObject) > 0)
                .Select(t => t.gameObject)
                .ToArray();

            if (broken.Length == 0)
            {
                issues.Add(Pass("No missing scripts"));
                return;
            }

            int total = broken.Sum(g => GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(g));
            issues.Add(new Issue
            {
                Severity = Severity.Error,
                Title = total + " missing script(s) on " + broken.Length + " object(s)",
                Detail = "Components whose script is gone, which is common on ripped avatars. VRChat's builder refuses these. " +
                         "If a package is missing, install it instead (the Ripper lists the packages a rip needs).",
                Show = broken.Cast<UnityEngine.Object>().ToArray(),
                FixLabel = "Remove them",
                Fix = () =>
                {
                    Undo.RegisterFullObjectHierarchyUndo(root, "Remove missing scripts");
                    foreach (var go in broken)
                    {
                        if (go != null)
                            GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                    }
                }
            });
        }

        private static void Materials(GameObject root, List<Issue> issues)
        {
            var pink = new List<UnityEngine.Object>();
            var empty = new List<UnityEngine.Object>();
            var noMesh = new List<UnityEngine.Object>();
            var pinkShaders = new HashSet<string>();

            foreach (var renderer in root.GetComponentsInChildren<Renderer>(true))
            {
                if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer)
                    continue;

                var skinned = renderer as SkinnedMeshRenderer;
                var filter = renderer.GetComponent<MeshFilter>();
                if ((skinned != null && skinned.sharedMesh == null) || (skinned == null && filter != null && filter.sharedMesh == null))
                    noMesh.Add(renderer.gameObject);

                foreach (var material in renderer.sharedMaterials)
                {
                    if (material == null)
                    {
                        empty.Add(renderer.gameObject);
                        continue;
                    }

                    var shader = material.shader;
                    if (shader == null || shader.name == "Hidden/InternalErrorShader" || !shader.isSupported)
                    {
                        pink.Add(renderer.gameObject);
                        pinkShaders.Add(shader != null ? shader.name : "(none)");
                    }
                }
            }

            if (pink.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = pink.Distinct().Count() + " object(s) will show pink",
                    Detail = "Their shader is missing or broken: " + string.Join(", ", pinkShaders.Take(4).ToArray()) +
                             ". Import the shader, or swap them with Bulk shader swap.",
                    Show = pink.Distinct().ToArray(),
                    ToolPage = 2,
                    ToolKey = "WPFMA.Tools.ShaderSwapExpanded"
                });
            }

            if (empty.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Empty material slots on " + empty.Distinct().Count() + " object(s)",
                    Detail = "Those parts render pink or not at all.",
                    Show = empty.Distinct().ToArray()
                });
            }

            if (noMesh.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = noMesh.Count + " renderer(s) have no mesh",
                    Detail = "They draw nothing. Usually a mesh that did not come across in a rip or re-import.",
                    Show = noMesh.ToArray()
                });
            }

            if (pink.Count == 0 && empty.Count == 0 && noMesh.Count == 0)
                issues.Add(Pass("Every material has a working shader"));
        }

        private static void Rig(GameObject root, List<Issue> issues)
        {
            var animator = root.GetComponent<Animator>();
            if (animator == null || animator.avatar == null)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "No rig on the Animator",
                    Detail = "The avatar root's Animator has no Avatar (rig) set, so gestures, IK and sitting will not work.",
                    Show = new UnityEngine.Object[] { root }
                });
                return;
            }

            issues.Add(animator.isHuman
                ? Pass("Humanoid rig")
                : new Issue
                {
                    Severity = Severity.Info,
                    Title = "Rig is not Humanoid",
                    Detail = "Fine for creatures and props, but full body, gestures and sitting need Humanoid. Avatar setup can switch the FBX over.",
                    ToolPage = 0,
                    ToolKey = "WPFMA.Tools.AvatarSetupExpanded"
                });
        }

        private static void ViewPosition(GameObject root, VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            var eyes = WPFMAAvatarSetup.EyeViewPoint(root);

            if (eyes != null)
            {
                var local = eyes.Value;
                float distance = Vector3.Distance(local, descriptor.ViewPosition);

                if (distance > 0.08f)
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Warning,
                        Title = "View position is " + Mathf.RoundToInt(distance * 100f) + " cm from the eyes",
                        Detail = "In VRChat you would see from that spot instead of the avatar's eyes.",
                        FixLabel = "Put it between the eyes",
                        Fix = () =>
                        {
                            Undo.RecordObject(descriptor, "Set view position");
                            descriptor.ViewPosition = local;
                            EditorUtility.SetDirty(descriptor);
                        }
                    });
                    return;
                }

                issues.Add(Pass("View position is at the eyes"));
                return;
            }

            if (descriptor.ViewPosition == Vector3.zero)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "View position is at the feet",
                    Detail = "Set it with View > Edit on the descriptor.",
                    Show = new UnityEngine.Object[] { descriptor }
                });
                return;
            }

            issues.Add(Pass("View position is set"));
        }

        private static void Expressions(VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            if (!descriptor.customExpressions)
            {
                issues.Add(Pass("Uses VRChat's default menu"));
                return;
            }

            var menu = descriptor.expressionsMenu;
            var parameters = descriptor.expressionParameters;

            if (menu != null && parameters == null)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Error,
                    Title = "Menu set but no Expression Parameters",
                    Detail = "The menu's controls have nothing to drive. Avatar setup can create the parameters asset.",
                    ToolPage = 0,
                    ToolKey = "WPFMA.Tools.AvatarSetupExpanded"
                });
            }

            if (parameters != null)
            {
                int cost = parameters.CalcTotalCost();
                if (cost > VRCExpressionParameters.MAX_PARAMETER_COST)
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Error,
                        Title = "Synced parameters: " + cost + " / " + VRCExpressionParameters.MAX_PARAMETER_COST + " bits",
                        Detail = "Over VRChat's limit, so it will not upload. Unsync or remove some.",
                        ToolPage = 1,
                        ToolKey = "WPFMA.Tools.ParameterBudgetExpanded"
                    });
                }

                List<string> unused, orphans;
                WPFMAParameterBudgetSection.Problems(descriptor, out unused, out orphans);
                if (unused.Count > 0)
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Warning,
                        Title = unused.Count + " parameter(s) nothing uses",
                        Detail = string.Join(", ", unused.Take(6).ToArray()) + (unused.Count > 6 ? "..." : string.Empty) +
                                 ". They take up sync budget for nothing.",
                        ToolPage = 1,
                        ToolKey = "WPFMA.Tools.ParameterBudgetExpanded"
                    });
                }

                if (orphans.Count > 0)
                {
                    issues.Add(new Issue
                    {
                        Severity = Severity.Warning,
                        Title = orphans.Count + " menu control(s) point at parameters that do not exist",
                        Detail = string.Join(", ", orphans.Take(6).ToArray()) + ". Those buttons do nothing unless a tool adds the parameter at upload.",
                        ToolPage = 1,
                        ToolKey = "WPFMA.Tools.ParameterBudgetExpanded"
                    });
                }

                var bools = WPFMAParameterBudgetSection.IntsThatCouldBeBools(descriptor);
                if (bools.Count > 0)
                {
                    var names = bools;
                    issues.Add(new Issue
                    {
                        Severity = cost > VRCExpressionParameters.MAX_PARAMETER_COST ? Severity.Warning : Severity.Info,
                        Title = bools.Count + " Int parameter(s) only ever hold 0 or 1",
                        Detail = string.Join(", ", bools.Take(6).ToArray()) + (bools.Count > 6 ? "..." : string.Empty) +
                                 ". As Bools they'd use 1 bit each instead of 8 (saving " + bools.Count * 7 + ") and work the same.",
                        FixLabel = "Make them Bools",
                        Fix = () => Debug.Log("[WPFMA-SDK] " + WPFMAParameterBudgetSection.MakeBools(descriptor, names)),
                        Assets = new[] { AssetDatabase.GetAssetPath(parameters) },
                        Scene = false
                    });
                }

                if (cost <= VRCExpressionParameters.MAX_PARAMETER_COST && unused.Count == 0 && orphans.Count == 0 && bools.Count == 0)
                    issues.Add(Pass("Parameters: " + cost + " / " + VRCExpressionParameters.MAX_PARAMETER_COST + " bits, all used"));
            }

            var full = new List<string>();
            var emptySubmenus = new List<string>();
            WalkMenu(menu, full, emptySubmenus, new HashSet<VRCExpressionsMenu>());

            if (full.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Menus over the " + VRCExpressionsMenu.MAX_CONTROLS + "-control limit",
                    Detail = string.Join(", ", full.ToArray()) + ". The extra controls do not show in game."
                });
            }

            if (emptySubmenus.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = emptySubmenus.Count + " submenu button(s) open nothing",
                    Detail = string.Join(", ", emptySubmenus.Take(6).ToArray()) + ". Their submenu asset is missing."
                });
            }
        }

        private static void WalkMenu(VRCExpressionsMenu menu, List<string> full, List<string> emptySubmenus, HashSet<VRCExpressionsMenu> seen)
        {
            if (menu == null || !seen.Add(menu) || menu.controls == null)
                return;

            if (menu.controls.Count > VRCExpressionsMenu.MAX_CONTROLS)
                full.Add(menu.name + " (" + menu.controls.Count + ")");

            foreach (var control in menu.controls)
            {
                if (control == null || control.type != VRCExpressionsMenu.Control.ControlType.SubMenu)
                    continue;

                if (control.subMenu == null)
                    emptySubmenus.Add(control.name);
                else
                    WalkMenu(control.subMenu, full, emptySubmenus, seen);
            }
        }

        private static void Layers(VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            if (!descriptor.customizeAnimationLayers || descriptor.baseAnimationLayers == null)
            {
                issues.Add(Pass("Uses VRChat's default animation layers"));
                return;
            }

            var empty = descriptor.baseAnimationLayers
                .Where(l => !l.isDefault && l.animatorController == null)
                .Select(l => l.type.ToString())
                .ToList();

            if (empty.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Customised layer(s) left empty: " + string.Join(", ", empty.ToArray()),
                    Detail = "The slot is set to custom but has no controller, so that layer does nothing in game.",
                    Show = new UnityEngine.Object[] { descriptor }
                });
            }
            else
            {
                issues.Add(Pass("Animation layers are filled in"));
            }
        }

        private static void WriteDefaults(VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            // The same check as the Write defaults tool (every controller, Merge Animators, Direct blend trees).
            bool any = false;
            foreach (var report in WPFMAWriteDefaults.Check(descriptor).Where(r => r.HasProblem))
            {
                any = true;
                var r = report;
                bool fixable = r.MergeAnimator != null || !r.ReadOnly;
                bool on = r.MergeAnimator != null || r.Recommended;
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = r.MergeAnimator != null ? r.Label + " doesn't match the avatar's write defaults" :
                        r.Mixed ? r.Label + " mixes write defaults (" + r.On + " on, " + r.Off + " off)" : r.Label + ": a Direct blend tree has write defaults off",
                    Detail = r.MergeAnimator != null ? "Modular Avatar can match it to the avatar at upload." :
                        r.ReadOnly ? "It's VRChat's own controller (in Packages); give the avatar a copy first." :
                        "Mixing makes toggles stick and faces freeze. Direct blend trees stay on; going off gives empty states a reset clip.",
                    Show = new UnityEngine.Object[] { r.Controller },
                    Assets = r.MergeAnimator == null ? new[] { r.Path } : new string[0],
                    Scene = r.MergeAnimator != null,
                    ToolPage = 1,
                    ToolKey = WPFMAWriteDefaultsSection.PrefKey,
                    FixLabel = !fixable ? null : r.MergeAnimator != null ? "Match the avatar" : "Make all " + (on ? "on" : "off"),
                    Fix = !fixable ? (Action)null : () => WPFMAWriteDefaults.Fix(descriptor, r, on, null)
                });
            }

            if (!any)
                issues.Add(Pass("Write defaults are consistent"));
        }

        private static IEnumerable<AnimatorState> AllStates(AnimatorStateMachine machine)
        {
            foreach (var child in machine.states)
                yield return child.state;

            foreach (var sub in machine.stateMachines)
            {
                if (sub.stateMachine == null)
                    continue;
                foreach (var state in AllStates(sub.stateMachine))
                    yield return state;
            }
        }

        private static void AnimationPaths(GameObject root, List<Issue> issues)
        {
            var scan = WPFMAAnimationPathFixer.Scan(root);
            var fixable = scan.Broken.Where(b => !b.LockedOnly).ToList();

            if (fixable.Count == 0)
            {
                issues.Add(Pass("Every animation points at something that exists (" + scan.Clips + " clips)"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Warning,
                Title = fixable.Count + " broken animation path(s)",
                Detail = "Animations aimed at objects that were renamed or moved: " +
                         string.Join(", ", fixable.Take(4).Select(b => b.Path).ToArray()) + (fixable.Count > 4 ? "..." : string.Empty),
                ToolPage = 1,
                ToolKey = "WPFMA.Tools.PathFixerExpanded"
            });
        }

        private static void FaceTracking(GameObject root, List<Issue> issues)
        {
            var report = WPFMAFaceTrackingChecker.Check(root);

            if (report.BrokenShapes.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = report.BrokenShapes.Count + " animated blendshape(s) do not exist",
                    Detail = string.Join(", ", report.BrokenShapes.Keys.Take(5).ToArray()) + ". Common after a rip or a mesh re-export.",
                    ToolPage = 1,
                    ToolKey = "WPFMA.Tools.FaceTrackingExpanded"
                });
            }

            var case_ = report.Coverage.Where(c => c.WrongCase.Count > 0).ToList();
            if (report.HasFaceTrackingParameters && case_.Count > 0)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Face tracking shapes with the wrong capitals",
                    Detail = case_.Sum(c => c.WrongCase.Count) + " shape(s). Templates are case-sensitive, so these never move.",
                    ToolPage = 1,
                    ToolKey = "WPFMA.Tools.FaceTrackingExpanded"
                });
            }

            if (report.BrokenShapes.Count == 0 && !(report.HasFaceTrackingParameters && case_.Count > 0))
                issues.Add(Pass("Animated blendshapes all exist"));
        }

        private static void LipSyncAndEyes(GameObject root, VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            if (descriptor.lipSync == VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.Default)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Info,
                    Title = "Lip sync is not set up",
                    Detail = "The mouth will not move when you talk.",
                    FixLabel = "Set it up",
                    Fix = () =>
                    {
                        Undo.RecordObject(descriptor, "Set up lip sync");
                        var result = new WPFMAAvatarSetup.Result();
                        WPFMAAvatarSetup.SetupLipSync(descriptor, root, false, result);
                        EditorUtility.SetDirty(descriptor);
                        foreach (var note in result.Notes)
                            Debug.Log("[WPFMA-SDK] " + note);
                    }
                });
            }
            else
            {
                issues.Add(Pass("Lip sync: " + descriptor.lipSync));
            }

            if (!descriptor.enableEyeLook && WPFMAAvatarSetup.HasEyes(root))
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Info,
                    Title = "Eye look is off",
                    Detail = "The model has eye bones, but the eyes will not look around or blink.",
                    FixLabel = "Turn it on",
                    Fix = () =>
                    {
                        Undo.RecordObject(descriptor, "Set up eye look");
                        var result = new WPFMAAvatarSetup.Result();
                        WPFMAAvatarSetup.SetupEyeLook(descriptor, root, false, result);
                        EditorUtility.SetDirty(descriptor);
                        foreach (var note in result.Notes)
                            Debug.Log("[WPFMA-SDK] " + note);
                    }
                });
            }
        }

        private static void Performance(VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            var pc = RunStats(descriptor, false).GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);
            var quest = RunStats(descriptor, true).GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);

            string summary = "PC " + WPFMAPerformanceSection.RatingName(pc) + ", Quest " + WPFMAPerformanceSection.RatingName(quest);

            if (pc == PerformanceRating.VeryPoor)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Warning,
                    Title = "Very Poor on PC (" + summary + ")",
                    Detail = "Many people's settings hide Very Poor avatars. The rank tool shows what to cut.",
                    ToolPage = 1,
                    ToolKey = "WPFMA.Tools.PerformanceExpanded"
                });
            }
            else if (quest == PerformanceRating.VeryPoor)
            {
                issues.Add(new Issue
                {
                    Severity = Severity.Info,
                    Title = "Very Poor on Quest (" + summary + ")",
                    Detail = "Only matters if you upload a Quest version - there it is hidden by default.",
                    ToolPage = 1,
                    ToolKey = "WPFMA.Tools.PerformanceExpanded"
                });
            }
            else
            {
                issues.Add(Pass("Rank: " + summary));
            }
        }

        private static AvatarPerformanceStats runPc, runQuest;

        private static AvatarPerformanceStats RunStats(VRCAvatarDescriptor descriptor, bool mobile)
        {
            if (mobile)
                return runQuest ?? (runQuest = WPFMAPerformanceSection.StatsFor(descriptor, true));
            return runPc ?? (runPc = WPFMAPerformanceSection.StatsFor(descriptor, false));
        }

        private static void Textures(GameObject root, VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            var entries = WPFMATextureOptimizer.Collect(root);
            if (entries.Count == 0)
                return;

            long bytes = entries.Sum(e => e.Bytes);
            string mb = (bytes / (1024.0 * 1024.0)).ToString("0.#") + " MB";
            var pc = RunStats(descriptor, false).GetPerformanceRatingForCategory(AvatarPerformanceCategory.TextureMegabytes);
            int big = entries.Count(e => e.Texture != null && Math.Max(e.Texture.width, e.Texture.height) > 2048);
            int raw = entries.Count(e => e.Importer != null && !e.Ramp && e.Importer.textureCompression == TextureImporterCompression.Uncompressed);

            if (pc < PerformanceRating.Poor && big == 0 && raw == 0)
            {
                issues.Add(Pass("Textures: " + mb + " of video memory"));
                return;
            }

            var parts = new List<string>();
            if (big > 0)
                parts.Add(big + " bigger than 2048");
            if (raw > 0)
                parts.Add(raw + " not compressed");
            issues.Add(new Issue
            {
                Severity = pc >= PerformanceRating.Poor ? Severity.Warning : Severity.Info,
                Title = "Textures use " + mb + " of video memory" + (pc != PerformanceRating.None ? " (PC " + WPFMAPerformanceSection.RatingName(pc) + ")" : string.Empty),
                Detail = (parts.Count > 0 ? string.Join(", ", parts.ToArray()) + ". " : string.Empty) +
                         "Textures are usually most of an avatar's memory and download. The texture optimizer can shrink them.",
                ToolPage = 2,
                ToolKey = "WPFMA.Tools.TextureOptimizerExpanded"
            });
        }

        private static void QuestShaders(GameObject root, List<Issue> issues)
        {
            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
                return;

            var bad = root.GetComponentsInChildren<Renderer>(true)
                .Where(r => r.sharedMaterials.Any(m => m != null && m.shader != null && !m.shader.name.StartsWith("VRChat/Mobile/", StringComparison.Ordinal)))
                .Select(r => r.gameObject)
                .Distinct()
                .ToArray();

            if (bad.Length == 0)
            {
                issues.Add(Pass("Every material uses a Quest shader"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Error,
                Title = bad.Length + " object(s) use shaders Quest doesn't allow",
                Detail = "Quest avatars can only use VRChat's Mobile shaders, so the upload fails. Bulk shader swap switches them " +
                         "(do it on a copy, or with Easy Quest Switch, so the PC version keeps its shaders).",
                Show = bad.Cast<UnityEngine.Object>().ToArray(),
                ToolPage = 2,
                ToolKey = "WPFMA.Tools.ShaderSwapExpanded"
            });
        }

        private static void ToggleLayers(VRCAvatarDescriptor descriptor, List<Issue> issues)
        {
            var fx = WPFMAToggleCreator.FindFxController(descriptor) as AnimatorController;
            if (fx == null || string.IsNullOrEmpty(AssetDatabase.GetAssetPath(fx)))
                return;

            int combinable = WPFMAToggleCreator.Combinable(fx).Count;
            if (combinable < 2)
            {
                issues.Add(Pass("FX controller: " + fx.layers.Length + " layer(s)"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = fx.layers.Length + " FX layers - " + combinable + " toggles could share one",
                Detail = "Every layer costs the avatar a little every frame. In one shared layer they work exactly the same.",
                FixLabel = "Combine them",
                Fix = () => Debug.Log("[WPFMA-SDK] " + WPFMAToggleCreator.CombineExisting(descriptor)),
                Assets = new[] { AssetDatabase.GetAssetPath(fx) },
                Scene = false
            });
        }

        private static void PhysBones(GameObject root, List<Issue> issues)
        {
            var report = WPFMAPhysBoneOptimizer.Analyze(root);
            if (report.Bones.Count == 0)
                return;

            if (report.Fixable == 0)
            {
                issues.Add(Pass("PhysBones: no wasted settings"));
                return;
            }

            var parts = new List<string>();
            if (report.WastedAnimated > 0)
                parts.Add(report.WastedAnimated + " with Is Animated on for nothing");
            if (report.EmptySlots > 0)
                parts.Add(report.EmptySlots + " empty collider slot(s)");
            if (report.MovesNothing > 0)
                parts.Add(report.MovesNothing + " that move nothing");
            if (report.UnusedColliders.Count > 0)
                parts.Add(report.UnusedColliders.Count + " collider(s) nothing uses");

            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = "PhysBone settings that cost for nothing",
                Detail = string.Join(", ", parts.ToArray()) + ". The PhysBone optimizer shows each one.",
                FixLabel = "Fix them",
                Fix = () => Debug.Log("[WPFMA-SDK] " + WPFMAPhysBoneOptimizer.Apply(report, new WPFMAPhysBoneOptimizer.Fixes())),
                ToolPage = 2,
                ToolKey = "WPFMA.Tools.PhysBoneOptimizerExpanded"
            });
        }

        private static void Lighting(GameObject root, List<Issue> issues)
        {
            int choice = WPFMAToolDefaults.BoundsAnchor;
            var state = WPFMABoundsFix.Inspect(root, choice);
            if (state.Renderers < 2)
                return;

            if (!state.NeedsFix)
            {
                issues.Add(Pass("Lighting anchor and bounds match"));
                return;
            }

            var parts = new List<string>();
            if (state.Anchors > 1 || state.WithoutAnchor > 0)
                parts.Add("meshes take their lighting from " + state.Anchors + " different place(s), so parts can be lit differently");
            if (state.ShortBounds > 0)
                parts.Add(state.ShortBounds + " mesh(es) have bounds smaller than the mesh, so they can vanish at some angles");

            bool bounds = WPFMAToolDefaults.BoundsFixBounds;
            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = "Lighting and bounds don't match across the meshes",
                Detail = string.Join("; ", parts.ToArray()) + ".",
                FixLabel = "Fix them",
                Fix = () => Debug.Log("[WPFMA-SDK] " + WPFMABoundsFix.Apply(root, choice, bounds)),
                ToolPage = 2,
                ToolKey = "WPFMA.Tools.BoundsFixExpanded"
            });
        }

        private static void Blueprint(GameObject root, List<Issue> issues)
        {
            var pipeline = root.GetComponent<VRC.Core.PipelineManager>();
            if (pipeline == null)
            {
                issues.Add(Pass("No upload ID yet - it will upload as a new avatar"));
                return;
            }

            var serialized = new SerializedObject(pipeline);
            var property = serialized.FindProperty("blueprintId");
            string id = property != null ? property.stringValue : null;

            if (string.IsNullOrEmpty(id))
            {
                issues.Add(Pass("No upload ID yet - it will upload as a new avatar"));
                return;
            }

            issues.Add(new Issue
            {
                Severity = Severity.Info,
                Title = "Will update the existing upload " + id,
                Detail = "Fine if that upload is yours. If this avatar came from someone else (a rip or a shared project), " +
                         "the upload fails - clear it to upload as a new avatar.",
                FixLabel = "Clear the ID",
                Fix = () =>
                {
                    var fresh = new SerializedObject(pipeline);
                    var idProperty = fresh.FindProperty("blueprintId");
                    if (idProperty == null)
                        return;
                    idProperty.stringValue = string.Empty;
                    fresh.ApplyModifiedProperties();
                }
            });
        }

        private static Issue Pass(string title)
        {
            return new Issue { Severity = Severity.Pass, Title = title };
        }
#endif
    }

    internal static class WPFMAPreUploadSection
    {
        private const string PrefKey = "WPFMA.Tools.PreUploadExpanded";

        private static GameObject checkedRoot;
        private static List<WPFMAPreUploadCheck.Issue> issues;
        private static bool showPasses;

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

            WPFMAToolSection.Draw(sectionStyle, "Pre-upload check", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            if (issues == null || checkedRoot == null)
                return "not run yet";

            int errors = issues.Count(i => i.Severity == WPFMAPreUploadCheck.Severity.Error);
            int warnings = issues.Count(i => i.Severity == WPFMAPreUploadCheck.Severity.Warning);
            if (errors + warnings == 0)
                return "all clear";

            return errors + " error(s), " + warnings + " warning(s)";
        }

#if !WPFMA_VRC_AVATARS
        private static void Body()
        {
            EditorGUILayout.HelpBox("This needs the VRChat avatar SDK, which is not in this project yet.", MessageType.Info);
        }
#else
        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Every check before you upload.", "One button that runs every check before you upload: missing scripts, pink materials, view position, " + "parameters, menus, write defaults, broken animations, face tracking, lip sync, rank and the upload ID."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject) ?? (checkedRoot != null && issues != null ? checkedRoot : null);
            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(checkedRoot == root && issues != null ? "Check again" : "Run check", GUILayout.Width(110f), GUILayout.Height(22f)))
                {
                    var target = root;
                    EditorApplication.delayCall += () => Run(target);
                }
            }

            if (issues == null || checkedRoot != root)
                return;

            var problems = issues.Where(i => i.Severity != WPFMAPreUploadCheck.Severity.Pass).ToList();
            var passes = issues.Where(i => i.Severity == WPFMAPreUploadCheck.Severity.Pass).ToList();

            if (problems.Count == 0)
            {
                EditorGUILayout.Space(4f);
                EditorGUILayout.LabelField("Everything checks out - ready to upload.",
                    new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = WPFMAToolSection.OkGreen } });
            }

            foreach (var issue in problems)
                DrawIssue(root, issue);

            EditorGUILayout.Space(4f);
            showPasses = EditorGUILayout.Foldout(showPasses, passes.Count + " check(s) passed", true);
            if (showPasses)
            {
                foreach (var pass in passes)
                    EditorGUILayout.LabelField("✓  " + pass.Title, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
            }
        }

        private static void Run(GameObject root)
        {
            checkedRoot = root;
            try
            {
                issues = WPFMAPreUploadCheck.Run(root);
            }
            catch (Exception e)
            {
                issues = new List<WPFMAPreUploadCheck.Issue>
                {
                    new WPFMAPreUploadCheck.Issue { Severity = WPFMAPreUploadCheck.Severity.Error, Title = "The check failed", Detail = e.Message }
                };
                Debug.LogWarning("[WPFMA-SDK] Pre-upload check failed: " + e);
            }
        }

        private static void DrawIssue(GameObject root, WPFMAPreUploadCheck.Issue issue)
        {
            Color color;
            string mark;
            switch (issue.Severity)
            {
                case WPFMAPreUploadCheck.Severity.Error:
                    color = WPFMAToolSection.ErrorRed;
                    mark = "✖";
                    break;
                case WPFMAPreUploadCheck.Severity.Warning:
                    color = WPFMAToolSection.WarnAmber;
                    mark = "▲";
                    break;
                default:
                    color = WPFMAToolSection.AccentBlue;
                    mark = "●";
                    break;
            }

            EditorGUILayout.Space(4f);
            var rect = EditorGUILayout.BeginVertical();
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, 3f, rect.height), color);

            EditorGUILayout.LabelField(mark + "  " + issue.Title,
                new GUIStyle(EditorStyles.boldLabel) { wordWrap = true, normal = { textColor = color } });

            if (!string.IsNullOrEmpty(issue.Detail))
                EditorGUILayout.LabelField(issue.Detail, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(14f);

                if (issue.Fix != null && GUILayout.Button(issue.FixLabel ?? "Fix", EditorStyles.miniButton, GUILayout.Width(150f)))
                {
                    var fix = issue.Fix;
                    var chosen = issue;
                    EditorApplication.delayCall += () =>
                    {
                        WPFMAChangeLog.Run("Pre-upload check", "\"" + chosen.FixLabel + "\" - " + chosen.Title, chosen.Assets, chosen.Scene,
                            () => { fix(); return "Fixed: " + chosen.Title; });
                        Run(root);
                    };
                }

                if (issue.Show != null && issue.Show.Length > 0 && GUILayout.Button("Show", EditorStyles.miniButton, GUILayout.Width(60f)))
                    Selection.objects = issue.Show.Where(o => o != null).ToArray();

                if (issue.ToolPage >= 0 && GUILayout.Button("Open the tool", EditorStyles.miniButton, GUILayout.Width(100f)))
                {
                    int page = issue.ToolPage;
                    string key = issue.ToolKey;
                    EditorApplication.delayCall += () => WPFMAToolSection.Reveal(page, key);
                }

                GUILayout.FlexibleSpace();
            }

            EditorGUILayout.EndVertical();
        }
#endif
    }
}
#endif
