using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VCam.Exporter.Gltf;
using VRC.Dynamics;
using VRC.SDK3.Dynamics.PhysBone.Components;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Approximates PhysBones as standard VRMC_springBone so other VRM apps (and our web app before the
    /// PhysBone solver in M5) still get swaying hair/tails. The exact parameters live in VCAM_physbones.
    ///
    /// Mapping (approximate, D-022):
    /// - chains: PhysBone root + descendants minus ignoreTransforms; a VRM spring cannot branch, so every branch
    ///   starts a new spring. Root with several children and multiChildType=Ignore → chains start at the children.
    /// - endpointPosition: adds a virtual tail node so the leaf bone swings like in PhysBone.
    /// - stiffness = 4·pull + 2·stiffness, dragForce = 0.4 + 0.5·(1 − spring), gravityPower = |gravity|,
    ///   hitRadius = radius; curves are evaluated at the joint's normalized depth.
    /// - not representable: immobile, angle limits, stretch/squish, grab/pose (reported as notes).
    /// - colliders: sphere and capsule; plane and inside-bounds colliders are skipped.
    /// </summary>
    internal static class SpringBoneFallback
    {
        public static void Write(GltfBuilder b, GameObject root, Dictionary<Transform, int> nodeOf, ExportReport report)
        {
            var physBones = root.GetComponentsInChildren<VRCPhysBone>(true).Where(p => p.enabled && p.gameObject.activeInHierarchy).ToArray();
            if (physBones.Length == 0) return;

            var colliders = new JArr();
            var colliderOf = new Dictionary<VRCPhysBoneColliderBase, int>();
            var groups = new JArr();
            var groupOf = new Dictionary<string, int>();
            var springs = new JArr();
            var skippedColliders = 0;
            var usesLimits = false;
            var usesImmobile = false;
            var usesStretch = false;

            int? Collider(VRCPhysBoneColliderBase c)
            {
                // A collider on a switched-off object (a hat or outfit toggled off) does not collide in VRChat (D-078).
                if (c == null || !c.enabled || !c.gameObject.activeInHierarchy) return null;
                if (colliderOf.TryGetValue(c, out var existing)) return existing;
                var t = c.rootTransform != null ? c.rootTransform : c.transform;
                if (!nodeOf.TryGetValue(t, out var node)) return null;
                JObj shape;
                if (c.insideBounds || c.shapeType == VRCPhysBoneColliderBase.ShapeType.Plane)
                {
                    skippedColliders++;
                    return null;
                }
                if (c.shapeType == VRCPhysBoneColliderBase.ShapeType.Capsule)
                {
                    var half = Mathf.Max(0f, c.height * 0.5f - c.radius);
                    var axis = c.rotation * Vector3.up * half;
                    shape = new JObj
                    {
                        ["capsule"] = new JObj
                        {
                            ["offset"] = UnityToGltf.Pos(c.position + axis),
                            ["radius"] = c.radius,
                            ["tail"] = UnityToGltf.Pos(c.position - axis),
                        },
                    };
                }
                else
                {
                    shape = new JObj { ["sphere"] = new JObj { ["offset"] = UnityToGltf.Pos(c.position), ["radius"] = c.radius } };
                }
                colliders.Add(new JObj { ["node"] = node, ["shape"] = shape });
                colliderOf[c] = colliders.Count - 1;
                return colliders.Count - 1;
            }

            foreach (var pb in physBones)
            {
                var rootT = pb.rootTransform != null ? pb.rootTransform : pb.transform;
                var ignored = new HashSet<Transform>(pb.ignoreTransforms.Where(t => t != null));
                usesLimits |= pb.limitType != VRCPhysBoneBase.LimitType.None;
                usesImmobile |= pb.immobile > 0f;
                usesStretch |= pb.maxStretch > 0f || pb.maxSquish > 0f;

                List<Transform> Children(Transform t) => t.Cast<Transform>().Where(c => !ignored.Contains(c) && nodeOf.ContainsKey(c)).ToList();

                // Chains, splitting at branches.
                var chains = new List<List<Transform>>();
                var starts = new Queue<Transform>();
                var rootChildren = Children(rootT);
                if (rootChildren.Count > 1 && pb.multiChildType == VRCPhysBoneBase.MultiChildType.Ignore)
                    foreach (var c in rootChildren) starts.Enqueue(c);
                else
                    starts.Enqueue(rootT);
                while (starts.Count > 0)
                {
                    var chain = new List<Transform>();
                    var t = starts.Dequeue();
                    while (true)
                    {
                        chain.Add(t);
                        var kids = Children(t);
                        if (kids.Count == 0) break;
                        if (kids.Count > 1)
                        {
                            foreach (var k in kids.Skip(1)) starts.Enqueue(k);
                        }
                        t = kids[0];
                    }
                    chains.Add(chain);
                }

                // Collider group for this PhysBone's collider set.
                var colliderIdx = pb.colliders.Select(Collider).Where(i => i.HasValue).Select(i => i.Value).Distinct().OrderBy(i => i).ToList();
                int? groupIndex = null;
                if (colliderIdx.Count > 0)
                {
                    var key = string.Join(",", colliderIdx);
                    if (!groupOf.TryGetValue(key, out var g))
                    {
                        groups.Add(new JObj { ["name"] = pb.name + " colliders", ["colliders"] = colliderIdx.Cast<object>().ToList() });
                        g = groups.Count - 1;
                        groupOf[key] = g;
                    }
                    groupIndex = g;
                }

                var maxDepth = Mathf.Max(1, chains.Max(c => Depth(c[c.Count - 1], rootT)));
                foreach (var chain in chains)
                {
                    var joints = new JArr();
                    foreach (var t in chain)
                    {
                        var depth = (float)Depth(t, rootT) / maxDepth;
                        joints.Add(Joint(nodeOf[t], pb, depth));
                    }
                    // Virtual tail so the last real bone also swings (PhysBone endpointPosition).
                    var leaf = chain[chain.Count - 1];
                    if (pb.endpointPosition != Vector3.zero)
                    {
                        var tail = b.AddNode(new JObj { ["name"] = leaf.name + "_vcam_end", ["translation"] = UnityToGltf.Pos(pb.endpointPosition) });
                        var leafNode = b.Node(nodeOf[leaf]);
                        if (!(leafNode.TryGetValue("children", out var ch) && ch is JArr kids))
                        {
                            kids = new JArr();
                            leafNode["children"] = kids;
                        }
                        kids.Add(tail);
                        joints.Add(Joint(tail, pb, 1f));
                    }
                    if (joints.Count < 2) continue; // a single joint has no direction to swing along
                    var spring = new JObj { ["name"] = pb.name, ["joints"] = joints };
                    if (groupIndex.HasValue) spring["colliderGroups"] = new JArr { groupIndex.Value };
                    springs.Add(spring);
                }
            }

            if (springs.Count == 0) return;
            var ext = new JObj { ["specVersion"] = "1.0", ["springs"] = springs };
            if (colliders.Count > 0) ext["colliders"] = colliders;
            if (groups.Count > 0) ext["colliderGroups"] = groups;
            b.Extensions["VRMC_springBone"] = ext;
            b.UseExtension("VRMC_springBone");

            report.Stat("폴백 SpringBone 체인", springs.Count);
            if (skippedColliders > 0) report.Note($"평면·내부 충돌 콜라이더 {skippedColliders}개는 폴백 SpringBone에 넣지 않았습니다(VCAM_physbones에는 있음).");
            var lost = new List<string>();
            if (usesLimits) lost.Add("각도 제한");
            if (usesImmobile) lost.Add("Immobile");
            if (usesStretch) lost.Add("늘어남·찌그러짐");
            if (lost.Count > 0)
                report.Note($"폴백 SpringBone은 {string.Join(", ", lost)}을 표현하지 못합니다. 웹앱은 VCAM_physbones로 원래 값을 씁니다(M5).");
        }

        private static int Depth(Transform t, Transform root)
        {
            var d = 0;
            for (var cur = t; cur != null && cur != root; cur = cur.parent) d++;
            return d;
        }

        private static float Eval(float value, AnimationCurve curve, float t) =>
            curve != null && curve.length > 0 ? value * curve.Evaluate(t) : value;

        private static JObj Joint(int node, VRCPhysBone pb, float t)
        {
            var pull = Eval(pb.pull, pb.pullCurve, t);
            var spring = Eval(pb.spring, pb.springCurve, t);
            var stiffness = Eval(pb.stiffness, pb.stiffnessCurve, t);
            var gravity = Eval(pb.gravity, pb.gravityCurve, t);
            var radius = Eval(pb.radius, pb.radiusCurve, t);
            return new JObj
            {
                ["node"] = node,
                ["hitRadius"] = Mathf.Max(0f, radius),
                ["stiffness"] = Mathf.Clamp(4f * pull + 2f * stiffness, 0f, 4f),
                ["gravityPower"] = Mathf.Abs(gravity),
                ["gravityDir"] = gravity >= 0f ? new[] { 0f, -1f, 0f } : new[] { 0f, 1f, 0f },
                ["dragForce"] = Mathf.Clamp01(0.4f + 0.5f * (1f - spring)),
            };
        }
    }
}
