using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using VCam.Exporter.Export;

namespace VCam.Exporter.Pipeline
{
    internal sealed class ExpressionBind
    {
        public SkinnedMeshRenderer Renderer;
        public int BlendShapeIndex;
        public float Weight = 1f;
    }

    internal sealed class MappedExpression
    {
        /// <summary>VRM preset name ("aa", "blink", ...) or custom name (ARKit names for perfect sync).</summary>
        public string Name;
        public bool IsPreset;
        public string Source;
        public readonly List<ExpressionBind> Binds = new List<ExpressionBind>();
    }

    /// <summary>
    /// Decides which blendshapes drive which VRM expression.
    /// Priority (D-077): 1) MMD standard morph names (あ い う え お まばたき ウィンク…), on every mesh that has them
    /// 2) VRChat descriptor (visemes, eyelid blink) 3) other blendshape name rules (vrc.v_*, English).
    /// If the avatar has ARKit "perfect sync" blendshapes, all 52 are also exported as custom expressions
    /// so the web app can drive them 1:1 from MediaPipe's 52 face blendshapes.
    /// </summary>
    internal static class ExpressionMapper
    {
        /// <summary>The 52 ARKit / MediaPipe face blendshape names.</summary>
        public static readonly string[] ArKitNames =
        {
            "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight",
            "cheekPuff", "cheekSquintLeft", "cheekSquintRight",
            "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight", "eyeLookInLeft", "eyeLookInRight",
            "eyeLookOutLeft", "eyeLookOutRight", "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",
            "eyeWideLeft", "eyeWideRight",
            "jawForward", "jawLeft", "jawOpen", "jawRight",
            "mouthClose", "mouthDimpleLeft", "mouthDimpleRight", "mouthFrownLeft", "mouthFrownRight", "mouthFunnel",
            "mouthLeft", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft", "mouthPressRight", "mouthPucker",
            "mouthRight", "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft",
            "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight", "mouthUpperUpLeft", "mouthUpperUpRight",
            "noseSneerLeft", "noseSneerRight", "tongueOut",
        };

        /// <summary>
        /// MMD standard morph names, tried first (the user's choice, D-077): most VRChat avatars from Japanese creators
        /// carry them, and they are the shapes made for the purpose (vrc.v_* visemes are often a mix of them). Plain
        /// "ウィンク" closes the LEFT eye in MMD (D-034).
        /// </summary>
        private static readonly Dictionary<string, string[]> MmdRules = new Dictionary<string, string[]>
        {
            ["aa"] = new[] { "あ" }, ["ih"] = new[] { "い" }, ["ou"] = new[] { "う" }, ["ee"] = new[] { "え" }, ["oh"] = new[] { "お" },
            ["blink"] = new[] { "まばたき" },
            ["blinkLeft"] = new[] { "ウィンク左", "ウィンク" },
            ["blinkRight"] = new[] { "ウィンク右" },
            ["happy"] = new[] { "笑い" },
            ["angry"] = new[] { "怒り" },
            ["sad"] = new[] { "悲しい", "困る" },
            ["surprised"] = new[] { "びっくり" },
        };

        /// <summary>Fallback name rules, compared after normalising (lower case, no spaces/_/-/.).</summary>
        private static readonly Dictionary<string, string[]> NameRules = new Dictionary<string, string[]>
        {
            ["aa"] = new[] { "vrcvaa", "aa", "あ", "mouth_a", "mtha" },
            ["ih"] = new[] { "vrcvih", "ih", "い", "mouth_i", "mthi" },
            ["ou"] = new[] { "vrcvou", "ou", "う", "mouth_u", "mthu" },
            ["ee"] = new[] { "vrcve", "ee", "え", "mouth_e", "mthe" },
            ["oh"] = new[] { "vrcvoh", "oh", "お", "mouth_o", "mtho" },
            ["blink"] = new[] { "blink", "まばたき", "eyeblink", "eyeclose", "eyesclosed" },
            // MMD standard morphs: plain "ウィンク" closes the LEFT eye, "ウィンク右" the right eye (D-034).
            // Explicit left names are tried first, the bare MMD name last.
            ["blinkLeft"] = new[] { "blinkl", "blinkleft", "winkl", "winkleft", "eyeblinkl", "ウィンク左", "まばたき左", "ウィンク" },
            ["blinkRight"] = new[] { "blinkr", "blinkright", "winkr", "winkright", "eyeblinkr", "ウィンク右", "まばたき右" },
            ["happy"] = new[] { "happy", "joy", "smile", "笑い", "にっこり" },
            ["angry"] = new[] { "angry", "怒り", "おこ" },
            ["sad"] = new[] { "sad", "sorrow", "悲しい", "困る", "かなしい" },
            ["relaxed"] = new[] { "relaxed", "fun", "なごみ", "にこり" },
            ["surprised"] = new[] { "surprised", "びっくり", "驚き", "おどろき" },
        };

