using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
using VCam.Exporter.Export;
using VRC.SDK3.Avatars.Components;
using Object = UnityEngine.Object;

namespace VCam.Exporter.Pipeline
{
    /// <summary>
    /// Applies the "in-game default" state (D-025) to a BAKED clone: the pose of objects, blendshapes and
    /// materials the avatar starts with in VRChat, which can differ from the editor scene (e.g. a toggle whose
    /// object is enabled in the scene but switched off by its default parameter).
    ///
    /// How:
    /// 1. Take the FX controller from the descriptor (after the bake it already contains MA/VRCFury layers).
    /// 2. Default parameter values = animator parameter defaults, overridden by the expression parameters'
    ///    defaultValue, plus fixed values for VRChat built-in parameters (remote view: IsLocal = false).
    /// 3. Per layer (weight > 0, top to bottom): start at the default state and follow transitions whose
    ///    conditions hold (any-state first; exit-time-only transitions count as "time passes"), up to 8 hops.
    /// 4. Sample that state's motion at t = 0 and write the values into the clone. Direct blend trees use
    ///    the default parameter of each child as its weight; 1D/2D trees pick the child nearest the default.
    /// Material curves change per-renderer COPIES of the materials, never the user's material assets.
    /// Approximations (reported): only FX, child weights below 0.5 are skipped, no blending between layers.
    /// </summary>
    internal static class StateSampler
    {
        private const int MaxHops = 8;

        /// <summary>VRChat built-in parameters with the values an avatar has when idle, seen by others.</summary>
        private static readonly Dictionary<string, float> BuiltIn = new Dictionary<string, float>
        {
            ["IsLocal"] = 0, ["Grounded"] = 1, ["Upright"] = 1, ["Seated"] = 0, ["AFK"] = 0, ["InStation"] = 0,
            ["MuteSelf"] = 0, ["Earmuffs"] = 0, ["IsOnFriendsList"] = 0, ["ScaleFactor"] = 1, ["ScaleModified"] = 0,
            ["Viseme"] = 0, ["Voice"] = 0, ["GestureLeft"] = 0, ["GestureRight"] = 0, ["GestureLeftWeight"] = 0,
            ["GestureRightWeight"] = 0, ["VelocityX"] = 0, ["VelocityY"] = 0, ["VelocityZ"] = 0, ["VelocityMagnitude"] = 0,
            ["AngularY"] = 0, ["TrackingType"] = 0, ["VRMode"] = 0, ["IsAnimatorEnabled"] = 1, ["PreviewMode"] = 0,
        };

        private sealed class Stats
        {
            public int Layers;
            public int Values;
            public int Skipped;
            public readonly HashSet<string> SkippedKinds = new HashSet<string>();
            public readonly Dictionary<Renderer, bool> CopiedMaterials = new Dictionary<Renderer, bool>();
        }

        public static void ApplyInGameDefault(GameObject root, ExportReport report)
        {
            var d = root.GetComponent<VRCAvatarDescriptor>();
            AnimatorController fx = null;
            if (d != null && d.customizeAnimationLayers)
            {
                foreach (var layer in d.baseAnimationLayers)
                {
                    if (layer.type == VRCAvatarDescriptor.AnimLayerType.FX && !layer.isDefault && layer.animatorController != null)
                        fx = layer.animatorController as AnimatorController;
                }
            }
            if (fx == null)
            {
                report.Note("FX 애니메이터가 없어 게임 기본 상태가 씬 상태와 같습니다.");
                return;
            }

            var parameters = DefaultParameters(fx, d);
            var stats = new Stats();
            var layers = fx.layers;
            for (var i = 0; i < layers.Length; i++)
            {
                var layer = layers[i];
                var weight = i == 0 ? 1f : layer.defaultWeight;
                if (weight <= 0f) continue;
                var source = layer.syncedLayerIndex >= 0 && layer.syncedLayerIndex < layers.Length ? layers[layer.syncedLayerIndex] : layer;
                var state = ResolveState(source.stateMachine, parameters);
                if (state == null) continue;
                var motion = layer.syncedLayerIndex >= 0 ? layer.GetOverrideMotion(state) ?? state.motion : state.motion;
                if (motion == null) continue;
                stats.Layers++;
                ApplyMotion(root, motion, parameters, 1f, stats);
            }

            report.Stat("게임 기본 상태: 적용한 FX 레이어", stats.Layers);
            report.Stat("게임 기본 상태: 적용한 값", stats.Values);
            if (stats.Skipped > 0)
                report.Note($"게임 기본 상태: 지원하지 않는 애니메이션 속성 {stats.Skipped}개는 건너뜀({string.Join(", ", stats.SkippedKinds.Take(6))})");
            report.Note("게임 기본 상태는 FX 레이어만 보고, 다른 사람에게 보이는 모습(IsLocal = false) 기준으로 계산했습니다.");
            var saved = d.expressionParameters != null && d.expressionParameters.parameters != null
                ? d.expressionParameters.parameters.Count(ep => ep != null && ep.saved && !string.IsNullOrEmpty(ep.name))
                : 0;
            if (saved > 0)
                report.Note($"저장되는(saved) 파라미터 {saved}개는 실제 VRChat에서 마지막으로 쓴 값으로 복원될 수 있습니다. 여기서는 처음 들어갔을 때의 기본값으로 계산했습니다.");
        }

