using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using VCam.Exporter.Util;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;

namespace VCam.Exporter.Gltf
{
    /// <summary>
    /// Minimal glTF 2.0 builder that produces a single GLB (JSON chunk + one binary buffer).
    ///
    /// The glTF JSON is kept as plain dictionaries/lists (JObj/JArr) so that extensions such as
    /// VRMC_vrm and our VCAM_* data can be attached freely without a typed schema (D-011).
    /// All binary data goes into one buffer; every bufferView is 4-byte aligned as the spec requires.
    /// </summary>
    internal sealed class GltfBuilder
    {
        public const int FLOAT = 5126;
        public const int UNSIGNED_INT = 5125;
        public const int UNSIGNED_SHORT = 5123;
        public const int ARRAY_BUFFER = 34962;
        public const int ELEMENT_ARRAY_BUFFER = 34963;

        public readonly JArr Nodes = new JArr();
        public readonly JArr Meshes = new JArr();
        public readonly JArr Accessors = new JArr();
        public readonly JArr BufferViews = new JArr();
        public readonly JArr Materials = new JArr();
        public readonly JArr Textures = new JArr();
        public readonly JArr Images = new JArr();
        public readonly JArr Samplers = new JArr();
        public readonly JArr Skins = new JArr();
        /// <summary>Root-level "extensions" object (VRMC_vrm, VCAM_* ...).</summary>
        public readonly JObj Extensions = new JObj();
        public int SceneRootNode;

        private readonly SortedSet<string> _extensionsUsed = new SortedSet<string>(StringComparer.Ordinal);
        private readonly MemoryStream _bin = new MemoryStream();

        public void UseExtension(string name) => _extensionsUsed.Add(name);

        public int AddNode(JObj node) => Add(Nodes, node);
        public int AddMesh(JObj mesh) => Add(Meshes, mesh);
        public int AddMaterial(JObj material) => Add(Materials, material);
        public int AddSkin(JObj skin) => Add(Skins, skin);
        public int AddSampler(JObj sampler) => Add(Samplers, sampler);
        public int AddTexture(int image, int sampler) => Add(Textures, new JObj { ["source"] = image, ["sampler"] = sampler });

        public JObj Node(int index) => (JObj)Nodes[index];

        private static int Add(JArr list, JObj item)
        {
            list.Add(item);
            return list.Count - 1;
        }

        public int AddBufferView(byte[] bytes, int? target = null)
        {
            Align4();
            var view = new JObj { ["buffer"] = 0, ["byteOffset"] = (int)_bin.Position, ["byteLength"] = bytes.Length };
            if (target.HasValue) view["target"] = target.Value;
            _bin.Write(bytes, 0, bytes.Length);
            return Add(BufferViews, view);
        }

        private void Align4()
        {
            while (_bin.Position % 4 != 0) _bin.WriteByte(0);
        }

        private static byte[] ToBytes(float[] data)
        {
            var bytes = new byte[data.Length * 4];
            Buffer.BlockCopy(data, 0, bytes, 0, bytes.Length);
            return bytes;
        }

        private static (JArr min, JArr max) MinMax(float[] data, int comps)
        {
            var min = new float[comps];
            var max = new float[comps];
            for (var c = 0; c < comps; c++)
            {
                min[c] = float.PositiveInfinity;
                max[c] = float.NegativeInfinity;
            }
            for (var i = 0; i < data.Length; i++)
            {
                var c = i % comps;
                if (data[i] < min[c]) min[c] = data[i];
                if (data[i] > max[c]) max[c] = data[i];
            }
            var minList = new JArr();
            var maxList = new JArr();
            for (var c = 0; c < comps; c++)
            {
                minList.Add(min[c]);
                maxList.Add(max[c]);
            }
            return (minList, maxList);
        }

        /// <summary>Tightly packed float accessor (VEC2/VEC3/VEC4/MAT4/SCALAR).</summary>
        public int AddFloatAccessor(float[] data, int comps, string type, bool withMinMax, int? target)
        {
            var acc = new JObj
            {
                ["bufferView"] = AddBufferView(ToBytes(data), target),
                ["componentType"] = FLOAT,
                ["count"] = data.Length / comps,
                ["type"] = type,
            };
            if (withMinMax)
            {
                var (min, max) = MinMax(data, comps);
                acc["min"] = min;
                acc["max"] = max;
            }
            return Add(Accessors, acc);
        }