        /// <summary>
        /// Brow shapes exported as VCam custom expressions (D-052); the web drives them from MediaPipe brows.
        /// MMD standard brow morphs are 上 (raise), 下 (lower) and 困る (worried, inner ends up).
        /// Skipped for perfect-sync avatars, which already have the ARKit brow shapes.
        /// </summary>
        private static readonly Dictionary<string, string[]> BrowRules = new Dictionary<string, string[]>
        {
            ["browUp"] = new[] { "browup", "eyebrowup", "browsup", "眉上", "まゆ上", "上" },
            ["browDown"] = new[] { "browdown", "eyebrowdown", "browsdown", "眉下", "まゆ下", "下" },
            ["browWorried"] = new[] { "browworried", "browsad", "browtrouble", "眉困る", "困る", "困り" },
        };

        /// <summary>
        /// NFKC first, so half-width katakana ("ｳｨﾝｸ２右") and full-width digits/letters compare equal to their
        /// normal forms ("ウィンク2右"); then lower case and drop separators.
        /// </summary>
        private static string Normalize(string s) =>
            new string((s ?? "").Normalize(System.Text.NormalizationForm.FormKC).ToLowerInvariant()
                .Where(ch => ch != ' ' && ch != '_' && ch != '-' && ch != '.').ToArray());

        public static List<MappedExpression> Map(GameObject root, DescriptorInfo d, ExportReport report, IEnumerable<ExpressionOverride> overrides = null)
        {
            var result = new List<MappedExpression>();
            var renderers = root.GetComponentsInChildren<SkinnedMeshRenderer>(true)
                .Where(r => r.sharedMesh != null && r.sharedMesh.blendShapeCount > 0)
                .ToList();

            MappedExpression Add(string name, bool preset, string source, SkinnedMeshRenderer r, int index)
            {
                var e = new MappedExpression { Name = name, IsPreset = preset, Source = source };
                e.Binds.Add(new ExpressionBind { Renderer = r, BlendShapeIndex = index });
                result.Add(e);
                return e;
            }
            bool Has(string name) => result.Any(e => e.Name == name);
            // Kemono-style avatars split the face over several meshes (face, beard, eyelashes) that carry the same
            // shape keys; binding only the first one leaves the others still (D-078), so bind every mesh that has it.
            void AddAll(string name, bool preset, string source, List<(SkinnedMeshRenderer renderer, int index)> hits)
            {
                var e = new MappedExpression { Name = name, IsPreset = preset, Source = hits.Count > 1 ? $"{source}, 메시 {hits.Count}개" : source };
                foreach (var (r, idx) in hits) e.Binds.Add(new ExpressionBind { Renderer = r, BlendShapeIndex = idx });
                result.Add(e);
            }

            // 1) MMD standard morph names, bound on every mesh that has the morph (face, eyelashes, teeth…).
            foreach (var rule in MmdRules)
            {
                var hits = FindAllByNames(renderers, rule.Value);
                if (hits.Count == 0) continue;
                var e = new MappedExpression
                {
                    Name = rule.Key, IsPreset = true,
                    Source = $"MMD 이름 ({hits[0].renderer.sharedMesh.GetBlendShapeName(hits[0].index)}, 메시 {hits.Count}개)",
                };
                foreach (var (r, idx) in hits) e.Binds.Add(new ExpressionBind { Renderer = r, BlendShapeIndex = idx });
                result.Add(e);
            }

            // 2) Descriptor visemes → VRM mouth presets, for any vowel MMD names did not cover.
            if (d.VisemeRenderer != null && d.VisemeRenderer.sharedMesh != null)
            {
                var mesh = d.VisemeRenderer.sharedMesh;
                foreach (var (vrm, vrc) in new[] { ("aa", "aa"), ("ih", "ih"), ("ou", "ou"), ("ee", "E"), ("oh", "oh") })
                {
                    if (Has(vrm)) continue;
                    var shape = d.Viseme(vrc);
                    var idx = shape != null ? mesh.GetBlendShapeIndex(shape) : -1;
                    if (idx >= 0) Add(vrm, true, $"디스크립터 비짐 {vrc} ({shape})", d.VisemeRenderer, idx);
                    else if (shape != null) report.Warn($"디스크립터 비짐 {vrc}의 쉐이프키 '{shape}'를 메시에서 찾지 못했습니다.");
                }
            }

            // 3) Descriptor eyelid blink.
            if (!Has("blink") && d.EyelidRenderer != null && d.EyelidRenderer.sharedMesh != null && d.BlinkIndex >= 0
                && d.BlinkIndex < d.EyelidRenderer.sharedMesh.blendShapeCount)
            {
                Add("blink", true, $"디스크립터 눈꺼풀 ({d.EyelidRenderer.sharedMesh.GetBlendShapeName(d.BlinkIndex)})", d.EyelidRenderer, d.BlinkIndex);
            }

            // 4) Other name rules for anything still missing.
            foreach (var rule in NameRules)
            {
                if (Has(rule.Key)) continue;
                var hits = FindAllByNames(renderers, rule.Value);
                if (hits.Count > 0)
                    AddAll(rule.Key, true, $"이름 규칙 ({hits[0].renderer.sharedMesh.GetBlendShapeName(hits[0].index)})", hits);
            }

            // 4) Perfect sync: export ARKit names as custom expressions when most of them exist.
            var arkit = new List<(string name, List<(SkinnedMeshRenderer renderer, int index)> hits)>();
            foreach (var name in ArKitNames)
            {
                var hits = FindAllByNames(renderers, new[] { name });
                if (hits.Count > 0) arkit.Add((name, hits));
            }
            if (arkit.Count >= 40)
            {
                foreach (var (name, hits) in arkit) AddAll(name, false, "퍼펙트싱크", hits);
                report.Note($"퍼펙트싱크 쉐이프키 {arkit.Count}/52개를 찾아 그대로 내보냈습니다.");
            }
            else if (arkit.Count > 0)
            {
                report.Note($"퍼펙트싱크 쉐이프키가 {arkit.Count}/52개뿐이라 퍼펙트싱크로 쓰지 않습니다.");
            }

            // 4b) Brows as VCam custom expressions when perfect sync does not already cover them.
            if (arkit.Count < 40)
            {
                foreach (var rule in BrowRules)
                {
                    if (Has(rule.Key)) continue;
                    var hits = FindAllByNames(renderers, rule.Value);
                    if (hits.Count > 0)
                        AddAll(rule.Key, false, $"눈썹 이름 규칙 ({hits[0].renderer.sharedMesh.GetBlendShapeName(hits[0].index)})", hits);
                }
            }

            // 5) User overrides from the exporter window win over everything above.
            if (overrides != null)
            {
                foreach (var o in overrides)
                {
                    if (string.IsNullOrEmpty(o.expression)) continue;
                    var isPreset = PresetNames.Contains(o.expression);
                    result.RemoveAll(e => e.Name == o.expression);
                    if (o.disabled) continue;
                    var r = FindRenderer(root, renderers, o.rendererPath);
                    var idx = r != null ? r.sharedMesh.GetBlendShapeIndex(o.blendShape ?? "") : -1;
                    if (idx >= 0) Add(o.expression, isPreset, $"사용자 지정 ({o.rendererPath}/{o.blendShape})", r, idx);
                    else report.Warn($"사용자 지정 표정 '{o.expression}'의 쉐이프키 '{o.rendererPath}/{o.blendShape}'를 찾지 못했습니다.");
                }
            }

            foreach (var preset in new[] { "aa", "ih", "ou", "ee", "oh", "blink" })
                if (!Has(preset)) report.Warn($"표정 '{preset}'에 맞는 쉐이프키를 찾지 못했습니다. 웹에서 이 움직임이 나오지 않습니다.");

            return result;
        }