        private static Dictionary<string, float> DefaultParameters(AnimatorController fx, VRCAvatarDescriptor d)
        {
            var p = new Dictionary<string, float>(BuiltIn);
            foreach (var ap in fx.parameters)
            {
                if (BuiltIn.ContainsKey(ap.name)) continue;
                switch (ap.type)
                {
                    case AnimatorControllerParameterType.Float: p[ap.name] = ap.defaultFloat; break;
                    case AnimatorControllerParameterType.Int: p[ap.name] = ap.defaultInt; break;
                    default: p[ap.name] = ap.defaultBool ? 1f : 0f; break;
                }
            }
            if (d != null && d.expressionParameters != null && d.expressionParameters.parameters != null)
            {
                foreach (var ep in d.expressionParameters.parameters)
                    if (ep != null && !string.IsNullOrEmpty(ep.name)) p[ep.name] = ep.defaultValue;
            }
            return p;
        }

        private static float Param(Dictionary<string, float> p, string name) => name != null && p.TryGetValue(name, out var v) ? v : 0f;

        private static bool Pass(AnimatorCondition[] conditions, Dictionary<string, float> p)
        {
            foreach (var c in conditions)
            {
                var v = Param(p, c.parameter);
                bool ok;
                switch (c.mode)
                {
                    case AnimatorConditionMode.If: ok = v != 0f; break;
                    case AnimatorConditionMode.IfNot: ok = v == 0f; break;
                    case AnimatorConditionMode.Greater: ok = v > c.threshold; break;
                    case AnimatorConditionMode.Less: ok = v < c.threshold; break;
                    case AnimatorConditionMode.Equals: ok = Mathf.Approximately(v, c.threshold); break;
                    case AnimatorConditionMode.NotEqual: ok = !Mathf.Approximately(v, c.threshold); break;
                    default: ok = false; break;
                }
                if (!ok) return false;
            }
            return true;
        }

        private static AnimatorState Destination(AnimatorStateTransition t) =>
            t.destinationState != null ? t.destinationState
            : t.destinationStateMachine != null ? t.destinationStateMachine.defaultState
            : null;

        private static AnimatorState ResolveState(AnimatorStateMachine sm, Dictionary<string, float> p)
        {
            var current = sm.defaultState;
            if (current == null) return null;
            for (var hop = 0; hop < MaxHops; hop++)
            {
                AnimatorState next = null;
                foreach (var t in sm.anyStateTransitions)
                {
                    var dest = Destination(t);
                    if (dest == null || (dest == current && !t.canTransitionToSelf)) continue;
                    if (t.conditions.Length > 0 && Pass(t.conditions, p))
                    {
                        next = dest;
                        break;
                    }
                }
                if (next == null)
                {
                    foreach (var t in current.transitions)
                    {
                        if (t.isExit || t.mute) continue;
                        var dest = Destination(t);
                        if (dest == null) continue;
                        // Conditionless transitions only fire through exit time (time passing).
                        if ((t.conditions.Length > 0 || t.hasExitTime) && Pass(t.conditions, p))
                        {
                            next = dest;
                            break;
                        }
                    }
                }
                if (next == null || next == current) break;
                current = next;
            }
            return current;
        }

        private static void ApplyMotion(GameObject root, Motion motion, Dictionary<string, float> p, float weight, Stats s)
        {
            if (weight < 0.5f) return;
            if (motion is AnimationClip clip)
            {
                ApplyClip(root, clip, s);
                return;
            }
            if (!(motion is BlendTree tree) || tree.children.Length == 0) return;
            switch (tree.blendType)
            {
                case BlendTreeType.Direct:
                    foreach (var child in tree.children)
                        ApplyMotion(root, child.motion, p, weight * Param(p, child.directBlendParameter), s);
                    break;
                case BlendTreeType.Simple1D:
                {
                    var v = Param(p, tree.blendParameter);
                    var best = tree.children.OrderBy(c => Mathf.Abs(c.threshold - v)).First();
                    ApplyMotion(root, best.motion, p, weight, s);
                    break;
                }
                default: // 2D variants
                {
                    var v = new Vector2(Param(p, tree.blendParameter), Param(p, tree.blendParameterY));
                    var best = tree.children.OrderBy(c => (c.position - v).sqrMagnitude).First();
                    ApplyMotion(root, best.motion, p, weight, s);
                    break;
                }
            }
        }

