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

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Writes the standard glTF material + VRMC_materials_mtoon. This is the FALLBACK look (D-001, D-004):
    /// other VRM apps and our web app's first version render this. The exact Unity look will come from the
    /// raw property dump (VCAM_materials_unity, M1-b) and the lilToon/Poiyomi ports in the web app (M4/M6).
    ///
    /// lilToon → MToon mapping (both are toon models over N·L):
    /// - lilToon thresholds half-lambert h = 0.5·N·L + 0.5 at _ShadowBorder with width _ShadowBlur.
    /// - MToon 1.0 shades with linearstep(-1 + toony, 1 - toony, N·L + shift).
    ///   Matching the center gives shift = 1 - 2·border; matching the width gives toony = 1 - blur.
    /// - lilToon outline offset is _OutlineWidth × 0.01 m along the normal → MToon worldCoordinates width.
    /// </summary>
    internal sealed class MaterialWriter
    {
        private readonly GltfBuilder _b;
        private readonly TextureWriter _tex;
        private readonly ExportReport _report;
        private readonly Dictionary<Material, int> _cache = new Dictionary<Material, int>();
        private int _defaultMaterial = -1;

        public MaterialWriter(GltfBuilder b, TextureWriter tex, ExportReport report)
        {
            _b = b;
            _tex = tex;
            _report = report;
        }

        public int Count => _cache.Count;

        public int Get(Material m)
        {
            if (m == null) return Default();
            if (_cache.TryGetValue(m, out var index)) return index;
            index = _b.AddMaterial(Build(m));
            _cache[m] = index;
            return index;
        }

        private int Default()
        {
            if (_defaultMaterial < 0)
            {
                _defaultMaterial = _b.AddMaterial(new JObj
                {
                    ["name"] = "(missing material)",
                    ["pbrMetallicRoughness"] = new JObj { ["metallicFactor"] = 0f, ["roughnessFactor"] = 1f },
                });
                _report.Warn("머티리얼이 비어 있는 슬롯이 있어 기본 머티리얼로 내보냈습니다.");
            }
            return _defaultMaterial;
        }

        private static float F(Material m, string prop, float fallback) => m.HasProperty(prop) ? m.GetFloat(prop) : fallback;
        private static Color C(Material m, string prop, Color fallback) => m.HasProperty(prop) ? m.GetColor(prop) : fallback;
        private static Texture T(Material m, string prop) => m.HasProperty(prop) ? m.GetTexture(prop) : null;

        private JObj Build(Material m)
        {
            var shaderName = m.shader != null ? m.shader.name : "";
            var kind = ShaderFamily.Classify(m.shader);
            var lower = shaderName.ToLowerInvariant();
            var isLil = kind == ShaderKind.LilToon || kind == ShaderKind.LilToonCustom;

            var baseColor = C(m, "_Color", Color.white);
            var pbr = new JObj
            {
                ["baseColorFactor"] = UnityToGltf.LinearRgba(baseColor),
                ["metallicFactor"] = 0f,
                ["roughnessFactor"] = 1f,
            };
            var mainTex = T(m, "_MainTex");
            var baseTex = _tex.Add(mainTex, TextureKind.Color);
            if (baseTex.HasValue) pbr["baseColorTexture"] = new JObj { ["index"] = baseTex.Value };
            if (mainTex != null && m.HasProperty("_MainTex_ST"))
            {
                var st = m.GetVector("_MainTex_ST");
                if (st != new Vector4(1, 1, 0, 0))
                    _report.Warn($"머티리얼 '{m.name}': _MainTex 타일링/오프셋({st})은 아직 폴백 머티리얼에 반영하지 않습니다.");
            }

            var mat = new JObj { ["name"] = m.name, ["pbrMetallicRoughness"] = pbr };

            // Alpha: by shader name first (lilToon/Poiyomi variants are named), then by render queue.
            var rq = m.renderQueue;
            var cutoutByName = lower.Contains("cutout");
            var transparentByName = lower.Contains("transparent") || lower.Contains("fade");
            if (transparentByName || (!cutoutByName && rq > 2500 && rq < 5000))
            {
                mat["alphaMode"] = "BLEND";
            }
            else if (cutoutByName || (rq >= 2450 && rq <= 2500))
            {
                mat["alphaMode"] = "MASK";
                mat["alphaCutoff"] = F(m, "_Cutoff", 0.5f);
            }

            // Unity CullMode: 0 = Off (double sided), 1 = Front, 2 = Back.
            if (m.HasProperty("_Cull") && Mathf.RoundToInt(m.GetFloat("_Cull")) == 0) mat["doubleSided"] = true;
            else if (m.HasProperty("_Cull") && Mathf.RoundToInt(m.GetFloat("_Cull")) == 1)
                _report.Warn($"머티리얼 '{m.name}': 앞면 컬링(Cull Front)은 glTF에서 표현할 수 없어 뒷면 컬링으로 내보냅니다.");

            // Emission (lilToon _UseEmission / generic _EmissionColor). glTF emissiveFactor is clamped to 1.
            var useEmission = isLil ? F(m, "_UseEmission", 0f) > 0.5f : m.IsKeywordEnabled("_EMISSION");
            if (useEmission && m.HasProperty("_EmissionColor"))
            {
                var e = m.GetColor("_EmissionColor").linear;
                var max = Mathf.Max(e.r, Mathf.Max(e.g, e.b));
                if (max > 1f)
                {
                    _report.Note($"머티리얼 '{m.name}': 발광 세기 {max:0.##}배는 폴백에서 1로 잘립니다.");
                    e /= max;
                }
                mat["emissiveFactor"] = new[] { e.r, e.g, e.b };
                var emTex = _tex.Add(T(m, "_EmissionMap"), TextureKind.Color);
                if (emTex.HasValue) mat["emissiveTexture"] = new JObj { ["index"] = emTex.Value };
            }

            // Normal map (lilToon: _UseBumpMap toggle; Standard: _NORMALMAP keyword; others: assigned = used).
            var bump = T(m, "_BumpMap");
            var useBump = bump != null && (isLil ? F(m, "_UseBumpMap", 0f) > 0.5f
                : kind == ShaderKind.Standard ? m.IsKeywordEnabled("_NORMALMAP") : true);
            if (useBump)
            {
                var n = _tex.Add(bump, TextureKind.Normal);
                if (n.HasValue) mat["normalTexture"] = new JObj { ["index"] = n.Value, ["scale"] = F(m, "_BumpScale", 1f) };
            }

            mat["extensions"] = new JObj
            {
                ["VRMC_materials_mtoon"] = MToon(m, isLil, lower, baseTex),
                ["VCAM_materials_unity"] = Dump(m, kind),
            };
            _b.UseExtension("VRMC_materials_mtoon");
            _b.UseExtension("VCAM_materials_unity");

            if (kind == ShaderKind.LilToonCustom)
                _report.Warn($"머티리얼 '{m.name}': 커스텀 lilToon 셰이더 '{shaderName}'는 폴백에서 일반 lilToon처럼 근사합니다(D-016).");
            else if (kind == ShaderKind.Other)
                _report.Warn($"머티리얼 '{m.name}': 셰이더 '{shaderName}'는 전용 변환이 없어 기본 색과 텍스처만 내보냅니다.");
            return mat;
        }

        /// <summary>
        /// VCAM_materials_unity: every property the material's shader declares, as stored in the material.
        /// The web app's lilToon/Poiyomi ports read these instead of the MToon fallback (D-004).
        /// Colors are GetColor values as authored (sRGB-encoded); in a Linear project Unity linearizes them
        /// before the shader sees them, and the web port must do the same. Every referenced texture is exported
        /// with its detected kind (color / data / normal) and its tiling (scale/offset).
        /// </summary>
        private JObj Dump(Material m, ShaderKind kind)
        {
            var shader = m.shader;
            var floats = new JObj();
            var colors = new JObj();
            var vectors = new JObj();
            var textures = new JObj();
            var hdrColors = new List<object>();
            if (shader != null)
            {
                for (var i = 0; i < shader.GetPropertyCount(); i++)
                {
                    var name = shader.GetPropertyName(i);
                    if (!m.HasProperty(name)) continue;
                    switch (shader.GetPropertyType(i))
                    {
                        case UnityEngine.Rendering.ShaderPropertyType.Color:
                        {
                            var c = m.GetColor(name);
                            colors[name] = new[] { c.r, c.g, c.b, c.a };
                            if ((shader.GetPropertyFlags(i) & UnityEngine.Rendering.ShaderPropertyFlags.HDR) != 0) hdrColors.Add(name);
                            break;
                        }
                        case UnityEngine.Rendering.ShaderPropertyType.Vector:
                        {
                            var v = m.GetVector(name);
                            vectors[name] = new[] { v.x, v.y, v.z, v.w };
                            break;
                        }
                        case UnityEngine.Rendering.ShaderPropertyType.Texture:
                        {
                            var tex = m.GetTexture(name);
                            var s = m.GetTextureScale(name);
                            var o = m.GetTextureOffset(name);
                            var entry = new JObj { ["scale"] = new[] { s.x, s.y }, ["offset"] = new[] { o.x, o.y } };
                            if (tex != null)
                            {
                                var texKind = TextureWriter.DetectKind(tex);
                                entry["name"] = tex.name;
                                entry["kind"] = texKind.ToString();
                                entry["index"] = _tex.Add(tex, texKind);
                                // A render texture is filled by an in-world camera at runtime (e.g. an eye "lens" that
                                // adds a reflection). It cannot be exported, and drawn without it the surface turns
                                // into a white sheet, so the web skips such materials (D-078).
                                if (!(tex is Texture2D)) entry["type"] = tex.GetType().Name;
                                // The sampler state Unity draws with (D-055). Which sampler a shader uses is the port's job.
                                entry["filter"] = tex.filterMode.ToString();
                                entry["wrap"] = new[] { tex.wrapModeU.ToString(), tex.wrapModeV.ToString() };
                                entry["aniso"] = tex.anisoLevel;
                                entry["mipmaps"] = tex.mipmapCount > 1;
                                entry["size"] = new[] { tex.width, tex.height };
                            }
                            else
                            {
                                entry["index"] = null;
                            }
                            textures[name] = entry;
                            break;
                        }
                        default: // Float, Range, Int
                            floats[name] = m.GetFloat(name);
                            break;
                    }
                }
            }
            return new JObj
            {
                ["shader"] = shader != null ? shader.name : null,
                ["family"] = kind.ToString(),
                ["shaderAsset"] = shader != null ? UnityEditor.AssetDatabase.GetAssetPath(shader) : null,
                ["shaderHash"] = ShaderHash(shader),
                ["renderQueue"] = m.renderQueue,
                ["keywords"] = new List<object>(m.shaderKeywords),
                ["floats"] = floats,
                ["colors"] = colors,
                ["hdrColors"] = hdrColors,
                ["vectors"] = vectors,
                ["textures"] = textures,
            };
        }

        private static readonly Dictionary<Shader, string> ShaderHashes = new Dictionary<Shader, string>();

        /// <summary>SHA-256 of the shader file, so a port can tell which version of the shader it was matched to.</summary>
        private static string ShaderHash(Shader shader)
        {
            if (shader == null) return null;
            if (ShaderHashes.TryGetValue(shader, out var known)) return known;
            string hash = null;
            var path = UnityEditor.AssetDatabase.GetAssetPath(shader);
            if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
            {
                using (var sha = System.Security.Cryptography.SHA256.Create())
                    hash = System.BitConverter.ToString(sha.ComputeHash(System.IO.File.ReadAllBytes(path))).Replace("-", "");
            }
            ShaderHashes[shader] = hash;
            return hash;
        }

        private static JObj MToon(Material m, bool isLil, string lowerShaderName, int? baseTex)
        {
            var mtoon = new JObj { ["specVersion"] = "1.0" };

            Color shade;
            float shift, toony;
            if (isLil)
            {
                var useShadow = F(m, "_UseShadow", 1f) > 0.5f;
                var strength = F(m, "_ShadowStrength", 1f);
                shade = useShadow ? Color.Lerp(Color.white, C(m, "_ShadowColor", new Color(0.82f, 0.76f, 0.85f)), strength) : Color.white;
                shift = 1f - 2f * F(m, "_ShadowBorder", 0.5f);
                toony = Mathf.Clamp01(1f - F(m, "_ShadowBlur", 0.1f));
            }
            else
            {
                shade = new Color(0.8f, 0.8f, 0.8f);
                shift = 0f;
                toony = 0.9f;
            }
            mtoon["shadeColorFactor"] = UnityToGltf.LinearRgb(shade);
            // Shade = base texture × shade color, so textured detail survives in shadow.
            if (baseTex.HasValue) mtoon["shadeMultiplyTexture"] = new JObj { ["index"] = baseTex.Value };
            mtoon["shadingShiftFactor"] = Mathf.Clamp(shift, -1f, 1f);
            mtoon["shadingToonyFactor"] = toony;
            mtoon["giEqualizationFactor"] = 0.9f;
            mtoon["parametricRimColorFactor"] = new[] { 0f, 0f, 0f };

            var hasOutline = lowerShaderName.Contains("outline") && m.HasProperty("_OutlineWidth");
            if (hasOutline)
            {
                mtoon["outlineWidthMode"] = "worldCoordinates";
                mtoon["outlineWidthFactor"] = m.GetFloat("_OutlineWidth") * 0.01f;
                mtoon["outlineColorFactor"] = UnityToGltf.LinearRgb(C(m, "_OutlineColor", Color.black));
                mtoon["outlineLightingMixFactor"] = 1f;
            }
            else
            {
                mtoon["outlineWidthMode"] = "none";
            }
            return mtoon;
        }
    }
}
