using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using VRC.SDKBase.Editor.BuildPipeline;
using Object = UnityEngine.Object;

namespace VCam.Exporter.Pipeline
{
    /// <summary>
    /// Produces the "as uploaded" version of an avatar without touching the original.
    ///
    /// How: clone the avatar root, then call VRCBuildPipelineCallbacks.OnPreprocessAvatar(clone).
    /// That runs every IVRCSDKPreprocessAvatarCallback registered in the project, i.e. exactly what
    /// VRChat runs on upload: NDMF (Modular Avatar and other NDMF plugins), VRCFury, lilToon's
    /// VRChat module, and so on. We do not call MA/VRCFury APIs directly, so new versions or other
    /// build-time tools keep working without code changes.
    ///
    /// Precedent: VRCFury's own "Build an Editor Test Copy" menu does the same thing
    /// (Packages/com.vrcfury.vrcfury/Editor/VF/Menu/VRCFuryTestCopyMenuItem.cs).
    /// </summary>
    internal static class AvatarBaker
    {
        public sealed class Result
        {
            public GameObject Clone;
            public string Error;
            /// <summary>
            /// Stored, not computed from Clone: after the caller destroys the clone, Unity's fake-null makes
            /// "Clone != null" false, which once turned a successful bake into a reported failure.
            /// </summary>
            public bool Ok;
        }

        public const string CloneSuffix = " (VCam Bake)";

        /// <summary>
        /// True for an object that is already a baked copy: our clone (name suffix) or a VRCFury build/test copy
        /// (VRCFury leaves a VF.Model.VRCFuryTest marker). Baking those again is wrong, and a leftover clone saved
        /// into a scene was once picked up as a second avatar by batch export (2026-11-28).
        /// </summary>
        public static bool IsBakedCopy(GameObject go)
        {
            if (go == null) return false;
            if (go.name.EndsWith(CloneSuffix)) return true;
            foreach (var c in go.GetComponents<Component>())
                if (c != null && c.GetType().FullName == "VF.Model.VRCFuryTest") return true;
            return false;
        }

        /// <summary>Caller owns the returned clone and must destroy it (Object.DestroyImmediate) when done.</summary>
        public static Result BakeClone(GameObject avatarRoot)
        {
            if (avatarRoot == null) return new Result { Error = "아바타가 선택되지 않았습니다." };

            var clone = Object.Instantiate(avatarRoot);
            clone.name = avatarRoot.name + CloneSuffix;
            if (clone.scene != avatarRoot.scene) SceneManager.MoveGameObjectToScene(clone, avatarRoot.scene);

            bool ok;
            string error = null;
            try
            {
                ok = VRCBuildPipelineCallbacks.OnPreprocessAvatar(clone);
            }
            catch (Exception e)
            {
                ok = false;
                error = e.ToString();
            }

            if (!ok)
            {
                if (clone != null) Object.DestroyImmediate(clone);
                return new Result
                {
                    Error = error ?? "VRChat 빌드 전처리(OnPreprocessAvatar)가 실패했습니다. Console 창의 오류를 확인하세요.",
                };
            }

            // OnPreprocessAvatar may replace or remove objects; re-check before use.
            if (clone == null) return new Result { Error = "전처리 후 복제본이 사라졌습니다." };
            clone.SetActive(true);
            return new Result { Clone = clone, Ok = true };
        }
    }
}
