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

namespace VCam.Exporter.Export
{
    /// <summary>How a texture's pixels must be read back.</summary>
    internal enum TextureKind
    {
        /// <summary>sRGB color (albedo, emission, matcap ...).</summary>
        Color,
        /// <summary>Linear data (masks, noise, flow ...).</summary>
        Data,
        /// <summary>Unity normal map (packed DXT5nm/BC5): decoded to RGB tangent-space normals.</summary>
        Normal,
    }

    /// <summary>
    /// Encodes Unity textures to PNG and adds them as glTF images/textures (deduplicated by texture + kind).
    ///
    /// Why a GPU blit instead of Texture2D.GetPixels: avatar textures are usually compressed (DXT/BC7) and
    /// not CPU-readable. Blitting into a RenderTexture and reading it back works for any texture without
    /// changing import settings. sRGB textures go through an sRGB render target so the stored bytes stay
    /// sRGB-encoded; data textures through a linear target; normal maps through Hidden/VCam/DecodeNormal.
    /// Requires a graphics device: do not run batch exports with -nographics.
    /// </summary>
    internal sealed class TextureWriter
    {
        private const string DecodeShaderPath = "Packages/com.vcam.avatar-exporter/Editor/Shaders/VCamDecodeNormal.shader";
        /// <summary>
        /// The decode shader's GUID (its .meta): found wherever the exporter is installed, Packages/ (VCC, the old ZIP)
        /// or Assets/VirtualCam/AvatarExporter (the .unitypackage, D-077).
        /// </summary>
        private const string DecodeShaderGuid = "c330fa01eb138654285d1c14ed07f2ee";

        private readonly GltfBuilder _b;
        private readonly ExportReport _report;
        private readonly int _maxSize;
        private readonly Dictionary<(int, TextureKind), int> _cache = new Dictionary<(int, TextureKind), int>();
        private readonly Dictionary<(TextureWrapMode, TextureWrapMode), int> _samplers = new Dictionary<(TextureWrapMode, TextureWrapMode), int>();
        private Material _decodeNormal;

        public int Count => _cache.Count;
        public long TotalPngBytes { get; private set; }

        public TextureWriter(GltfBuilder b, ExportReport report, int maxSize)
        {
            _b = b;
            _report = report;
            _maxSize = maxSize;
        }

        /// <summary>Kind from the texture's import settings (normal map type, sRGB flag).</summary>
        public static TextureKind DetectKind(Texture tex)
        {
            if (tex == null) return TextureKind.Color;
            if (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tex)) is TextureImporter ti)
            {
                if (ti.textureType == TextureImporterType.NormalMap) return TextureKind.Normal;
                return ti.sRGBTexture ? TextureKind.Color : TextureKind.Data;
            }
            // Generated textures (e.g. by NDMF/lilToon bake) have no importer: trust the GPU format.
            return GraphicsFormatUtility.IsSRGBFormat(tex.graphicsFormat) ? TextureKind.Color : TextureKind.Data;
        }

        /// <returns>glTF texture index, or null if the texture cannot be exported.</returns>
        public int? Add(Texture tex, TextureKind kind)
        {
            if (tex == null) return null;
            if (!(tex is Texture2D t2d))
            {
                _report.Warn($"텍스처 '{tex.name}'({tex.GetType().Name})는 Texture2D가 아니라 내보내지 않았습니다.");
                return null;
            }
            var key = (t2d.GetInstanceID(), kind);
            if (_cache.TryGetValue(key, out var cached)) return cached;

            var png = EncodePng(t2d, kind, out var w, out var h);
            if (png == null) return null;
            TotalPngBytes += png.Length;
            if (w != t2d.width || h != t2d.height)
                _report.Note($"텍스처 '{t2d.name}' {t2d.width}×{t2d.height} → {w}×{h}로 줄임 (최대 {_maxSize})");

            var image = _b.AddImagePng(png, t2d.name);
            var index = _b.AddTexture(image, Sampler(t2d.wrapModeU, t2d.wrapModeV));
            _cache[key] = index;
            return index;
        }

        private int Sampler(TextureWrapMode u, TextureWrapMode v)
        {
            if (_samplers.TryGetValue((u, v), out var s)) return s;
            int Wrap(TextureWrapMode m) => m == TextureWrapMode.Clamp ? 33071 : m == TextureWrapMode.Mirror ? 33648 : 10497;
            s = _b.AddSampler(new JObj
            {
                ["magFilter"] = 9729, // LINEAR
                ["minFilter"] = 9987, // LINEAR_MIPMAP_LINEAR
                ["wrapS"] = Wrap(u),
                ["wrapT"] = Wrap(v),
            });
            _samplers[(u, v)] = s;
            return s;
        }

        private Material DecodeNormalMaterial()
        {
            if (_decodeNormal != null) return _decodeNormal;
            var byGuid = AssetDatabase.GUIDToAssetPath(DecodeShaderGuid);
            var shader = (string.IsNullOrEmpty(byGuid) ? null : AssetDatabase.LoadAssetAtPath<Shader>(byGuid))
                ?? AssetDatabase.LoadAssetAtPath<Shader>(DecodeShaderPath) ?? Shader.Find("Hidden/VCam/DecodeNormal");
            if (shader == null) return null;
            _decodeNormal = new Material(shader) { hideFlags = HideFlags.HideAndDontSave };
            return _decodeNormal;
        }

        private byte[] EncodePng(Texture2D tex, TextureKind kind, out int w, out int h)
        {
            w = tex.width;
            h = tex.height;
            var longest = Mathf.Max(w, h);
            if (_maxSize > 0 && longest > _maxSize)
            {
                var scale = (float)_maxSize / longest;
                w = Mathf.Max(1, Mathf.RoundToInt(w * scale));
                h = Mathf.Max(1, Mathf.RoundToInt(h * scale));
            }

            var linear = kind != TextureKind.Color;
            var rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32,
                linear ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB);
            var prev = RenderTexture.active;
            try
            {
                if (kind == TextureKind.Normal)
                {
                    var mat = DecodeNormalMaterial();
                    if (mat == null)
                    {
                        _report.Warn($"노멀맵 디코딩 셰이더를 찾지 못해 '{tex.name}'를 내보내지 않았습니다.");
                        return null;
                    }
                    Graphics.Blit(tex, rt, mat);
                }
                else
                {
                    Graphics.Blit(tex, rt);
                }
                RenderTexture.active = rt;
                var readback = new Texture2D(w, h, TextureFormat.RGBA32, false, linear);
                readback.ReadPixels(new Rect(0, 0, w, h), 0, 0);
                readback.Apply();
                var png = readback.EncodeToPNG();
                Object.DestroyImmediate(readback);
                return png;
            }
            finally
            {
                RenderTexture.active = prev;
                RenderTexture.ReleaseTemporary(rt);
            }
        }

        public void Dispose()
        {
            if (_decodeNormal != null) Object.DestroyImmediate(_decodeNormal);
        }
    }
}
