using UnityEngine;

namespace VCam.Exporter.Gltf
{
    /// <summary>
    /// Unity (left-handed, +Z forward) → glTF/VRM 1.0 (right-handed, +Z forward) conversion by mirroring X.
    /// VRM 1.0 models face +Z in glTF, and Unity avatars face +Z, so mirroring X keeps the facing direction.
    ///
    /// Rules (see docs/DECISIONS.md D-011):
    /// - position/normal: (-x, y, z)
    /// - rotation: (x, -y, -z, w)   (S·R·S with S = diag(-1,1,1))
    /// - matrix: S·M·S
    /// - UV: (u, 1 - v)             (Unity v=0 is the image bottom, glTF v=0 is the image top)
    /// - tangent: (-x, y, z, -w)    (normal maps are copied unchanged, so the bitangent must keep pointing to the
    ///                               image's "up" on the surface: B' = M·B. With N' = M·N, T' = M·T and
    ///                               cross(MN, MT) = -M·cross(N, T), that needs w' = -w. The UV V flip does not
    ///                               change this because the image pixels are not flipped.)
    /// - triangle winding must be reversed (the mirror turns Unity's front-face order into a back face)
    /// </summary>
    internal static class UnityToGltf
    {
        public static void Pos(Vector3 v, float[] dst, int i)
        {
            dst[i] = -v.x;
            dst[i + 1] = v.y;
            dst[i + 2] = v.z;
        }

        public static float[] Pos(Vector3 v) => new[] { -v.x, v.y, v.z };

        public static float[] Rot(Quaternion q)
        {
            var n = Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
            if (n < 1e-8f) return new[] { 0f, 0f, 0f, 1f };
            return new[] { q.x / n, -q.y / n, -q.z / n, q.w / n };
        }

        public static void Tangent(Vector4 t, float[] dst, int i)
        {
            dst[i] = -t.x;
            dst[i + 1] = t.y;
            dst[i + 2] = t.z;
            dst[i + 3] = t.w < 0 ? 1f : -1f; // w' = -w, see class comment
        }

        public static void Uv(Vector2 uv, float[] dst, int i)
        {
            dst[i] = uv.x;
            dst[i + 1] = 1f - uv.y;
        }

        /// <summary>Column-major float[16] of S·M·S.</summary>
        public static void Matrix(Matrix4x4 m, float[] dst, int offset)
        {
            for (var col = 0; col < 4; col++)
            {
                for (var row = 0; row < 4; row++)
                {
                    var s = (row == 0 ? -1f : 1f) * (col == 0 ? -1f : 1f);
                    dst[offset + col * 4 + row] = s * m[row, col];
                }
            }
        }

        /// <summary>Unity material colors are sRGB; glTF color factors are linear.</summary>
        public static float[] LinearRgba(Color c)
        {
            var l = c.linear;
            return new[] { l.r, l.g, l.b, c.a };
        }

        public static float[] LinearRgb(Color c)
        {
            var l = c.linear;
            return new[] { l.r, l.g, l.b };
        }
    }
}
