#if TOPON_HAS_CC_FRAMEWORK_COMMON_BUILD_WINDOW
using UnityEditor;
using UnityEngine;

namespace Topon_Adapter.Editor
{
    [InitializeOnLoad]
    internal static class ToponBuildWindowExtensionBootstrap
    {
        static ToponBuildWindowExtensionBootstrap()
        {
            BuildWindowExtensionRegistry.Register(new ToponBuildWindowExtension());
        }
    }

    public sealed class ToponBuildWindowExtension : IBuildWindowExtension
    {
        public string Id => "com.commercialization.topon.build.settings";
        public string DisplayName => "TopOn 配置";
        public int Order => 80;

        public void DrawSection(BuildWindowExtensionContext context)
        {
            var profile = context?.profile;
            if (profile == null)
            {
                EditorGUILayout.HelpBox("当前没有构建配置。", MessageType.Info);
                return;
            }

            var settings = ToponBuildSettingsStore.LoadForProfileName(profile.profileName, context.repositoryRoot);

            EditorGUILayout.LabelField("TopOn Android 调试工具", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox(
                "Android 正式 release 默认关闭 DebugUI。verbto util 独立控制，默认强制指定到 1.1.3，避免回落到存在数据库降级风险的旧版本。",
                MessageType.Info);

            EditorGUI.BeginChangeCheck();
            settings.enableDebuggerUI = EditorGUILayout.Toggle(
                new GUIContent("启用 Android DebugUI 依赖", "仅用于开发/测试包；正式 release 应保持关闭。"),
                settings.enableDebuggerUI);

            settings.forceVerbtoUtilVersion = EditorGUILayout.Toggle(
                new GUIContent("强制指定 verbto util", "无论 DebugUI 是否启用，都声明下方的 com.verbto.tools:util 坐标；取消勾选后交给 Taku/宿主项目自动处理。"),
                settings.forceVerbtoUtilVersion);

            using (new EditorGUI.DisabledScope(!settings.forceVerbtoUtilVersion))
            {
                settings.verbtoUtilDependency = EditorGUILayout.TextField(
                    new GUIContent("util 坐标", "默认 com.verbto.tools:util:1.1.3；Taku 修复后可取消强制指定。"),
                    ToponBuildSettingsStore.GetVerbtoUtilDependency(settings));
            }

            settings.stripResolvedDebuggerArtifacts = EditorGUILayout.Toggle(
                new GUIContent("禁用时剔除 DebugUI 旧产物", "关闭 DebugUI 时，从生成的 Gradle 工程中删除旧 Resolver 带入的 debugger-ui AAR；不会把 verbto util 当作 DebugUI 一起剔除。"),
                settings.stripResolvedDebuggerArtifacts);

            EditorGUILayout.Space(6);
            EditorGUILayout.LabelField("TopOn iOS 调试工具", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox(
                "iOS DebugUI 通过导出后的 Podfile 写入 AnyThinkDebugUISDK。当前 Taku iOS SDK 6.5.45 对应 DebugUI 1.0.7；正式 release 应保持关闭。",
                MessageType.Info);

            settings.enableIOSDebuggerUI = EditorGUILayout.Toggle(
                new GUIContent("启用 iOS DebugUI Pod", "仅用于开发/测试包；启用后导出工程 Podfile 会写入 AnyThinkDebugUISDK。"),
                settings.enableIOSDebuggerUI);

            using (new EditorGUI.DisabledScope(!settings.enableIOSDebuggerUI))
            {
                settings.iosDebuggerPodVersion = EditorGUILayout.TextField(
                    new GUIContent("iOS DebugUI 版本", "Taku iOS SDK 6.5.45 推荐 AnyThinkDebugUISDK 1.0.7。"),
                    ToponBuildSettingsStore.GetIOSDebuggerPodVersion(settings));
            }

            if (EditorGUI.EndChangeCheck())
            {
                ToponBuildSettingsStore.SaveForProfileName(profile.profileName, context.repositoryRoot, settings);
            }

            EditorGUILayout.Space(6);
            if (settings.enableDebuggerUI)
            {
                EditorGUILayout.HelpBox("当前配置会把 TopOn Android DebugUI 打进 Android 构建；请不要用于正式 release。", MessageType.Warning);
            }
            else
            {
                EditorGUILayout.HelpBox("当前配置不会打包 TopOn Android DebugUI。", MessageType.None);
            }

            if (settings.enableIOSDebuggerUI)
            {
                EditorGUILayout.HelpBox($"当前配置会在 iOS Podfile 写入 {ToponBuildSettingsStore.IOSDebuggerPodName} {ToponBuildSettingsStore.GetIOSDebuggerPodVersion(settings)}；请不要用于正式 release。", MessageType.Warning);
            }
            else
            {
                EditorGUILayout.HelpBox("当前配置不会打包 TopOn iOS DebugUI。", MessageType.None);
            }

            if (settings.forceVerbtoUtilVersion)
            {
                EditorGUILayout.HelpBox($"当前会强制声明 {ToponBuildSettingsStore.GetVerbtoUtilDependency(settings)}。", MessageType.None);
            }
            else
            {
                EditorGUILayout.HelpBox("当前不会干预 verbto util 版本，由 Taku/宿主项目依赖解析决定。", MessageType.Info);
            }

            DrawResolverStatus(context);
        }

        public BuildWindowExtensionReport Preflight(BuildWindowExtensionContext context)
        {
            var profile = context?.profile;
            if (profile == null)
            {
                return BuildWindowExtensionReport.Pass();
            }

            var settings = ToponBuildSettingsStore.LoadForProfileName(profile.profileName, context.repositoryRoot);
            ToponBuildSettingsStore.SetActiveForCurrentBuild(settings);

            var report = BuildWindowExtensionReport.Pass();
            if (settings.enableDebuggerUI)
            {
                report.AddMessage("TopOn Android DebugUI 已启用。");
                if (!profile.isDevelopment)
                {
                    report.AddWarning("Android DebugUI 已启用，但当前不是 Development Build，请确认该配置不是正式 release。");
                }
            }
            else
            {
                report.AddMessage("TopOn Android DebugUI 已关闭，构建产物不会打包 debugger-ui。");
            }

            if (settings.enableIOSDebuggerUI)
            {
                report.AddMessage($"TopOn iOS DebugUI 已启用，将写入 {ToponBuildSettingsStore.IOSDebuggerPodName} {ToponBuildSettingsStore.GetIOSDebuggerPodVersion(settings)}。");
                if (!profile.isDevelopment)
                {
                    report.AddWarning("iOS DebugUI 已启用，但当前不是 Development Build，请确认该配置不是正式 release。");
                }
            }
            else
            {
                report.AddMessage("TopOn iOS DebugUI 已关闭，导出工程不会写入 AnyThinkDebugUISDK。");
            }

            if (!settings.enableDebuggerUI && ToponBuildSettingsStore.HasStaleDebuggerResolverOutput(context.repositoryRoot))
            {
                report.AddWarning("检测到旧 Resolver 输出仍包含 TopOn DebugUI；本次构建会在生成 Gradle 后剔除，建议后续重新 Resolve。");
            }

            if (settings.forceVerbtoUtilVersion)
            {
                var dependency = ToponBuildSettingsStore.GetVerbtoUtilDependency(settings);
                report.AddMessage($"TopOn 将强制声明 {dependency}。");
                if (ToponBuildSettingsStore.HasUnforcedVerbtoUtilOutput(context.repositoryRoot, dependency))
                {
                    report.AddWarning($"检测到旧 Resolver 输出或本地 AAR 可能不是 {dependency}；本次构建会在生成 Gradle 后改写为强制版本。");
                }
            }
            else
            {
                report.AddMessage("TopOn 不干预 verbto util 版本。");
            }

            return report;
        }

        public BuildWindowExtensionReport PostBuild(BuildWindowExtensionContext context)
        {
            return BuildWindowExtensionReport.Pass();
        }

        private static void DrawResolverStatus(BuildWindowExtensionContext context)
        {
            var profile = context?.profile;
            var settings = profile == null
                ? ToponBuildSettingsStore.CreateDefault()
                : ToponBuildSettingsStore.LoadForProfileName(profile.profileName, context.repositoryRoot);
            var dependency = ToponBuildSettingsStore.GetVerbtoUtilDependency(settings);
            var hasStaleDebuggerOutput = ToponBuildSettingsStore.HasStaleDebuggerResolverOutput(context.repositoryRoot);
            var hasUnforcedUtilOutput = ToponBuildSettingsStore.HasUnforcedVerbtoUtilOutput(context.repositoryRoot, dependency);
            var debuggerArtifacts = ToponBuildSettingsStore.FindResolvedDebuggerArtifacts(context.repositoryRoot);
            var utilArtifacts = ToponBuildSettingsStore.FindResolvedVerbtoUtilArtifacts(context.repositoryRoot);

            EditorGUILayout.Space(6);
            EditorGUILayout.LabelField("本地依赖状态", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("旧 DebugUI 输出", hasStaleDebuggerOutput ? "检测到 debugger-ui" : "未检测到");
            EditorGUILayout.LabelField("Android DebugUI AAR/JAR", debuggerArtifacts.Count == 0 ? "未检测到" : $"{debuggerArtifacts.Count} 个");
            EditorGUILayout.LabelField("verbto util 强制", settings.forceVerbtoUtilVersion ? dependency : "自动/不干预");
            EditorGUILayout.LabelField("verbto util 本地产物", utilArtifacts.Count == 0 ? "未检测到" : $"{utilArtifacts.Count} 个");
            EditorGUILayout.LabelField("iOS DebugUI Pod", settings.enableIOSDebuggerUI
                ? $"{ToponBuildSettingsStore.IOSDebuggerPodName} {ToponBuildSettingsStore.GetIOSDebuggerPodVersion(settings)}"
                : "关闭");
            if (settings.forceVerbtoUtilVersion && hasUnforcedUtilOutput)
            {
                EditorGUILayout.HelpBox("检测到本地/Resolver 中存在非强制版本的 verbto util；Android Gradle 工程生成后会改写依赖，并清理旧版本本地产物。", MessageType.Warning);
            }
        }
    }
}
#endif
