using Alibabacloud.Rum.Unity.Logs;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;

namespace Alibabacloud.Rum.Unity.Editor
{
    /// <summary>
    /// Preprocessor that ensures IL2CPP emits source mapping files when OutputSymbols is enabled.
    /// This is required for proper stack trace symbolication on IL2CPP builds.
    /// </summary>
    public class Il2CppBuildPreprocess : IPreprocessBuildWithReport
    {
        private const string Il2CppEmitSourceMappingArg = "--emit-source-mapping";

        /// <summary>
        /// Callback order - runs early in the build process
        /// </summary>
        public int callbackOrder => 0;

        /// <summary>
        /// Called before the build starts. Adds IL2CPP arguments if symbol output is enabled.
        /// </summary>
        public void OnPreprocessBuild(BuildReport report)
        {
            // Only process IL2CPP builds
            if (PlayerSettings.GetScriptingBackend(report.summary.platformGroup) != ScriptingImplementation.IL2CPP)
            {
                UnityEngine.Debug.Log($"[ALIBABACLOUD] Skipping symbol processing - not using IL2CPP backend (current: {PlayerSettings.GetScriptingBackend(report.summary.platformGroup)})");
                return;
            }

            var options = AlibabacloudOptionsExtensions.GetOrCreate();
            if (options == null)
            {
                return;
            }
            
            var il2CppArgs = PlayerSettings.GetAdditionalIl2CppArgs();
            
            if (options.Enabled && options.OutputSymbols)
            {
                // Add the emit source mapping argument if not already present
                if (!il2CppArgs.Contains(Il2CppEmitSourceMappingArg))
                {
                    il2CppArgs += $" {Il2CppEmitSourceMappingArg}";
                    PlayerSettings.SetAdditionalIl2CppArgs(il2CppArgs);
                }
            }
            else
            {
                // Remove the emit source mapping argument if present
                if (il2CppArgs.Contains(Il2CppEmitSourceMappingArg))
                {
                    il2CppArgs = il2CppArgs.Replace(Il2CppEmitSourceMappingArg, string.Empty).Trim();
                    PlayerSettings.SetAdditionalIl2CppArgs(il2CppArgs);
                }
            }
        }
    }
}
