using UnityEngine;
using VRC.SDK3.Avatars.Components;
using VRC.SDKBase;

namespace VCam.Exporter.Pipeline
{
    /// <summary>
    /// Reads what the VRChat avatar descriptor knows about the face: viseme blendshapes, eyelid blink
    /// blendshape, eye bones and the view position. These are the most reliable sources for VRM expressions
    /// because the avatar author set them up for VRChat already; name guessing is only a fallback.
    /// </summary>
    internal sealed class DescriptorInfo
    {
        /// <summary>VRChat viseme order: sil, PP, FF, TH, DD, kk, CH, SS, nn, RR, aa, E, ih, oh, ou.</summary>
        public static readonly string[] VisemeOrder = { "sil", "PP", "FF", "TH", "DD", "kk", "CH", "SS", "nn", "RR", "aa", "E", "ih", "oh", "ou" };

        public SkinnedMeshRenderer VisemeRenderer;
        public string[] VisemeBlendShapes = new string[0];
        public SkinnedMeshRenderer EyelidRenderer;
        /// <summary>Blendshape index for "blink" on <see cref="EyelidRenderer"/>, or -1.</summary>
        public int BlinkIndex = -1;
        public Transform LeftEye;
        public Transform RightEye;
        /// <summary>View position in world space (descriptor stores it as an offset from the avatar root).</summary>
        public Vector3 ViewPositionWorld;

        public static DescriptorInfo Read(GameObject avatarRoot)
        {
            var info = new DescriptorInfo();
            var d = avatarRoot.GetComponent<VRCAvatarDescriptor>();
            if (d == null) return info;

            if (d.lipSync == VRC_AvatarDescriptor.LipSyncStyle.VisemeBlendShape && d.VisemeSkinnedMesh != null)
            {
                info.VisemeRenderer = d.VisemeSkinnedMesh;
                info.VisemeBlendShapes = d.VisemeBlendShapes ?? new string[0];
            }

            var eye = d.customEyeLookSettings;
            if (d.enableEyeLook)
            {
                info.LeftEye = eye.leftEye;
                info.RightEye = eye.rightEye;
            }
            if (eye.eyelidType == VRCAvatarDescriptor.EyelidType.Blendshapes && eye.eyelidsSkinnedMesh != null
                && eye.eyelidsBlendshapes != null && eye.eyelidsBlendshapes.Length > 0)
            {
                info.EyelidRenderer = eye.eyelidsSkinnedMesh;
                info.BlinkIndex = eye.eyelidsBlendshapes[0];
            }

            info.ViewPositionWorld = avatarRoot.transform.position + d.ViewPosition;
            if (d.enableEyeLook) ReadEyeAngles(eye, info);
            return info;
        }

        /// <summary>Eye rotation limits (degrees) from the descriptor's eye look settings; null = not set.</summary>
        public float? EyeUp, EyeDown, EyeOuter, EyeInner;

        /// <summary>
        /// Reads eyesLookingStraight/Up/Down/Left/Right (each an EyeRotations struct with left/right quaternions)
        /// by reflection, because the struct is declared inside the precompiled SDK DLL. Angles are measured on
        /// the LEFT eye: looking left = outer, looking right = inner.
        /// </summary>
        private static void ReadEyeAngles(object eyeSettings, DescriptorInfo info)
        {
            Quaternion? Left(string field)
            {
                var rot = eyeSettings.GetType().GetField(field)?.GetValue(eyeSettings);
                var q = rot?.GetType().GetField("left")?.GetValue(rot);
                // An unset rotation is (0,0,0,0), not identity: Quaternion.Angle reads it as 180° from anything, and
                // that went out as the eye limit (PC_Canine_2.0_BLANK: eyes swung six times the gaze, D-092).
                if (!(q is Quaternion quat) || quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w < 0.25f) return null;
                return quat;
            }
            var straight = Left("eyesLookingStraight");
            if (!straight.HasValue) return;
            float? Angle(string field)
            {
                var q = Left(field);
                if (!q.HasValue) return null;
                var a = Quaternion.Angle(straight.Value, q.Value);
                // Unset rotations equal "straight"; no eye turns past 60°, so a larger angle is not a real limit.
                return a > 0.5f && a <= 60f ? a : (float?)null;
            }
            info.EyeUp = Angle("eyesLookingUp");
            info.EyeDown = Angle("eyesLookingDown");
            info.EyeOuter = Angle("eyesLookingLeft");
            info.EyeInner = Angle("eyesLookingRight");
        }

        /// <summary>Viseme blendshape name for a VRChat viseme (e.g. "aa"), or null.</summary>
        public string Viseme(string visemeName)
        {
            var i = System.Array.IndexOf(VisemeOrder, visemeName);
            if (i < 0 || i >= VisemeBlendShapes.Length) return null;
            var n = VisemeBlendShapes[i];
            return string.IsNullOrEmpty(n) || n == "-none-" ? null : n;
        }
    }
}
