#if UNITY_IOS
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using System.IO;
using System.Collections.Generic;
using UnityEngine;

public class ConfigurableLocalizationPostProcess
{
    [PostProcessBuild(500)]
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        if (target != BuildTarget.iOS) return;

        // 加载配置
        IOSLocalizationSettings settings = AssetDatabase.LoadAssetAtPath<IOSLocalizationSettings>("Assets/Editor/LocalizationSettings.asset");

        if (settings == null)
        {
            UnityEngine.Debug.LogWarning("未找到LocalizationSettings配置，使用默认多语言设置");
            settings = ScriptableObject.CreateInstance<IOSLocalizationSettings>();
        }

        // 处理主Info.plist
        string plistPath = Path.Combine(pathToBuiltProject, "Info.plist");

        if (!File.Exists(plistPath))
        {
            UnityEngine.Debug.LogWarning("Info.plist文件未找到: " + plistPath);
            return;
        }

        PlistDocument plist = new PlistDocument();
        plist.ReadFromFile(plistPath);
        PlistElementDict rootDict = plist.root;

        // 查找英语描述或使用第一个描述作为默认
        string defaultDescription = settings.languageDescriptions[0].trackingDescription;
        foreach (var desc in settings.languageDescriptions)
        {
            if (desc.languageCode == "en")
            {
                defaultDescription = desc.trackingDescription;
                break;
            }
        }

        rootDict.SetString("NSUserTrackingUsageDescription", defaultDescription);
        plist.WriteToFile(plistPath);

        // 为每种语言创建本地化文件
        foreach (var langDesc in settings.languageDescriptions)
        {
            if (langDesc.languageCode == "en") continue;

            string lprojPath = Path.Combine(pathToBuiltProject, $"{langDesc.languageCode}.lproj");
            if (!Directory.Exists(lprojPath))
            {
                Directory.CreateDirectory(lprojPath);
            }

            string stringsPath = Path.Combine(lprojPath, "InfoPlist.strings");

            using (StreamWriter writer = new StreamWriter(stringsPath, false, System.Text.Encoding.UTF8))
            {
                writer.WriteLine($"\"NSUserTrackingUsageDescription\" = \"{langDesc.trackingDescription}\";");
            }
        }

        // 更新Xcode项目
        UpdateXcodeProject(pathToBuiltProject, settings);

        UnityEngine.Debug.Log("多语言隐私描述已成功添加到Xcode项目。");
    }

    private static void UpdateXcodeProject(string pathToBuiltProject, IOSLocalizationSettings settings)
    {
        string pbxProjectPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
        PBXProject pbxProject = new PBXProject();
        pbxProject.ReadFromFile(pbxProjectPath);

        string targetGuid = pbxProject.GetUnityMainTargetGuid();

        foreach (var langDesc in settings.languageDescriptions)
        {
            if (langDesc.languageCode == "en") continue;

            string lprojPath = $"{langDesc.languageCode}.lproj";
            string stringsPath = Path.Combine(lprojPath, "InfoPlist.strings");

            string fileGuid = pbxProject.AddFile(stringsPath, stringsPath, PBXSourceTree.Source);
            pbxProject.AddFileToBuild(targetGuid, fileGuid);
        }

        pbxProject.WriteToFile(pbxProjectPath);
    }
}

// 创建配置文件的编辑器菜单
public class LocalizationSettingsCreator
{
    [MenuItem("Tools/IOS Localization Settings")]
    public static void CreateLocalizationSettings()
    {
        IOSLocalizationSettings asset = ScriptableObject.CreateInstance<IOSLocalizationSettings>();

        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (string.IsNullOrEmpty(path))
        {
            path = "Assets";
        }
        else if (!string.IsNullOrEmpty(Path.GetExtension(path)))
        {
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
        }

        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/LocalizationSettings.asset");

        AssetDatabase.CreateAsset(asset, assetPathAndName);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow();
        Selection.activeObject = asset;
    }
}
#endif