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

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Converts a Unity Mesh (+ materials, + optional skin) to a glTF mesh.
    /// - One glTF primitive per submesh; all primitives share the vertex attribute accessors.
    /// - Every blendshape becomes a morph target (sparse accessors), in Unity's order, so
    ///   "blendshape index == morph target index". VRM expression binds rely on that.
    /// - Extra materials beyond the submesh count re-draw the last submesh (Unity's multi-pass behaviour).
    /// </summary>
    internal static class MeshWriter
    {
        public sealed class Result
        {
            public int MeshIndex;
            public List<string> MorphNames = new List<string>();
        }

        /// <param name="exportTangents">Off by default (D-023): three-vrm 3.6 MToon outlines break when TANGENT is present.</param>
        /// <param name="bones">The renderer's bones, to measure skinned normal lengths in the scene pose (D-055).</param>
        public static Result Write(GltfBuilder b, Mesh mesh, Material[] materials, MaterialWriter mats, string name, bool skinned, ExportReport report,
            bool exportTangents = false, Transform[] bones = null)
        {
            var vcount = mesh.vertexCount;
            var attributes = new JObj();

            var positions = mesh.vertices;
            var pos = new float[vcount * 3];
            for (var i = 0; i < vcount; i++) UnityToGltf.Pos(positions[i], pos, i * 3);
            attributes["POSITION"] = b.AddFloatAccessor(pos, 3, "VEC3", true, GltfBuilder.ARRAY_BUFFER);

            var normals = mesh.normals;
            var hasNormals = normals.Length == vcount;
            if (hasNormals)
            {
                var nrm = new float[vcount * 3];
                var fixedCount = 0;
                for (var i = 0; i < vcount; i++)
                {
                    var n = normals[i];
                    // glTF requires unit-length normals; degenerate ones get a placeholder.
                    if (n.sqrMagnitude < 1e-12f)
                    {
                        n = Vector3.up;
                        fixedCount++;
                    }
                    UnityToGltf.Pos(n.normalized, nrm, i * 3);
                }
                if (fixedCount > 0) report.Note($"메시 '{name}': 길이가 0인 노멀 {fixedCount}개를 위쪽 방향으로 바꿈");
                attributes["NORMAL"] = b.AddFloatAccessor(nrm, 3, "VEC3", false, GltfBuilder.ARRAY_BUFFER);
            }

            var tangents = mesh.tangents;
            if (exportTangents && hasNormals && tangents.Length == vcount)
            {
                var tan = new float[vcount * 4];
                for (var i = 0; i < vcount; i++)
                {
                    var t = tangents[i];
                    var xyz = new Vector3(t.x, t.y, t.z);
                    xyz = xyz.sqrMagnitude < 1e-12f ? Vector3.right : xyz.normalized;
                    UnityToGltf.Tangent(new Vector4(xyz.x, xyz.y, xyz.z, t.w), tan, i * 4);
                }
                attributes["TANGENT"] = b.AddFloatAccessor(tan, 4, "VEC4", false, GltfBuilder.ARRAY_BUFFER);
            }

            AddUv(b, attributes, "TEXCOORD_0", mesh.uv, vcount);
            AddUv(b, attributes, "TEXCOORD_1", mesh.uv2, vcount);
            AddUv(b, attributes, "TEXCOORD_2", mesh.uv3, vcount);
            AddUv(b, attributes, "TEXCOORD_3", mesh.uv4, vcount);
            WritePreciseAttributes(b, attributes, mesh, name, skinned ? bones : null, hasNormals, report);

            if (skinned)
            {
                var weights = mesh.boneWeights;
                if (weights.Length == vcount)
                {
                    var joints = new ushort[vcount * 4];
                    var w = new float[vcount * 4];
                    for (var i = 0; i < vcount; i++)
                    {
                        var bw = weights[i];
                        var sum = bw.weight0 + bw.weight1 + bw.weight2 + bw.weight3;
                        if (sum <= 0f)
                        {
                            // Unweighted vertex: pin it to joint 0 so the weights stay valid (sum = 1).
                            w[i * 4] = 1f;
                            continue;
                        }
                        void Put(int slot, int bone, float weight)
                        {
                            var normalized = weight / sum;
                            // glTF: joints with zero weight should be 0.
                            joints[i * 4 + slot] = normalized > 0f ? (ushort)bone : (ushort)0;
                            w[i * 4 + slot] = normalized;
                        }
                        Put(0, bw.boneIndex0, bw.weight0);
                        Put(1, bw.boneIndex1, bw.weight1);
                        Put(2, bw.boneIndex2, bw.weight2);
                        Put(3, bw.boneIndex3, bw.weight3);
                    }
                    attributes["JOINTS_0"] = b.AddJointsAccessor(joints);
                    attributes["WEIGHTS_0"] = b.AddFloatAccessor(w, 4, "VEC4", false, GltfBuilder.ARRAY_BUFFER);
                }
                else
                {
                    report.Warn($"메시 '{name}': 스킨 가중치가 없어 뼈를 따라 움직이지 않습니다.");
                }
            }

            var result = new Result();
            var targets = new JArr();
            if (mesh.blendShapeCount > 0)
            {
                var dv = new Vector3[vcount];
                var dn = new Vector3[vcount];
                var dt = new Vector3[vcount];
                for (var s = 0; s < mesh.blendShapeCount; s++)
                {
                    var frame = mesh.GetBlendShapeFrameCount(s) - 1;
                    mesh.GetBlendShapeFrameVertices(s, frame, dv, dn, dt);
                    // glTF weight 1.0 must equal Unity weight 100 (the usual last-frame weight).
                    var frameWeight = mesh.GetBlendShapeFrameWeight(s, frame);
                    var scale = frameWeight > 0f ? 100f / frameWeight : 1f;
                    if (mesh.GetBlendShapeFrameCount(s) > 1)
                        report.Note($"메시 '{name}': 쉐이프키 '{mesh.GetBlendShapeName(s)}'는 프레임이 여러 개라 마지막 프레임만 내보냄");

                    var p = new float[vcount * 3];
                    for (var i = 0; i < vcount; i++) UnityToGltf.Pos(dv[i] * scale, p, i * 3);
                    var target = new JObj { ["POSITION"] = b.AddSparseFloatAccessor(p, 3, "VEC3", true) };
                    if (hasNormals)
                    {
                        var n = new float[vcount * 3];
                        for (var i = 0; i < vcount; i++) UnityToGltf.Pos(dn[i] * scale, n, i * 3);
                        target["NORMAL"] = b.AddSparseFloatAccessor(n, 3, "VEC3", false);
                    }
                    targets.Add(target);
                    result.MorphNames.Add(mesh.GetBlendShapeName(s));
                }
            }

            var primitives = new JArr();
            var lastIndices = -1;
            var subCount = mesh.subMeshCount;
            var primCount = Mathf.Max(subCount, materials?.Length ?? 0);
            for (var i = 0; i < primCount; i++)
            {
                int indices;
                if (i < subCount)
                {
                    if (mesh.GetTopology(i) != MeshTopology.Triangles)
                    {
                        report.Warn($"메시 '{name}' 서브메시 {i}: 삼각형이 아닌 메시({mesh.GetTopology(i)})는 내보내지 않습니다.");
                        continue;
                    }
                    var tris = mesh.GetTriangles(i);
                    // Reverse winding: the X mirror turns Unity's front faces into glTF back faces.
                    for (var t = 0; t + 2 < tris.Length; t += 3)
                    {
                        var tmp = tris[t + 1];
                        tris[t + 1] = tris[t + 2];
                        tris[t + 2] = tmp;
                    }
                    indices = b.AddIndexAccessor(tris);
                    lastIndices = indices;
                }
                else
                {
                    if (lastIndices < 0) break;
                    indices = lastIndices;
                    report.Note($"메시 '{name}': 서브메시보다 머티리얼이 많아 마지막 서브메시를 머티리얼 {i}로 한 번 더 그림");
                }
                var material = materials != null && i < materials.Length ? materials[i] : null;
                var prim = new JObj
                {
                    ["attributes"] = attributes,
                    ["indices"] = indices,
                    ["material"] = mats.Get(material),
                    ["mode"] = 4,
                };
                if (targets.Count > 0) prim["targets"] = targets;
                primitives.Add(prim);
            }

            var meshObj = new JObj { ["name"] = name, ["primitives"] = primitives };
            if (result.MorphNames.Count > 0)
            {
                // three.js reads extras.targetNames to build morphTargetDictionary (name → index).
                meshObj["extras"] = new JObj { ["targetNames"] = new JArr(result.MorphNames) };
            }
            result.MeshIndex = b.AddMesh(meshObj);
            return result;
        }

        /// <summary>
        /// Extra per-vertex data the Unity-shader ports need to match Unity (D-055). Application-specific names
        /// (leading underscore) so other glTF/VRM readers ignore them: GLTFLoader would otherwise switch MToon to
        /// vertex colors for COLOR_0, and three-vrm MToon outlines break with TANGENT (D-023).
        /// - _UNITY_TANGENT: Unity's imported tangents (MikkTSpace), mirrored like TANGENT, not re-normalized.
        /// - _UNITY_COLOR:   mesh vertex colors as Unity stores them.
        /// - _NORMAL_SCALE:  length of the skinned normal in the scene pose. Unity does not re-normalize skinned
        ///                   normals, so meshes bound with a scale (hair at ~0.056) push outlines by a shorter normal.
        /// </summary>
        private static void WritePreciseAttributes(GltfBuilder b, JObj attributes, Mesh mesh, string name, Transform[] bones, bool hasNormals,
            ExportReport report)
        {
            var vcount = mesh.vertexCount;
            var tangents = mesh.tangents;
            if (hasNormals && tangents.Length == vcount)
            {
                var tan = new float[vcount * 4];
                for (var i = 0; i < vcount; i++) UnityToGltf.Tangent(tangents[i], tan, i * 4);
                attributes["_UNITY_TANGENT"] = b.AddFloatAccessor(tan, 4, "VEC4", false, GltfBuilder.ARRAY_BUFFER);
            }

            var colors = mesh.colors;
            if (colors.Length == vcount)
            {
                var col = new float[vcount * 4];
                for (var i = 0; i < vcount; i++)
                {
                    col[i * 4] = colors[i].r;
                    col[i * 4 + 1] = colors[i].g;
                    col[i * 4 + 2] = colors[i].b;
                    col[i * 4 + 3] = colors[i].a;
                }
                attributes["_UNITY_COLOR"] = b.AddFloatAccessor(col, 4, "VEC4", false, GltfBuilder.ARRAY_BUFFER);
            }

            if (bones == null || !hasNormals) return;
            var weights = mesh.boneWeights;
            var bindposes = mesh.bindposes;
            if (weights.Length != vcount || bindposes.Length != bones.Length) return;
            var skin = new Matrix4x4[bones.Length];
            for (var j = 0; j < bones.Length; j++) skin[j] = bones[j] != null ? bones[j].localToWorldMatrix * bindposes[j] : Matrix4x4.identity;
            var normals = mesh.normals;
            var scale = new float[vcount];
            var differs = false;
            for (var i = 0; i < vcount; i++)
            {
                var bw = weights[i];
                var n = normals[i];
                var skinned = skin[bw.boneIndex0].MultiplyVector(n) * bw.weight0 + skin[bw.boneIndex1].MultiplyVector(n) * bw.weight1
                    + skin[bw.boneIndex2].MultiplyVector(n) * bw.weight2 + skin[bw.boneIndex3].MultiplyVector(n) * bw.weight3;
                scale[i] = n.sqrMagnitude > 1e-12f ? skinned.magnitude / n.magnitude : 1f;
                if (Mathf.Abs(scale[i] - 1f) > 1e-3f) differs = true;
            }
            if (!differs) return;
            attributes["_NORMAL_SCALE"] = b.AddFloatAccessor(scale, 1, "SCALAR", false, GltfBuilder.ARRAY_BUFFER);
            report.Note($"메시 '{name}': 스킨 노멀 길이가 1이 아니라(바인드 행렬 배율) _NORMAL_SCALE을 함께 내보냄");
        }

        private static void AddUv(GltfBuilder b, JObj attributes, string key, Vector2[] uv, int vcount)
        {
            if (uv == null || uv.Length != vcount) return;
            var data = new float[vcount * 2];
            for (var i = 0; i < vcount; i++) UnityToGltf.Uv(uv[i], data, i * 2);
            attributes[key] = b.AddFloatAccessor(data, 2, "VEC2", false, GltfBuilder.ARRAY_BUFFER);
        }

        /// <summary>Inverse bind matrices from Unity bindposes (mesh space → bone space, as glTF expects).</summary>
        public static int WriteInverseBindMatrices(GltfBuilder b, Matrix4x4[] bindposes)
        {
            var data = new float[bindposes.Length * 16];
            for (var i = 0; i < bindposes.Length; i++) UnityToGltf.Matrix(bindposes[i], data, i * 16);
            return b.AddFloatAccessor(data, 16, "MAT4", false, null);
        }
    }
}
