#if UNITY_IOS
using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

public class NotificationAutoConfig : IPreprocessBuildWithReport
{
    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report)
    {
        if (report.summary.platform != BuildTarget.iOS) return;

        // 1. 构造文件绝对路径
        string settingsPath = "ProjectSettings/NotificationsSettings.asset";
        string fullPath = Path.GetFullPath(Path.Combine(Application.dataPath, "..", settingsPath));

        if (!File.Exists(fullPath))
        {
            Debug.LogError($"[NotificationAutoConfig] 文件不存在: {fullPath}");
            return;
        }

        // 2. 通过反射获取 NotificationSettingsManager 类型
        Type managerType = null;
        foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
        {
            managerType = asm.GetType("Unity.Notifications.NotificationSettingsManager");
            if (managerType != null) break;
        }

        if (managerType == null)
        {
            Debug.LogError("[NotificationAutoConfig] 无法找到 NotificationSettingsManager 类型。");
            return;
        }

        // 3. 读取文件 JSON，创建 Manager 实例并用 JSON 覆盖数据
        string json = File.ReadAllText(fullPath);
        ScriptableObject managerInstance = ScriptableObject.CreateInstance(managerType);
        EditorJsonUtility.FromJsonOverwrite(json, managerInstance);

        // 4. 获取 m_iOSNotificationSettingsValues 字段（NotificationSettingsCollection）
        FieldInfo settingsField = managerType.GetField("m_iOSNotificationSettingsValues",
            BindingFlags.NonPublic | BindingFlags.Instance);
        if (settingsField == null)
        {
            Debug.LogError("[NotificationAutoConfig] 找不到 m_iOSNotificationSettingsValues 字段。");
            ScriptableObject.DestroyImmediate(managerInstance);
            return;
        }

        object iOSSettings = settingsField.GetValue(managerInstance);
        if (iOSSettings == null)
        {
            Debug.LogError("[NotificationAutoConfig] m_iOSNotificationSettingsValues 为 null。");
            ScriptableObject.DestroyImmediate(managerInstance);
            return;
        }

        // 5. 获取索引器（this[string key]）
        Type collectionType = iOSSettings.GetType();
        PropertyInfo indexer = collectionType.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance);
        if (indexer == null)
        {
            Debug.LogError("[NotificationAutoConfig] 无法找到 NotificationSettingsCollection 的索引器。");
            ScriptableObject.DestroyImmediate(managerInstance);
            return;
        }

        // 6. 修改目标键的值
        bool changed = false;
        changed |= SetSettingValue(indexer, iOSSettings, "UnityNotificationRequestAuthorizationOnAppLaunch", false);
        changed |= SetSettingValue(indexer, iOSSettings, "UnityAddRemoteNotificationCapability", true);
        changed |= SetSettingValue(indexer, iOSSettings, "UnityUseAPSReleaseEnvironment", true);

        // 7. 写回文件并刷新
        if (changed)
        {
            string newJson = EditorJsonUtility.ToJson(managerInstance, true);
            File.WriteAllText(fullPath, newJson);
            AssetDatabase.Refresh();
            Debug.Log("[NotificationAutoConfig] iOS 通知配置已成功更新。");
        }
        else
        {
            Debug.Log("[NotificationAutoConfig] 配置已是预期状态，无需修改。");
        }

        ScriptableObject.DestroyImmediate(managerInstance);
    }

    private bool SetSettingValue(PropertyInfo indexer, object collection, string key, bool value)
    {
        object current = indexer.GetValue(collection, new object[] { key });
        if (current is bool b && b == value)
            return false;

        indexer.SetValue(collection, value, new object[] { key });
        Debug.Log($"[NotificationAutoConfig] 修改 {key} = {value}");
        return true;
    }
}
#endif