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

public static class IOSPostBuildProcessor
{
    // 全局配置变量
    private static readonly string BUNDLE_IDENTIFIER = "com.hoolai.saintseiya";
    private static readonly string ACCESS_SDK_SCHEME_SUFFIX = "223333";
    private static readonly string TRACKING_USAGE_DESCRIPTION = "想访问您的设备标识符（IDFA）用于广告追踪";
    private static readonly string PHOTO_LIBRARY_USAGE_DESCRIPTION = "将要保存截图到相册";
    private static readonly string PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION = "将要访问您的相册";

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

        Debug.Log("🚀 [IOSPostBuildProcessor] 开始自动配置 iOS 工程...");

        string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
        PBXProject proj = new PBXProject();
        proj.ReadFromFile(projPath);

#if UNITY_2019_3_OR_NEWER
        string mainTarget = proj.GetUnityMainTargetGuid();
        string frameworkTarget = proj.GetUnityFrameworkTargetGuid();
#else
        string mainTarget = proj.TargetGuidByName("Unity-iPhone");
        string frameworkTarget = mainTarget;
#endif

        // ✅ 设置 Bundle ID
        SetBundleIdentifier(proj, mainTarget, BUNDLE_IDENTIFIER);

        // ✅ 添加系统 Framework
        string[] frameworks = {
            "StoreKit.framework", "WebKit.framework", "Network.framework",
            "SystemConfiguration.framework", "AppTrackingTransparency.framework",
            "AdSupport.framework", "CoreTelephony.framework", "iAd.framework", "AdServices.framework"
        };
        foreach (var fw in frameworks)
            proj.AddFrameworkToProject(frameworkTarget, fw, false);

        // ✅ 添加 .tbd 库
        string[] tbds = { "libz.tbd", "libc++.tbd", "libresolv.tbd" };
        foreach (var tbd in tbds)
            proj.AddFrameworkToProject(frameworkTarget, tbd, false);

        // ✅ 链接参数
        proj.AddBuildProperty(frameworkTarget, "OTHER_LDFLAGS", "-ObjC");

        // ✅ 修改 Info.plist
        UpdatePlist(pathToBuiltProject);

        // ✅ 替换 Unity 生成文件
        ReplaceUnityGeneratedFiles(pathToBuiltProject);

        // ✅ 修正引用路径
        FixFileReference(proj, frameworkTarget, pathToBuiltProject);

        // ✅ 保存工程
        proj.WriteToFile(projPath);

        Debug.Log("🎉 [IOSPostBuildProcessor] 自动化配置完成！");
    }

    private static void SetBundleIdentifier(PBXProject proj, string targetGuid, string bundleId)
    {
        if (string.IsNullOrEmpty(bundleId)){
            Debug.LogWarning("⚠️ 未设置 Bundle Identifier，保持默认值");
            return;
        }
        proj.SetBuildProperty(targetGuid, "PRODUCT_BUNDLE_IDENTIFIER", bundleId);
        Debug.Log($"📦 Bundle Identifier 已设置为：{bundleId}");
    }

    private static void UpdatePlist(string pathToBuiltProject)
    {
        string plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
        if (!File.Exists(plistPath)){
            Debug.LogWarning("⚠️ 未找到 Info.plist，跳过修改");
            return;
        }

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

        string gameName = PlayerSettings.productName;
        root.SetString("NSUserTrackingUsageDescription", $"{gameName} {TRACKING_USAGE_DESCRIPTION}");
        root.SetString("NSPhotoLibraryUsageDescription", $"{gameName} {PHOTO_LIBRARY_USAGE_DESCRIPTION}");
        root.SetString("NSPhotoLibraryAddUsageDescription", $"{gameName} {PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION}");
        root.SetBoolean("NSAppTransportSecurity:NSAllowsArbitraryLoads", true);

        // ✅ 添加 URL Types
        PlistElementArray urlTypes;
        if (root.values.ContainsKey("CFBundleURLTypes"))
            urlTypes = root["CFBundleURLTypes"].AsArray();
        else
            urlTypes = root.CreateArray("CFBundleURLTypes");

        PlistElementDict newUrlType = urlTypes.AddDict();
        newUrlType.SetString("CFBundleTypeRole", "Editor");
        PlistElementArray urlSchemes = newUrlType.CreateArray("CFBundleURLSchemes");
        urlSchemes.AddString("accesssdk" + ACCESS_SDK_SCHEME_SUFFIX);

        plist.WriteToFile(plistPath);
        Debug.Log("📄 Info.plist 已更新");
    }

    private static void ReplaceUnityGeneratedFiles(string pathToBuiltProject)
    {
        Debug.Log("🛠 开始替换 Unity 导出文件...");

        string srcDir = "Assets/Plugins/iOS";
        string classesDir = Path.Combine(pathToBuiltProject, "Classes");
        string librariesDir = Path.Combine(pathToBuiltProject, "Libraries");

        string[] filesToReplace =
        {
            "UnityAppController.h",
            "UnityAppController.mm"
        };

        foreach (var file in filesToReplace){
            string srcPath = Path.Combine(srcDir, file);
            if (!File.Exists(srcPath)){
                Debug.LogWarning($"⚠️ 未找到源文件：{srcPath}");
                continue;
            }

            // 删除旧文件
            TryDelete(Path.Combine(classesDir, file));
            TryDelete(Path.Combine(librariesDir, file));

            // 拷贝新文件到 Classes
            Directory.CreateDirectory(classesDir);
            string dstPath = Path.Combine(classesDir, file);
            File.Copy(srcPath, dstPath, true);
            Debug.Log($"✅ 已替换文件：{file}");
        }

        Debug.Log("🔁 文件替换完成");
    }

    private static void TryDelete(string filePath)
    {
        if (File.Exists(filePath)){
            File.Delete(filePath);
            Debug.Log($"🗑️ 已删除旧文件：{filePath}");
        }
    }

    /// <summary>
    /// 修复 PBX 工程文件中对 UnityAppController 的错误引用
    /// </summary>
    private static void FixFileReference(PBXProject proj, string targetGuid, string pathToBuiltProject)
    {
        string newPathH = "Classes/UnityAppController.h";
        string newPathMM = "Classes/UnityAppController.mm";

        // 删除旧的 .h 文件引用
        var oldPathH = "Libraries/Plugins/Ios/UnityAppController.h";
        var oldGUID_H = proj.FindFileGuidByProjectPath(oldPathH);
        if (!string.IsNullOrEmpty(oldGUID_H)){
            proj.RemoveFileFromBuild(targetGuid, oldGUID_H);
            proj.RemoveFile(oldGUID_H);
            Debug.Log("🧹 已清除旧的 UnityAppController.h 引用");
        }

        // 删除旧的 .mm 文件引用
        var oldPathMM = "Libraries/Plugins/Ios/UnityAppController.mm";
        var oldGUID_MM = proj.FindFileGuidByProjectPath(oldPathMM);
        if (!string.IsNullOrEmpty(oldGUID_MM)){
            proj.RemoveFileFromBuild(targetGuid, oldGUID_MM);
            proj.RemoveFile(oldGUID_MM);
            Debug.Log("🧹 已清除旧的 UnityAppController.mm 引用");
        }

        // 添加新的引用
        proj.AddFileToBuild(targetGuid, proj.AddFile(newPathH, newPathH));
        proj.AddFileToBuild(targetGuid, proj.AddFile(newPathMM, newPathMM));
        Debug.Log("✅ 已添加新的 UnityAppController 引用");
    }
}
#endif