using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using VCam.Exporter.Gltf;
using JObj = System.Collections.Generic.Dictionary<string, object>;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Approximates VRC constraints as VRMC_node_constraint (rotation / roll / aim, single source).
    /// The exact data lives in VCAM_constraints. Read through reflection because the VRC constraint
    /// components are in a precompiled DLL and we only need a few well-known fields
    /// (Sources[].SourceTransform/Weight, TargetTransform, GlobalWeight, AffectsRotationX/Y/Z, AimAxis).
    /// Parent/position/scale constraints have no VRM equivalent and are only reported.
    /// Unity constraints are converted to VRC constraints by the VRChat build (seen in M0), so they are not
    /// handled here.
    /// </summary>
    internal static class NodeConstraintFallback
    {
        public static void Write(GltfBuilder b, GameObject root, Dictionary<Transform, int> nodeOf, ExportReport report)
        {
            var written = 0;
            var unsupported = new SortedDictionary<string, int>();
            foreach (var c in root.GetComponentsInChildren<Component>(true))
            {
                if (!VcamExtensions.IsVrcConstraint(c) || !c.gameObject.activeInHierarchy || (c is Behaviour behaviour && !behaviour.enabled)) continue;
                if (!Get(c, "IsActive", true) || !Get(c, "Locked", true)) continue;

                var target = Get<Transform>(c, "TargetTransform") ?? c.transform;
                if (!nodeOf.TryGetValue(target, out var targetNode)) continue;

                var (source, sourceWeight, sourceCount) = FirstSource(c);
                if (source == null || !nodeOf.TryGetValue(source, out var sourceNode)) continue;
                var weight = Mathf.Clamp01(Get(c, "GlobalWeight", 1f) * sourceWeight);
                var typeName = c.GetType().Name;

                JObj constraint = null;
                if (typeName == "VRCRotationConstraint")
                {
                    var x = Get(c, "AffectsRotationX", true);
                    var y = Get(c, "AffectsRotationY", true);
                    var z = Get(c, "AffectsRotationZ", true);
                    var axes = (x ? 1 : 0) + (y ? 1 : 0) + (z ? 1 : 0);
                    if (axes == 3)
                        constraint = new JObj { ["rotation"] = new JObj { ["source"] = sourceNode, ["weight"] = weight } };
                    else if (axes == 1)
                        constraint = new JObj { ["roll"] = new JObj { ["source"] = sourceNode, ["rollAxis"] = x ? "X" : y ? "Y" : "Z", ["weight"] = weight } };
                }
                else if (typeName == "VRCAimConstraint" || typeName == "VRCLookAtConstraint")
                {
                    var axis = Get(c, "AimAxis", Vector3.forward);
                    constraint = new JObj { ["aim"] = new JObj { ["source"] = sourceNode, ["aimAxis"] = AimAxisName(axis), ["weight"] = weight } };
                }

                if (constraint == null)
                {
                    unsupported[typeName] = unsupported.TryGetValue(typeName, out var n) ? n + 1 : 1;
                    continue;
                }
                if (sourceCount > 1)
                    report.Note($"'{c.name}'의 {typeName}는 소스가 {sourceCount}개지만 폴백에는 첫 소스만 넣었습니다.");

                var node = b.Node(targetNode);
                if (!(node.TryGetValue("extensions", out var e) && e is JObj ext))
                {
                    ext = new JObj();
                    node["extensions"] = ext;
                }
                ext["VRMC_node_constraint"] = new JObj { ["specVersion"] = "1.0", ["constraint"] = constraint };
                written++;
            }

            if (written > 0)
            {
                b.UseExtension("VRMC_node_constraint");
                report.Stat("폴백 노드 컨스트레인트", written);
            }
            foreach (var kv in unsupported)
                report.Note($"{kv.Key} {kv.Value}개는 VRM 표준에 대응하는 컨스트레인트가 없어 VCAM_constraints에만 넣었습니다.");
        }

        /// <summary>X-mirror flips the X axis direction (D-018), so PositiveX ↔ NegativeX.</summary>
        private static string AimAxisName(Vector3 axis)
        {
            var a = new Vector3(Mathf.Abs(axis.x), Mathf.Abs(axis.y), Mathf.Abs(axis.z));
            if (a.x >= a.y && a.x >= a.z) return axis.x >= 0 ? "NegativeX" : "PositiveX";
            if (a.y >= a.z) return axis.y >= 0 ? "PositiveY" : "NegativeY";
            return axis.z >= 0 ? "PositiveZ" : "NegativeZ";
        }

        private static (Transform source, float weight, int count) FirstSource(Component c)
        {
            if (!(Field(c, "Sources") is IEnumerable sources)) return (null, 0f, 0);
            Transform first = null;
            var firstWeight = 0f;
            var count = 0;
            foreach (var s in sources)
            {
                if (s == null) continue;
                var t = Field(s, "SourceTransform") as Transform;
                if (t == null) continue;
                count++;
                if (first == null)
                {
                    first = t;
                    firstWeight = Field(s, "Weight") is float w ? w : 1f;
                }
            }
            return (first, firstWeight, count);
        }

        private static object Field(object o, string name)
        {
            var t = o.GetType();
            var f = t.GetField(name, BindingFlags.Public | BindingFlags.Instance);
            if (f != null) return f.GetValue(o);
            var p = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            return p != null && p.GetIndexParameters().Length == 0 ? p.GetValue(o) : null;
        }

        private static T Get<T>(object o, string name, T fallback = default)
        {
            var v = Field(o, name);
            if (v is T typed)
            {
                // Unity fake null for Transform references.
                if (v is Object uo && uo == null) return fallback;
                return typed;
            }
            return fallback;
        }
    }
}
