using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Rendering;
using VCam.Exporter.Gltf;
using VCam.Exporter.Pipeline;
using VCam.Exporter.Util;
using VRC.SDK3.Dynamics.PhysBone.Components;
using JArr = System.Collections.Generic.List<object>;
using JObj = System.Collections.Generic.Dictionary<string, object>;
using Object = UnityEngine.Object;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Builds our own glTF extensions that carry the original Unity data the web app needs to reproduce the
    /// avatar exactly (D-001). Spec: docs/FILE_FORMAT.md.
    /// - VCAM_physbones   : every PhysBone and PhysBone collider, all fields (reflection dump, D-003)
    /// - VCAM_constraints : VRC constraints and Unity constraints, all fields
    /// - VCAM_avatar      : export metadata, expression sources, Unity scene lighting (incl. ambient SH)
    /// Unity-space values (positions, rotations, curves) are written UNCONVERTED: the web side applies the
    /// same X mirror as UnityToGltf (D-018). References carry both "path" and glTF "node".
    /// </summary>
    internal static class VcamExtensions
    {
        /// <summary>2: precise Unity data for shader ports: extra vertex attributes, renderers, texture sampling, quality (D-055).</summary>
        public const int FormatVersion = 2;
        private const int AvatarFormatVersion = 3;
        public const string ExporterVersion = "0.1.0";

        public static RefResolver Refs(Transform root, IReadOnlyDictionary<Transform, int> nodeOf, Func<Component, int?> componentId = null)
        {
            return new RefResolver
            {
                Path = t => t == null ? null : t == root ? "" : t.IsChildOf(root) ? AnimationUtility.CalculateTransformPath(t, root) : null,
                Node = t => t != null && nodeOf.TryGetValue(t, out var n) ? n : (int?)null,
                ComponentId = componentId,
            };
        }

        public static JObj PhysBones(GameObject root, IReadOnlyDictionary<Transform, int> nodeOf, ExportReport report)
        {
            var colliders = root.GetComponentsInChildren<VRCPhysBoneCollider>(true);
            var colliderIndex = new Dictionary<Component, int>();
            for (var i = 0; i < colliders.Length; i++) colliderIndex[colliders[i]] = i;
            var refs = Refs(root.transform, nodeOf, c => c != null && colliderIndex.TryGetValue(c, out var i) ? i : (int?)null);

            var colliderArr = new JArr();
            foreach (var c in colliders)
            {
                var dump = ReflectionDump.Component(c, refs, ReflectionDump.IsEditorOnlyField);
                // Colliders of outfits and hats switched off in the scene stay in the file but must not push bones:
                // without this flag the web let a hidden hat's ear planes fold the ears down (D-078).
                if (!c.gameObject.activeInHierarchy) dump["activeInHierarchy"] = false;
                colliderArr.Add(dump);
            }
            var boneArr = new JArr();
            var outside = 0;
            foreach (var pb in root.GetComponentsInChildren<VRCPhysBone>(true))
            {
                var dump = ReflectionDump.Component(pb, refs, ReflectionDump.IsEditorOnlyField);
                if (!pb.gameObject.activeInHierarchy) dump["activeInHierarchy"] = false;
                foreach (var col in pb.colliders)
                    if (col != null && !colliderIndex.ContainsKey(col)) outside++;
                boneArr.Add(dump);
            }
            if (outside > 0) report.Warn($"아바타 밖에 있는 PhysBone 콜라이더 참조 {outside}개는 내보내지 않았습니다.");
            report.Stat("PhysBone", boneArr.Count);
            report.Stat("PhysBone 콜라이더", colliderArr.Count);
            return new JObj { ["version"] = FormatVersion, ["colliders"] = colliderArr, ["physBones"] = boneArr };
        }

        public static bool IsVrcConstraint(Component c) => c != null && (c.GetType().Namespace ?? "").StartsWith("VRC.SDK3.Dynamics.Constraint");

        public static JObj Constraints(GameObject root, IReadOnlyDictionary<Transform, int> nodeOf, ExportReport report)
        {
            var refs = Refs(root.transform, nodeOf);
            var arr = new JArr();
            foreach (var c in root.GetComponentsInChildren<Component>(true))
            {
                if (c == null) continue;
                var vrc = IsVrcConstraint(c);
                if (!vrc && !(c is IConstraint)) continue;
                var dump = ReflectionDump.Component(c, refs, ReflectionDump.IsEditorOnlyField);
                dump["kind"] = vrc ? "vrc" : "unity";
                if (!c.gameObject.activeInHierarchy) dump["activeInHierarchy"] = false;
                arr.Add(dump);
            }
            report.Stat("컨스트레인트", arr.Count);
            return new JObj { ["version"] = FormatVersion, ["constraints"] = arr };
        }

        public static JObj Avatar(GameObject root, string sourceName, List<MappedExpression> expressions, ExportReport report,
            ExportOptions options, JArr referenceCaptures, JArr renderers = null)
        {
            var exprArr = new JArr();
            foreach (var e in expressions)
                exprArr.Add(new JObj { ["name"] = e.Name, ["preset"] = e.IsPreset, ["source"] = e.Source });

            var obj = new JObj
            {
                ["version"] = AvatarFormatVersion,
                ["exporter"] = "VCam Avatar Exporter " + ExporterVersion,
                ["unityVersion"] = Application.unityVersion,
                ["exportedAt"] = DateTime.Now.ToString("s"),
                ["sourceAvatar"] = sourceName,
                ["state"] = options.state == ExportState.InGameDefault ? "inGameDefault" : "scene",
                ["colorSpace"] = QualitySettings.activeColorSpace == ColorSpace.Linear ? "linear" : "gamma",
                ["expressions"] = exprArr,
                ["lighting"] = Lighting(root, report),
                // How Unity samples and resolves (D-055): forced anisotropic filtering raises texture aniso levels,
                // and MSAA samples are resolved in linear color.
                ["quality"] = new JObj
                {
                    ["anisotropicFiltering"] = QualitySettings.anisotropicFiltering.ToString(),
                    ["antiAliasing"] = QualitySettings.antiAliasing,
                    ["textureMipmapLimit"] = QualitySettings.globalTextureMipmapLimit,
                },
            };
            if (renderers != null && renderers.Count > 0) obj["renderers"] = renderers;
            if (referenceCaptures != null && referenceCaptures.Count > 0) obj["referenceCaptures"] = referenceCaptures;
            return obj;
        }

        /// <summary>
        /// Lighting of the open scene as Unity renders it in the editor. lilToon/Poiyomi read the main
        /// directional light and the ambient spherical harmonics (ShadeSH9), so we export both.
        /// </summary>
        private static JObj Lighting(GameObject avatarRoot, ExportReport report)
        {
            var lights = new JArr();
            foreach (var l in Object.FindObjectsOfType<Light>())
            {
                if (l.type != LightType.Directional || !l.enabled || !l.gameObject.activeInHierarchy) continue;
                if (l.transform.IsChildOf(avatarRoot.transform)) continue;
                lights.Add(new JObj
                {
                    ["name"] = l.name,
                    ["color"] = UnityToGltf.LinearRgb(l.color),
                    ["intensity"] = l.intensity,
                    // Direction the light travels, converted to glTF space.
                    ["direction"] = UnityToGltf.Pos(l.transform.forward),
                    ["shadows"] = l.shadows.ToString(),
                });
            }

            // In batch mode the editor never computed skybox ambient lighting, so ambientProbe was all zeros
            // (seen 2026-11-28). Ask the GI system to refresh it first; warn if it is still empty.
            DynamicGI.UpdateEnvironment();
            var sh = RenderSettings.ambientProbe;
            var shEmpty = true;
            for (var rgb = 0; rgb < 3 && shEmpty; rgb++)
                for (var coef = 0; coef < 9; coef++)
                    if (Mathf.Abs(sh[rgb, coef]) > 1e-6f)
                    {
                        shEmpty = false;
                        break;
                    }
            if (shEmpty && RenderSettings.ambientMode == AmbientMode.Skybox)
                report.Warn("씬의 환경광(앰비언트 SH)이 0입니다. Unity가 아직 환경광을 계산하지 않은 상태로 보입니다. " +
                            "Unity 에디터에서 씬을 연 뒤 내보내면 정상 값이 들어갑니다(배치 모드에서 자주 발생).");
            var shArr = new JArr();
            // 9 coefficients × RGB, Unity's raw SphericalHarmonicsL2 order (not yet converted to unity_SHAr form).
            for (var coef = 0; coef < 9; coef++)
                shArr.Add(new[] { sh[0, coef], sh[1, coef], sh[2, coef] });

            return new JObj
            {
                ["directionalLights"] = lights,
                ["ambientMode"] = RenderSettings.ambientMode.ToString(),
                ["ambientIntensity"] = RenderSettings.ambientIntensity,
                ["ambientColor"] = UnityToGltf.LinearRgb(RenderSettings.ambientLight),
                ["ambientSkyColor"] = UnityToGltf.LinearRgb(RenderSettings.ambientSkyColor),
                ["ambientEquatorColor"] = UnityToGltf.LinearRgb(RenderSettings.ambientEquatorColor),
                ["ambientGroundColor"] = UnityToGltf.LinearRgb(RenderSettings.ambientGroundColor),
                ["ambientSH"] = shArr,
                ["shNote"] = "Unity SphericalHarmonicsL2 raw coefficients [coef][rgb], Unity world space (not mirrored)",
            };
        }
    }
}
