using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;

namespace VCam.Exporter.Util
{
    /// <summary>How object references inside a dump are written.</summary>
    internal sealed class RefResolver
    {
        /// <summary>Transform → path relative to the avatar root ("" = root, null = outside the avatar).</summary>
        public Func<Transform, string> Path;
        /// <summary>Optional: Transform → glTF node index (null = not exported).</summary>
        public Func<Transform, int?> Node;
        /// <summary>Optional: Component → id in our own list (e.g. collider index inside VCAM_physbones).</summary>
        public Func<Component, int?> ComponentId;
    }

    /// <summary>
    /// Converts every public instance field of a component (PhysBone, collider, constraint, ...) into a
    /// plain object graph (dictionaries/lists) by reflection, ready for JsonWriter.Any or a glTF extension.
    ///
    /// Why reflection instead of hand-written field lists (D-003):
    /// - The VRChat SDK ships PhysBone etc. as precompiled DLLs and adds fields between versions.
    ///   Dumping all public fields means a new SDK field is exported automatically.
    /// - The "export exactly what Unity shows" requirement means we must not silently drop parameters.
    /// References are written as {"$ref": kind, "path": ..., "node": ..., "id": ...}.
    /// </summary>
    internal static class ReflectionDump
    {
        private const int MaxDepth = 4;

        /// <summary>Fields that only drive the Unity inspector/gizmos or runtime parameters, never the result.</summary>
        public static bool IsEditorOnlyField(FieldInfo f)
        {
            var n = f.Name;
            return n.StartsWith("foldout", StringComparison.Ordinal)
                   || n.StartsWith("param_", StringComparison.Ordinal)
                   || n == "showGizmos" || n == "boneOpacity" || n == "limitOpacity"
                   || typeof(Delegate).IsAssignableFrom(f.FieldType)
                   || typeof(UnityEngine.Events.UnityEventBase).IsAssignableFrom(f.FieldType);
        }

        /// <param name="skip">Optional field filter (e.g. <see cref="IsEditorOnlyField"/>).</param>
        public static JObj Component(Component c, RefResolver r, Func<FieldInfo, bool> skip = null)
        {
            var obj = new JObj
            {
                ["type"] = c.GetType().FullName,
                ["path"] = r.Path(c.transform),
            };
            var node = r.Node?.Invoke(c.transform);
            if (node.HasValue) obj["node"] = node.Value;
            obj["enabled"] = !(c is Behaviour b) || b.enabled;
            obj["fields"] = Fields(c, r, 0, skip);
            return obj;
        }

        private static JObj Fields(object target, RefResolver r, int depth, Func<FieldInfo, bool> skip)
        {
            var obj = new JObj();
            foreach (var f in target.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                if (f.IsDefined(typeof(NonSerializedAttribute), true)) continue;
                if (skip != null && skip(f)) continue;
                object v;
                try
                {
                    v = f.GetValue(target);
                }
                catch
                {
                    continue;
                }
                obj[f.Name] = Value(v, r, depth + 1, skip);
            }
            return obj;
        }

        public static object Value(object v, RefResolver r, int depth, Func<FieldInfo, bool> skip = null)
        {
            // Unity "fake null": destroyed or missing object references compare equal to null.
            if (v == null || (v is UnityEngine.Object uo && uo == null)) return null;

            switch (v)
            {
                case bool _:
                case string _:
                case float _:
                case double _:
                case int _:
                case long _:
                case uint _:
                case short _:
                case byte _:
                    return v;
                case Enum e: return e.ToString();
                case Vector2 v2: return new[] { v2.x, v2.y };
                case Vector3 v3: return new[] { v3.x, v3.y, v3.z };
                case Vector4 v4: return new[] { v4.x, v4.y, v4.z, v4.w };
                case Quaternion q: return new[] { q.x, q.y, q.z, q.w };
                case Color col: return new[] { col.r, col.g, col.b, col.a };
                case AnimationCurve curve: return Curve(curve);
                case Transform t: return TransformRef("transform", t, r);
                case GameObject go: return TransformRef("gameObject", go.transform, r);
                case Component comp:
                {
                    var o = TransformRef("component", comp.transform, r);
                    o["type"] = comp.GetType().FullName;
                    o["index"] = IndexAmongSameType(comp);
                    var id = r.ComponentId?.Invoke(comp);
                    if (id.HasValue) o["id"] = id.Value;
                    return o;
                }
                case UnityEngine.Object asset:
                    return new JObj { ["$ref"] = "asset", ["type"] = asset.GetType().FullName, ["name"] = asset.name };
                case IList list:
                {
                    var arr = new JArr();
                    if (depth < MaxDepth)
                        foreach (var item in list) arr.Add(Value(item, r, depth + 1, skip));
                    return arr;
                }
            }

            var type = v.GetType();
            if (depth < MaxDepth && (type.IsValueType || type.IsDefined(typeof(SerializableAttribute), false)))
                return Fields(v, r, depth, skip);
            return v.ToString();
        }

        private static JObj TransformRef(string kind, Transform t, RefResolver r)
        {
            var o = new JObj { ["$ref"] = kind, ["path"] = r.Path(t) };
            var node = r.Node?.Invoke(t);
            if (node.HasValue) o["node"] = node.Value;
            return o;
        }

        /// <summary>Curve keys: [time, value, inTangent, outTangent, inWeight, outWeight, weightedMode].</summary>
        public static JObj Curve(AnimationCurve curve)
        {
            var keys = new JArr();
            foreach (var k in curve.keys)
                keys.Add(new object[] { k.time, k.value, k.inTangent, k.outTangent, k.inWeight, k.outWeight, (int)k.weightedMode });
            return new JObj
            {
                ["preWrapMode"] = curve.preWrapMode.ToString(),
                ["postWrapMode"] = curve.postWrapMode.ToString(),
                ["keys"] = keys,
            };
        }

        /// <summary>Index among components of the same type on the same GameObject (to disambiguate references).</summary>
        public static int IndexAmongSameType(Component comp)
        {
            var all = comp.GetComponents(comp.GetType());
            return Array.IndexOf(all, comp);
        }
    }
}