        private static void ApplyClip(GameObject root, AnimationClip clip, Stats s)
        {
            foreach (var b in AnimationUtility.GetCurveBindings(clip))
            {
                var t = b.path.Length == 0 ? root.transform : root.transform.Find(b.path);
                if (t == null) continue;
                var curve = AnimationUtility.GetEditorCurve(clip, b);
                if (curve == null) continue;
                var v = curve.Evaluate(0f);
                if (ApplyFloat(t, b, v, s)) s.Values++;
                else
                {
                    s.Skipped++;
                    s.SkippedKinds.Add($"{b.type.Name}.{b.propertyName}");
                }
            }
            foreach (var b in AnimationUtility.GetObjectReferenceCurveBindings(clip))
            {
                var t = b.path.Length == 0 ? root.transform : root.transform.Find(b.path);
                if (t == null) continue;
                var keys = AnimationUtility.GetObjectReferenceCurve(clip, b);
                if (keys == null || keys.Length == 0) continue;
                if (ApplyObject(t, b, keys[0].value, s)) s.Values++;
                else
                {
                    s.Skipped++;
                    s.SkippedKinds.Add($"{b.type.Name}.{b.propertyName}");
                }
            }
        }

        private static bool ApplyFloat(Transform t, EditorCurveBinding b, float v, Stats s)
        {
            var prop = b.propertyName;
            if (b.type == typeof(GameObject) && prop == "m_IsActive")
            {
                t.gameObject.SetActive(v > 0.5f);
                return true;
            }
            if (b.type == typeof(Transform))
            {
                var axis = prop.Length > 2 && prop[prop.Length - 2] == '.' ? prop[prop.Length - 1] : ' ';
                if (prop.StartsWith("m_LocalPosition.")) t.localPosition = Set(t.localPosition, axis, v);
                else if (prop.StartsWith("m_LocalScale.")) t.localScale = Set(t.localScale, axis, v);
                else if (prop.StartsWith("localEulerAnglesRaw.")) t.localEulerAngles = Set(t.localEulerAngles, axis, v);
                else return false;
                return true;
            }

            var comp = t.GetComponent(b.type);
            if (comp == null) return false;
            if (prop == "m_Enabled")
            {
                if (comp is Behaviour beh) beh.enabled = v > 0.5f;
                else if (comp is Renderer ren) ren.enabled = v > 0.5f;
                else return false;
                return true;
            }
            if (comp is SkinnedMeshRenderer smr && prop.StartsWith("blendShape."))
            {
                var mesh = smr.sharedMesh;
                var idx = mesh != null ? mesh.GetBlendShapeIndex(prop.Substring("blendShape.".Length)) : -1;
                if (idx < 0) return false;
                smr.SetBlendShapeWeight(idx, v);
                return true;
            }
            if (comp is Renderer r && prop.StartsWith("material."))
            {
                // "material._Color.r" / "material._Cutoff"
                var rest = prop.Substring("material.".Length);
                var dot = rest.LastIndexOf('.');
                var channel = dot > 0 && rest.Length - dot == 2 ? rest[rest.Length - 1] : ' ';
                var name = channel != ' ' ? rest.Substring(0, dot) : rest;
                CopyMaterials(r, s);
                var any = false;
                foreach (var m in r.sharedMaterials)
                {
                    if (m == null || !m.HasProperty(name)) continue;
                    any = true;
                    if (channel == ' ') m.SetFloat(name, v);
                    else if (channel == 'r' || channel == 'g' || channel == 'b' || channel == 'a')
                    {
                        var c = m.GetColor(name);
                        if (channel == 'r') c.r = v; else if (channel == 'g') c.g = v; else if (channel == 'b') c.b = v; else c.a = v;
                        m.SetColor(name, c);
                    }
                    else
                    {
                        var vec = m.GetVector(name);
                        if (channel == 'x') vec.x = v; else if (channel == 'y') vec.y = v; else if (channel == 'z') vec.z = v; else if (channel == 'w') vec.w = v;
                        m.SetVector(name, vec);
                    }
                }
                return any;
            }
            return false;
        }

        private static bool ApplyObject(Transform t, EditorCurveBinding b, Object value, Stats s)
        {
            var r = t.GetComponent(b.type) as Renderer;
            const string prefix = "m_Materials.Array.data[";
            if (r == null || !b.propertyName.StartsWith(prefix)) return false;
            if (!int.TryParse(b.propertyName.Substring(prefix.Length).TrimEnd(']'), out var slot)) return false;
            var mats = r.sharedMaterials;
            if (slot < 0 || slot >= mats.Length) return false;
            mats[slot] = value as Material;
            r.sharedMaterials = mats;
            s.CopiedMaterials.Remove(r); // the swapped-in material is an asset again; copy before any property edit
            return true;
        }

        /// <summary>Replaces a renderer's materials with copies once, so property curves never edit project assets.</summary>
        private static void CopyMaterials(Renderer r, Stats s)
        {
            if (s.CopiedMaterials.ContainsKey(r)) return;
            r.sharedMaterials = r.sharedMaterials.Select(m => m != null ? new Material(m) { name = m.name } : null).ToArray();
            s.CopiedMaterials[r] = true;
        }

        private static Vector3 Set(Vector3 v, char axis, float value)
        {
            if (axis == 'x') v.x = value;
            else if (axis == 'y') v.y = value;
            else if (axis == 'z') v.z = value;
            return v;
        }
    }
}