        /// <summary>VRM 1.0 preset expression names, in the order the exporter window lists them.</summary>
        public static readonly string[] PresetNames =
        {
            "aa", "ih", "ou", "ee", "oh", "blink", "blinkLeft", "blinkRight",
            "happy", "angry", "sad", "relaxed", "surprised", "lookUp", "lookDown", "lookLeft", "lookRight", "neutral",
        };

        /// <summary>
        /// Finds a renderer by path relative to the avatar root; falls back to a unique name match because
        /// Modular Avatar may move objects during the bake (the window lists paths of the unbaked avatar).
        /// </summary>
        private static SkinnedMeshRenderer FindRenderer(GameObject root, List<SkinnedMeshRenderer> renderers, string path)
        {
            if (string.IsNullOrEmpty(path)) return null;
            var t = root.transform.Find(path);
            var byPath = t != null ? t.GetComponent<SkinnedMeshRenderer>() : null;
            if (byPath != null && byPath.sharedMesh != null) return byPath;
            var name = path.Substring(path.LastIndexOf('/') + 1);
            var byName = renderers.Where(r => r.name == name).ToList();
            return byName.Count == 1 ? byName[0] : null;
        }

        /// <summary>Every (mesh, shape key) whose name is the first candidate that any mesh has.</summary>
        private static List<(SkinnedMeshRenderer renderer, int index)> FindAllByNames(List<SkinnedMeshRenderer> renderers, string[] candidates)
        {
            foreach (var cand in candidates.Select(Normalize))
            {
                var hits = new List<(SkinnedMeshRenderer, int)>();
                foreach (var r in renderers)
                {
                    var mesh = r.sharedMesh;
                    for (var i = 0; i < mesh.blendShapeCount; i++)
                        if (Normalize(mesh.GetBlendShapeName(i)) == cand) { hits.Add((r, i)); break; }
                }
                if (hits.Count > 0) return hits;
            }
            return new List<(SkinnedMeshRenderer, int)>();
        }
    }
}
