using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using VCam.Exporter.Gltf;
using VCam.Exporter.Pipeline;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;
using Object = UnityEngine.Object;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Renders reference screenshots of the baked avatar with Unity's real shaders and the scene lighting
    /// (D-026). The web compare tool (M4) renders the .vrm with the same camera and measures the difference,
    /// which is how "looks exactly like Unity" is checked.
    ///
    /// - Neutral and posed shots use the same export nodes and a transparent 1024×1024 target.
    /// - Only the avatar is drawn: it is moved to a temporary layer that the capture camera alone sees.
    /// - Camera data is stored in VCAM_avatar.referenceCaptures in glTF space relative to the avatar root
    ///   (position + target + up + vertical FOV), so a three.js camera can use lookAt() directly.
    /// Edit mode: capture rotations and morph weights explicitly without simulating PhysBones.
    /// </summary>
    internal static class ReferenceCapture
    {
        private const int CaptureLayer = 31;
        private const int Size = 1024;
        private const float Fov = 30f;

        public static JArr Capture(GameObject root, string outputVrmPath, ExportReport report,
            IReadOnlyDictionary<Transform, int> nodes, IReadOnlyDictionary<SkinnedMeshRenderer, int> meshNodes,
            IReadOnlyList<MappedExpression> expressions)
        {
            var captures = new JArr();
            var renderers = root.GetComponentsInChildren<Renderer>().Where(r => r.enabled && r.gameObject.activeInHierarchy).ToArray();
            if (renderers.Length == 0) return captures;
            var skins = renderers.OfType<SkinnedMeshRenderer>().Where(r => r.sharedMesh != null).ToArray();

            var bounds = renderers[0].bounds;
            foreach (var r in renderers) bounds.Encapsulate(r.bounds);

            var layers = root.GetComponentsInChildren<Transform>(true).ToDictionary(t => t, t => t.gameObject.layer);
            foreach (var t in layers.Keys) t.gameObject.layer = CaptureLayer;

            var camGo = new GameObject("VCam Reference Camera") { hideFlags = HideFlags.HideAndDontSave };
            var cam = camGo.AddComponent<Camera>();
            cam.cullingMask = 1 << CaptureLayer;
            cam.clearFlags = CameraClearFlags.SolidColor;
            cam.backgroundColor = new Color(0, 0, 0, 0);
            cam.fieldOfView = Fov;
            cam.nearClipPlane = 0.01f;
            cam.farClipPlane = 100f;
            cam.allowHDR = false;
            var rt = new RenderTexture(Size, Size, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { antiAliasing = 4 };
            cam.targetTexture = rt;

            try
            {
                DynamicGI.UpdateEnvironment();
                var forward = root.transform.forward; // Unity avatars face +Z of the root
                var up = root.transform.up;
                var halfFov = Fov * 0.5f * Mathf.Deg2Rad;

                void Add(string name, Vector3 center, float distance, float yaw = 0f, JObj pose = null)
                {
                    var direction = Quaternion.AngleAxis(yaw, up) * forward;
                    JObj Render() => Shot(name, cam, rt, root.transform, center, center + direction * distance, outputVrmPath);
                    var capture = pose == null ? Render() : WithFreshSkin(skins, Render);
                    if (pose != null) capture["pose"] = pose;
                    captures.Add(capture);
                }

                var fullDist = bounds.extents.y / Mathf.Tan(halfFov) * 1.1f + bounds.extents.z;
                Add("full", bounds.center, fullDist);

                // Face close-up around the head bone (falls back to the top of the bounds).
                var animator = root.GetComponent<Animator>();
                var head = animator != null && animator.isHuman ? animator.GetBoneTransform(HumanBodyBones.Head) : null;
                var faceCenter = head != null ? head.position + up * 0.06f : bounds.center + up * bounds.extents.y * 0.8f;
                var faceDist = 0.22f / Mathf.Tan(halfFov) + 0.1f;
                Add("face", faceCenter, faceDist);
                Add("full-three-quarter", bounds.center, fullDist, 40f);
                Add("full-back", bounds.center, fullDist, 180f);

                void Express(string name, string expression, float weight, float yaw)
                {
                    var bindings = expressions.FirstOrDefault(x => x.Name == expression)?.Binds
                        .Where(x => meshNodes.ContainsKey(x.Renderer)).ToArray();
                    if (bindings == null || bindings.Length == 0) return;
                    var pose = new JArr();
                    var original = bindings.Select(x => x.Renderer.GetBlendShapeWeight(x.BlendShapeIndex)).ToArray();
                    try
                    {
                        foreach (var bind in bindings)
                        {
                            var value = Mathf.Clamp01(bind.Weight * weight);
                            bind.Renderer.SetBlendShapeWeight(bind.BlendShapeIndex, 100f * value);
                            pose.Add(new JObj { ["node"] = meshNodes[bind.Renderer], ["index"] = bind.BlendShapeIndex, ["weight"] = value });
                        }
                        Add(name, faceCenter, faceDist, yaw, new JObj { ["morphs"] = pose });
                    }
                    finally
                    {
                        for (var i = 0; i < bindings.Length; i++)
                            bindings[i].Renderer.SetBlendShapeWeight(bindings[i].BlendShapeIndex, original[i]);
                    }
                }
                Express("face-wink", "blinkLeft", 1f, 15f);
                Express("face-speaking", "aa", 0.8f, -15f);

                if (animator != null && animator.isHuman)
                {
                    var joints = new[]
                    {
                        (HumanBodyBones.Spine, up, 16f),
                        (HumanBodyBones.Head, up, -22f),
                        (HumanBodyBones.LeftUpperArm, forward, -50f),
                        (HumanBodyBones.LeftLowerArm, up, 55f),
                    };
                    var original = new Dictionary<Transform, Quaternion>();
                    var rotations = new JArr();
                    try
                    {
                        foreach (var (id, axis, angle) in joints)
                        {
                            var bone = animator.GetBoneTransform(id);
                            if (bone == null || !nodes.TryGetValue(bone, out var node)) continue;
                            original.Add(bone, bone.localRotation);
                            bone.rotation = Quaternion.AngleAxis(angle, axis) * bone.rotation;
                            rotations.Add(new JObj { ["node"] = node, ["rotation"] = UnityToGltf.Rot(bone.localRotation) });
                        }
                        if (rotations.Count != 0) Add("full-pose", bounds.center, fullDist, -25f, new JObj { ["bones"] = rotations });
                    }
                    finally
                    {
                        foreach (var (bone, rotation) in original) bone.localRotation = rotation;
                    }
                }
            }
            finally
            {
                cam.targetTexture = null;
                Object.DestroyImmediate(rt);
                Object.DestroyImmediate(camGo);
                foreach (var kv in layers)
                    if (kv.Key != null) kv.Key.gameObject.layer = kv.Value;
            }
            report.Stat("기준 스크린샷", captures.Count);
            return captures;
        }

        // Camera.Render can reuse a skin from the earlier camera in the same editor frame. Fresh renderers
        // read the modified bones and weights for this shot while keeping Unity's actual skinning and shaders.
        private static JObj WithFreshSkin(SkinnedMeshRenderer[] skins, Func<JObj> render)
        {
            var temporary = new List<GameObject>();
            try
            {
                foreach (var source in skins)
                {
                    var original = source.transform;
                    var clone = new GameObject("VCam Reference Skin") { layer = CaptureLayer, hideFlags = HideFlags.HideAndDontSave };
                    temporary.Add(clone);
                    clone.transform.SetParent(original.parent, false);
                    clone.transform.localPosition = original.localPosition;
                    clone.transform.localRotation = original.localRotation;
                    clone.transform.localScale = original.localScale;
                    var fresh = clone.AddComponent<SkinnedMeshRenderer>();
                    EditorUtility.CopySerialized(source, fresh);
                    for (var i = 0; i < source.sharedMesh.blendShapeCount; i++)
                        fresh.SetBlendShapeWeight(i, source.GetBlendShapeWeight(i));
                    source.enabled = false;
                }
                return render();
            }
            finally
            {
                foreach (var clone in temporary) Object.DestroyImmediate(clone);
                foreach (var source in skins) source.enabled = true;
            }
        }

        private static JObj Shot(string name, Camera cam, RenderTexture rt, Transform root, Vector3 target, Vector3 position, string outputVrmPath)
        {
            cam.transform.position = position;
            cam.transform.LookAt(target, root.up);
            cam.Render();

            var prev = RenderTexture.active;
            var tex = new Texture2D(Size, Size, TextureFormat.RGBA32, false, false);
            byte[] png;
            try
            {
                RenderTexture.active = rt;
                tex.ReadPixels(new Rect(0, 0, Size, Size), 0, 0);
                tex.Apply();
                png = tex.EncodeToPNG();
            }
            finally
            {
                RenderTexture.active = prev;
                Object.DestroyImmediate(tex);
            }

            var file = Path.GetFileNameWithoutExtension(outputVrmPath) + ".ref-" + name + ".png";
            var dir = Path.GetDirectoryName(Path.GetFullPath(outputVrmPath));
            Directory.CreateDirectory(dir);
            File.WriteAllBytes(Path.Combine(dir, file), png);

            // Camera in glTF space relative to the avatar root (root = origin, D-018 mirror).
            return new JObj
            {
                ["name"] = name,
                ["file"] = file,
                ["width"] = Size,
                ["height"] = Size,
                ["fovY"] = Fov,
                ["near"] = cam.nearClipPlane,
                ["far"] = cam.farClipPlane,
                ["position"] = UnityToGltf.Pos(root.InverseTransformPoint(position)),
                ["target"] = UnityToGltf.Pos(root.InverseTransformPoint(target)),
                ["up"] = UnityToGltf.Pos(root.InverseTransformDirection(root.up)),
                ["background"] = "transparent",
            };
        }
    }
}
