using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VCam.Exporter.Gltf;
using VCam.Exporter.Pipeline;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Writes a baked avatar (see AvatarBaker) as a VRM 1.0 GLB with our own glTF writer (D-011).
    /// - Every Transform under the avatar root becomes a node, keeping Unity's hierarchy and local TRS,
    ///   so PhysBone/constraint data can refer to nodes by the same paths later (VCAM_* extensions).
    /// - The root node has an identity transform: the avatar is exported at the origin, facing +Z.
    /// - Only renderers that are visible in the scene (active + enabled) get meshes.
    /// </summary>
    internal sealed class VrmWriter
    {
        private readonly ExportOptions _options;
        private readonly ExportReport _report;
        private readonly GltfBuilder _b = new GltfBuilder();
        private readonly Dictionary<Transform, int> _nodeOf = new Dictionary<Transform, int>();
        private readonly Dictionary<SkinnedMeshRenderer, int> _meshNodeOf = new Dictionary<SkinnedMeshRenderer, int>();

        public VrmWriter(ExportOptions options, ExportReport report)
        {
            _options = options;
            _report = report;
        }

        public byte[] Write(GameObject root, string avatarName, string outputPath)
        {
            var tex = new TextureWriter(_b, _report, _options.maxTextureSize);
            var mats = new MaterialWriter(_b, tex, _report);

            _b.SceneRootNode = AddNodeRecursive(root.transform, isRoot: true);
            WriteRenderers(root, mats);

            var descriptor = DescriptorInfo.Read(root);
            var expressions = ExpressionMapper.Map(root, descriptor, _report, _options.expressionOverrides);
            foreach (var (text, warning) in AvatarChecks.Run(root, descriptor, expressions))
                if (warning) _report.Warn(text); else _report.Note(text);
            WriteVrm(root, avatarName, descriptor, expressions);

            JArr references = null;
            if (_options.captureReference)
            {
                try
                {
                    references = ReferenceCapture.Capture(root, outputPath, _report, _nodeOf, _meshNodeOf, expressions);
                }
                catch (Exception e)
                {
                    _report.Warn("기준 스크린샷을 찍지 못했습니다: " + e.Message);
                }
            }

            // Original Unity data for exact reproduction in the web app (docs/FILE_FORMAT.md).
            var physBones = VcamExtensions.PhysBones(root, _nodeOf, _report);
            if (((List<object>)physBones["physBones"]).Count > 0 || ((List<object>)physBones["colliders"]).Count > 0)
                AddExtension("VCAM_physbones", physBones);
            var constraints = VcamExtensions.Constraints(root, _nodeOf, _report);
            if (((List<object>)constraints["constraints"]).Count > 0)
                AddExtension("VCAM_constraints", constraints);
            AddExtension("VCAM_avatar", VcamExtensions.Avatar(root, avatarName, expressions, _report, _options, references, _renderers));

            // Standard-VRM approximations for other apps (and our web app until M5).
            SpringBoneFallback.Write(_b, root, _nodeOf, _report);
            NodeConstraintFallback.Write(_b, root, _nodeOf, _report);
            tex.Dispose();

            _report.Stat("노드", _b.Nodes.Count);
            _report.Stat("메시", _b.Meshes.Count);
            _report.Stat("머티리얼", mats.Count);
            _report.Stat("텍스처", tex.Count);
            _report.Stat("텍스처 PNG 합계(MB)", Math.Round(tex.TotalPngBytes / 1048576.0, 1));
            _report.Stat("표정", expressions.Count);
            return _b.ToGlb();
        }

        private void AddExtension(string name, JObj data)
        {
            _b.Extensions[name] = data;
            _b.UseExtension(name);
        }

        private int AddNodeRecursive(Transform t, bool isRoot)
        {
            var node = new JObj { ["name"] = t.name };
            if (!isRoot)
            {
                if (t.localPosition != Vector3.zero) node["translation"] = UnityToGltf.Pos(t.localPosition);
                if (t.localRotation != Quaternion.identity) node["rotation"] = UnityToGltf.Rot(t.localRotation);
                if (t.localScale != Vector3.one) node["scale"] = new[] { t.localScale.x, t.localScale.y, t.localScale.z };
                if (t.localScale.x < 0 || t.localScale.y < 0 || t.localScale.z < 0)
                    _report.Warn($"'{t.name}'의 스케일이 음수입니다. 좌우 반전 결과가 Unity와 다를 수 있습니다.");
            }
            var index = _b.AddNode(node);
            _nodeOf[t] = index;
            if (t.childCount > 0)
            {
                var children = new JArr();
                foreach (Transform child in t) children.Add(AddNodeRecursive(child, isRoot: false));
                node["children"] = children;
            }
            return index;
        }

        private static bool Visible(Renderer r) => r.enabled && r.gameObject.activeInHierarchy;

        /// <summary>
        /// Per renderer: the transform Unity uses as unity_ObjectToWorld when drawing. For skinned meshes that is the
        /// root bone (usually Hips), not the renderer, and shaders that work in object space depend on it (D-055).
        /// </summary>
        private readonly JArr _renderers = new JArr();

        private void RecordRenderer(int node, int mesh, Transform objectSpace)
        {
            var entry = new JObj { ["node"] = node, ["mesh"] = mesh };
            if (_nodeOf.TryGetValue(objectSpace, out var bone)) entry["objectSpaceNode"] = bone;
            var m = new float[16];
            UnityToGltf.Matrix(objectSpace.localToWorldMatrix, m, 0);
            entry["objectToWorld"] = m;
            _renderers.Add(entry);
        }

        /// <summary>An empty child of <paramref name="parent"/> at its origin: a distinct node with the same world matrix.</summary>
        private int StandInNode(int parent, string name)
        {
            var index = _b.AddNode(new JObj { ["name"] = name });
            var node = _b.Node(parent);
            if (!(node.TryGetValue("children", out var c) && c is JArr children))
            {
                children = new JArr();
                node["children"] = children;
            }
            children.Add(index);
            return index;
        }

        /// <summary>How many of the given bone slots have a vertex weighted to them.</summary>
        private static int WeightedBones(Mesh mesh, List<int> slots)
        {
            var wanted = new HashSet<int>(slots);
            var found = new HashSet<int>();
            // A view into the mesh's own data: not to be disposed.
            var weights = mesh.GetAllBoneWeights();
            for (var i = 0; i < weights.Length; i++)
                if (weights[i].weight > 0f && wanted.Contains(weights[i].boneIndex)) found.Add(weights[i].boneIndex);
            return found.Count;
        }

        private void WriteRenderers(GameObject root, MaterialWriter mats)
        {
            var skipped = 0;
            foreach (var smr in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                if (smr.sharedMesh == null) continue;
                if (!Visible(smr))
                {
                    skipped++;
                    continue;
                }
                var mesh = smr.sharedMesh;
                var bones = smr.bones;
                var skinned = bones != null && bones.Length > 0 && mesh.bindposes.Length == bones.Length;
                if (bones != null && bones.Length > 0 && !skinned)
                    _report.Warn($"'{smr.name}': 뼈 개수({bones.Length})와 바인드포즈 개수({mesh.bindposes.Length})가 달라 스킨 없이 내보냅니다.");

                var written = MeshWriter.Write(_b, mesh, smr.sharedMaterials, mats, smr.name, skinned, _report, _options.exportTangents, bones);
                var nodeIndex = _nodeOf[smr.transform];
                RecordRenderer(nodeIndex, written.MeshIndex, smr.rootBone != null ? smr.rootBone : smr.transform);
                var node = _b.Node(nodeIndex);
                node["mesh"] = written.MeshIndex;
                _meshNodeOf[smr] = nodeIndex;

                if (mesh.blendShapeCount > 0)
                {
                    // Current blendshape values in the scene (body shape keys etc.) become the node's default weights.
                    var weights = new float[mesh.blendShapeCount];
                    for (var i = 0; i < weights.Length; i++) weights[i] = Mathf.Clamp(smr.GetBlendShapeWeight(i) / 100f, 0f, 1f);
                    node["weights"] = weights;
                }

                if (skinned)
                {
                    var joints = new JArr();
                    var missing = new List<int>();
                    var used = new HashSet<int>();
                    for (var b = 0; b < bones.Length; b++)
                    {
                        var bone = bones[b];
                        var found = bone != null && _nodeOf.TryGetValue(bone, out var j) ? j : -1;
                        if (found < 0) missing.Add(b);
                        var at = found >= 0 ? found : _b.SceneRootNode;
                        // glTF wants every joint of a skin to be a different node (DUPLICATE_ELEMENTS otherwise; merged
                        // outfits had dozens of empty slots all on the root, D-078). A repeat gets an empty child node
                        // in the same place, so it still moves exactly like the node it stands for.
                        joints.Add(used.Add(at) ? at : StandInNode(at, $"{smr.name} bone {b}"));
                    }
                    if (missing.Count > 0)
                    {
                        // Merged outfits keep empty slots for bones Modular Avatar removed; they carry no weight, so
                        // only slots that actually move vertices are worth a warning (D-078).
                        var weighted = WeightedBones(mesh, missing);
                        if (weighted > 0) _report.Warn($"'{smr.name}': 아바타 밖이거나 비어 있는 뼈 {missing.Count}개를 루트에 붙였습니다(그중 {weighted}개에 정점이 붙어 있어 그 부분은 몸을 따라가지 않습니다).");
                        else _report.Note($"'{smr.name}': 정점이 붙지 않은 빈 뼈 자리 {missing.Count}개는 루트에 붙였습니다(영향 없음).");
                    }
                    node["skin"] = _b.AddSkin(new JObj
                    {
                        ["joints"] = joints,
                        ["inverseBindMatrices"] = MeshWriter.WriteInverseBindMatrices(_b, mesh.bindposes),
                    });
                }
            }

            foreach (var mr in root.GetComponentsInChildren<MeshRenderer>(true))
            {
                var mf = mr.GetComponent<MeshFilter>();
                if (mf == null || mf.sharedMesh == null) continue;
                if (!Visible(mr))
                {
                    skipped++;
                    continue;
                }
                var written = MeshWriter.Write(_b, mf.sharedMesh, mr.sharedMaterials, mats, mr.name, false, _report, _options.exportTangents);
                _b.Node(_nodeOf[mr.transform])["mesh"] = written.MeshIndex;
                RecordRenderer(_nodeOf[mr.transform], written.MeshIndex, mr.transform);
            }
            if (skipped > 0) _report.Note($"씬에서 꺼져 있는 렌더러 {skipped}개는 내보내지 않았습니다.");
        }

        // ---------------------------------------------------------------- VRMC_vrm

        private static string VrmBoneName(HumanBodyBones bone)
        {
            switch (bone)
            {
                // VRM 1.0 renamed the thumb bones (Unity proximal = VRM metacarpal, and so on).
                case HumanBodyBones.LeftThumbProximal: return "leftThumbMetacarpal";
                case HumanBodyBones.LeftThumbIntermediate: return "leftThumbProximal";
                case HumanBodyBones.RightThumbProximal: return "rightThumbMetacarpal";
                case HumanBodyBones.RightThumbIntermediate: return "rightThumbProximal";
            }
            var n = bone.ToString();
            return char.ToLowerInvariant(n[0]) + n.Substring(1);
        }

        private static readonly string[] RequiredBones =
        {
            "hips", "spine", "head", "leftUpperLeg", "leftLowerLeg", "leftFoot", "rightUpperLeg", "rightLowerLeg", "rightFoot",
            "leftUpperArm", "leftLowerArm", "leftHand", "rightUpperArm", "rightLowerArm", "rightHand",
        };

        private void WriteVrm(GameObject root, string avatarName, DescriptorInfo d, List<MappedExpression> expressions)
        {
            var humanBones = new JObj();
            var animator = root.GetComponent<Animator>();
            Transform head = null;
            if (animator != null && animator.isHuman)
            {
                foreach (HumanBodyBones bone in Enum.GetValues(typeof(HumanBodyBones)))
                {
                    if (bone == HumanBodyBones.LastBone) continue;
                    var t = animator.GetBoneTransform(bone);
                    if (t == null || !_nodeOf.TryGetValue(t, out var node)) continue;
                    humanBones[VrmBoneName(bone)] = new JObj { ["node"] = node };
                    if (bone == HumanBodyBones.Head) head = t;
                }
            }
            else
            {
                _report.Error("아바타 루트에 휴머노이드 Animator가 없습니다. VRM은 휴머노이드 뼈 정보가 필요합니다.");
            }
            // Descriptor eye bones win when the Animator avatar has none.
            if (!humanBones.ContainsKey("leftEye") && d.LeftEye != null && _nodeOf.TryGetValue(d.LeftEye, out var le))
                humanBones["leftEye"] = new JObj { ["node"] = le };
            if (!humanBones.ContainsKey("rightEye") && d.RightEye != null && _nodeOf.TryGetValue(d.RightEye, out var re))
                humanBones["rightEye"] = new JObj { ["node"] = re };
            // Neither the Animator nor the descriptor names the eyes (eye look off, eyes not mapped in the humanoid):
            // look for the usual eye bone names under the head, so the web app can still turn the eyes (D-077).
            if (head != null)
            {
                foreach (var (key, side) in new[] { ("leftEye", 'L'), ("rightEye", 'R') })
                {
                    if (humanBones.ContainsKey(key)) continue;
                    var eye = FindEyeByName(head, side);
                    if (eye != null && _nodeOf.TryGetValue(eye, out var en))
                    {
                        humanBones[key] = new JObj { ["node"] = en };
                        _report.Note($"눈 뼈를 이름으로 찾았습니다: {eye.name}");
                    }
                }
            }

            var missingRequired = RequiredBones.Where(n => !humanBones.ContainsKey(n)).ToList();
            if (missingRequired.Count > 0) _report.Error("필수 휴머노이드 뼈가 없습니다: " + string.Join(", ", missingRequired));
            _report.Stat("휴머노이드 뼈", humanBones.Count);
            NoteRestPose(animator);

            var vrm = new JObj
            {
                ["specVersion"] = "1.0",
                // Conservative defaults: the avatar's real license is set by its creator; the user must check it.
                ["meta"] = new JObj
                {
                    ["name"] = avatarName,
                    ["version"] = "1.0",
                    ["authors"] = new JArr(_options.AuthorList()),
                    ["licenseUrl"] = "https://vrm.dev/licenses/1.0/",
                    ["avatarPermission"] = "onlyAuthor",
                    ["allowExcessivelyViolentUsage"] = false,
                    ["allowExcessivelySexualUsage"] = false,
                    ["commercialUsage"] = "personalNonProfit",
                    ["allowPoliticalOrReligiousUsage"] = false,
                    ["allowAntisocialOrHateUsage"] = false,
                    ["creditNotation"] = "required",
                    ["allowRedistribution"] = false,
                    ["modification"] = "prohibited",
                },
                ["humanoid"] = new JObj { ["humanBones"] = humanBones },
            };

            var preset = new JObj();
            var custom = new JObj();
            foreach (var e in expressions)
            {
                var binds = new JArr();
                foreach (var bind in e.Binds)
                {
                    if (!_meshNodeOf.TryGetValue(bind.Renderer, out var node))
                    {
                        _report.Warn($"표정 '{e.Name}': 메시 '{bind.Renderer.name}'가 꺼져 있어 연결하지 못했습니다.");
                        continue;
                    }
                    binds.Add(new JObj { ["node"] = node, ["index"] = bind.BlendShapeIndex, ["weight"] = bind.Weight });
                }
                if (binds.Count == 0) continue;
                var expr = new JObj { ["morphTargetBinds"] = binds, ["isBinary"] = false };
                if (e.IsPreset) preset[e.Name] = expr;
                else custom[e.Name] = expr;
            }
            var exprRoot = new JObj();
            if (preset.Count > 0) exprRoot["preset"] = preset;
            if (custom.Count > 0) exprRoot["custom"] = custom;
            if (exprRoot.Count > 0) vrm["expressions"] = exprRoot;

            if (humanBones.ContainsKey("leftEye") || humanBones.ContainsKey("rightEye"))
            {
                var offset = head != null ? UnityToGltf.Pos(head.InverseTransformPoint(d.ViewPositionWorld)) : new[] { 0f, 0.06f, 0f };
                // The web app sends gaze within ±30°: map that to the avatar's eye limit (it was 90°, so the eyes
                // turned a third of their limit at most, D-077). Without limits in the descriptor, 12°.
                JObj Range(float degrees) => new JObj { ["inputMaxValue"] = 30f, ["outputScale"] = degrees };
                vrm["lookAt"] = new JObj
                {
                    ["type"] = "bone",
                    ["offsetFromHeadBone"] = offset,
                    ["rangeMapHorizontalInner"] = Range(d.EyeInner ?? 12f),
                    ["rangeMapHorizontalOuter"] = Range(d.EyeOuter ?? 12f),
                    ["rangeMapVerticalDown"] = Range(d.EyeDown ?? 12f),
                    ["rangeMapVerticalUp"] = Range(d.EyeUp ?? 12f),
                };
            }

            _b.Extensions["VRMC_vrm"] = vrm;
            _b.UseExtension("VRMC_vrm");
        }

        /// <summary>
        /// An eye bone under the head by its usual names: Eye_L / Eye.L / EyeL / LeftEye / Left_Eye / 目.L / 左目
        /// (and the right-side forms). Two levels deep at most; shape-key-only eyes have none.
        /// </summary>
        internal static Transform FindEyeByName(Transform head, char side)
        {
            string s = side == 'L' ? "l" : "r", word = side == 'L' ? "left" : "right", jp = side == 'L' ? "左" : "右";
            bool Match(string raw)
            {
                var n = raw.ToLowerInvariant().Replace(" ", "");
                if (n.Contains("lid") || n.Contains("lash") || n.Contains("brow") || n.Contains("high") || n.Contains("end")) return false;
                return n == $"eye_{s}" || n == $"eye.{s}" || n == $"eye{s}" || n == $"{word}eye" || n == $"{word}_eye"
                    || n == $"eye_{word}" || n == $"目.{s}" || n == $"{jp}目";
            }
            foreach (Transform a in head)
            {
                if (Match(a.name)) return a;
                foreach (Transform b in a) if (Match(b.name)) return b;
            }
            return null;
        }

        /// <summary>
        /// VRM expects a T-pose rest pose. Many VRChat avatars rest in an A-pose. We do not re-pose yet
        /// (that changes bind poses); we only measure and report it so the web rig can compensate (M2).
        /// </summary>
        private void NoteRestPose(Animator animator)
        {
            if (animator == null || !animator.isHuman) return;
            var upper = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm);
            var lower = animator.GetBoneTransform(HumanBodyBones.LeftLowerArm);
            if (upper == null || lower == null) return;
            var dir = (lower.position - upper.position).normalized;
            var rootT = animator.transform;
            var local = rootT.InverseTransformDirection(dir);
            var droop = Mathf.Asin(Mathf.Clamp(-local.y, -1f, 1f)) * Mathf.Rad2Deg;
            _report.Stat("기본 자세 팔 처짐 각도(도)", Math.Round(droop, 1));
            if (droop > 10f)
                _report.Warn($"기본 자세가 T자가 아닙니다(팔이 수평에서 {droop:0}도 아래). 다른 VRM 앱에서는 팔 각도가 어긋날 수 있습니다. Virtual Cam 웹앱은 이 차이를 보정합니다(M2).");
        }
    }
}