        /// <summary>
        /// Sparse float accessor: only non-zero elements are stored. Used for morph targets, where most
        /// vertices do not move; this shrinks a 98-blendshape body mesh from tens of MB to a few MB.
        /// </summary>
        public int AddSparseFloatAccessor(float[] dense, int comps, string type, bool withMinMax)
        {
            var count = dense.Length / comps;
            var indices = new List<int>();
            for (var v = 0; v < count; v++)
            {
                for (var c = 0; c < comps; c++)
                {
                    if (dense[v * comps + c] != 0f)
                    {
                        indices.Add(v);
                        break;
                    }
                }
            }

            var acc = new JObj { ["componentType"] = FLOAT, ["count"] = count, ["type"] = type };
            if (withMinMax)
            {
                var (min, max) = MinMax(dense, comps);
                acc["min"] = min;
                acc["max"] = max;
            }
            // No bufferView + no sparse = all zeros (valid per spec). Sparse needs count >= 1.
            if (indices.Count > 0)
            {
                var idxBytes = new byte[indices.Count * 4];
                Buffer.BlockCopy(indices.ToArray(), 0, idxBytes, 0, idxBytes.Length);
                var values = new float[indices.Count * comps];
                for (var i = 0; i < indices.Count; i++)
                    Array.Copy(dense, indices[i] * comps, values, i * comps, comps);
                acc["sparse"] = new JObj
                {
                    ["count"] = indices.Count,
                    ["indices"] = new JObj { ["bufferView"] = AddBufferView(idxBytes), ["componentType"] = UNSIGNED_INT },
                    ["values"] = new JObj { ["bufferView"] = AddBufferView(ToBytes(values)) },
                };
            }
            return Add(Accessors, acc);
        }

        public int AddIndexAccessor(int[] indices)
        {
            var max = 0;
            foreach (var i in indices) if (i > max) max = i;
            byte[] bytes;
            int componentType;
            if (max < 65535)
            {
                var shorts = new ushort[indices.Length];
                for (var i = 0; i < indices.Length; i++) shorts[i] = (ushort)indices[i];
                bytes = new byte[shorts.Length * 2];
                Buffer.BlockCopy(shorts, 0, bytes, 0, bytes.Length);
                componentType = UNSIGNED_SHORT;
            }
            else
            {
                bytes = new byte[indices.Length * 4];
                Buffer.BlockCopy(indices, 0, bytes, 0, bytes.Length);
                componentType = UNSIGNED_INT;
            }
            return Add(Accessors, new JObj
            {
                ["bufferView"] = AddBufferView(bytes, ELEMENT_ARRAY_BUFFER),
                ["componentType"] = componentType,
                ["count"] = indices.Length,
                ["type"] = "SCALAR",
            });
        }

        public int AddJointsAccessor(ushort[] joints)
        {
            var bytes = new byte[joints.Length * 2];
            Buffer.BlockCopy(joints, 0, bytes, 0, bytes.Length);
            return Add(Accessors, new JObj
            {
                ["bufferView"] = AddBufferView(bytes, ARRAY_BUFFER),
                ["componentType"] = UNSIGNED_SHORT,
                ["count"] = joints.Length / 4,
                ["type"] = "VEC4",
            });
        }

        public int AddImagePng(byte[] png, string name)
        {
            var image = new JObj { ["bufferView"] = AddBufferView(png), ["mimeType"] = "image/png" };
            if (!string.IsNullOrEmpty(name)) image["name"] = name;
            return Add(Images, image);
        }

        public byte[] ToGlb()
        {
            var root = new JObj
            {
                ["asset"] = new JObj { ["version"] = "2.0", ["generator"] = "VCam Avatar Exporter" },
            };
            if (_extensionsUsed.Count > 0) root["extensionsUsed"] = new JArr(_extensionsUsed);
            root["scene"] = 0;
            root["scenes"] = new JArr { new JObj { ["nodes"] = new JArr { SceneRootNode } } };
            void Put(string key, JArr list)
            {
                if (list.Count > 0) root[key] = list;
            }
            Put("nodes", Nodes);
            Put("meshes", Meshes);
            Put("skins", Skins);
            Put("materials", Materials);
            Put("textures", Textures);
            Put("images", Images);
            Put("samplers", Samplers);
            Put("accessors", Accessors);
            Put("bufferViews", BufferViews);
            Align4();
            root["buffers"] = new JArr { new JObj { ["byteLength"] = (int)_bin.Length } };
            if (Extensions.Count > 0) root["extensions"] = Extensions;

            var json = Encoding.UTF8.GetBytes(new JsonWriter().Any(root).ToString());
            var jsonPadded = Pad(json, 0x20);
            var binPadded = Pad(_bin.ToArray(), 0x00);

            using (var ms = new MemoryStream())
            using (var w = new BinaryWriter(ms))
            {
                var total = 12 + 8 + jsonPadded.Length + 8 + binPadded.Length;
                w.Write(0x46546C67u); // "glTF"
                w.Write(2u);
                w.Write((uint)total);
                w.Write((uint)jsonPadded.Length);
                w.Write(0x4E4F534Au); // "JSON"
                w.Write(jsonPadded);
                w.Write((uint)binPadded.Length);
                w.Write(0x004E4942u); // "BIN\0"
                w.Write(binPadded);
                w.Flush();
                return ms.ToArray();
            }
        }

        private static byte[] Pad(byte[] data, byte fill)
        {
            var len = (data.Length + 3) & ~3;
            if (len == data.Length) return data;
            var padded = new byte[len];
            Buffer.BlockCopy(data, 0, padded, 0, data.Length);
            for (var i = data.Length; i < len; i++) padded[i] = fill;
            return padded;
        }
    }
}
