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

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

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

#if UNITY_2019_3_OR_NEWER
        string unityFrameworkTarget = proj.GetUnityFrameworkTargetGuid();
#else
        string unityFrameworkTarget = proj.TargetGuidByName(PBXProject.GetUnityTargetName());
#endif
        string mainTargetGuid = proj.GetUnityMainTargetGuid();

        // ------------------------------------------------------------------
        // Remove any pre-existing references to ChottuLinkSDK.xcframework.
        // Unity 6+ auto-adds & embeds xcframeworks found under Plugins/iOS, which
        // collides with the manual embed below ("Multiple commands produce ...").
        // Stripping them first makes this script the single source of truth on
        // every Unity version (older Unity simply has nothing to remove).
        // ------------------------------------------------------------------
        RemoveExistingXCFrameworkReferences(proj, mainTargetGuid, unityFrameworkTarget);

        // ------------------------------------------------------------------
        // Ensure the xcframework (and its slices) exist inside the Xcode build
        // ------------------------------------------------------------------
        string srcXCFramework = Path.Combine(Application.dataPath, "ChottuLink/Plugins/iOS/ChottuLinkSDK.xcframework");
        string dstXCFramework = Path.Combine(pathToBuiltProject, "Frameworks/ChottuLinkSDK.xcframework");
        if (Directory.Exists(dstXCFramework))
        {
            FileUtil.DeleteFileOrDirectory(dstXCFramework);
        }
        FileUtil.CopyFileOrDirectory(srcXCFramework, dstXCFramework);
        Debug.Log($"ChottuLinkPostProcessBuild: Copied xcframework to build -> {dstXCFramework}");

        // ------------------------------------------------------------------

        // Link/embed the xcframework root so Xcode picks the correct slice (device vs simulator).
        // Pointing only at ios-arm64/ChottuLinkSDK.framework breaks simulator builds and can fail at launch.
        string frameworkFolder = "Frameworks/ChottuLinkSDK.xcframework";

        // Add to project only once
        string fileGuid = proj.AddFile(frameworkFolder, frameworkFolder, PBXSourceTree.Source);

        // Link with UnityFramework target
        proj.AddFileToBuild(unityFrameworkTarget, fileGuid);
        proj.AddBuildProperty(unityFrameworkTarget, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks");
        proj.AddBuildProperty(unityFrameworkTarget, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks @loader_path/Frameworks");
        proj.AddBuildProperty(unityFrameworkTarget, "OTHER_LDFLAGS", "-ObjC");

        // Embed & sign in MAIN APP target – this puts the framework inside SampleProject.app/Frameworks so it’s available at runtime
        proj.AddFileToEmbedFrameworks(mainTargetGuid, fileGuid);
        proj.AddBuildProperty(mainTargetGuid, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks");
        proj.AddBuildProperty(mainTargetGuid, "LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
        proj.SetBuildProperty(mainTargetGuid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
        proj.SetBuildProperty(mainTargetGuid, "ENABLE_BITCODE", "NO");

        // --- Clean up stale references ---
        string staleFile = "ChottuLinkAppController.mm";
        string staleFileGuid = proj.FindFileGuidByProjectPath("Libraries/ChottuLink/Plugins/iOS/" + staleFile);
        if (staleFileGuid != null)
        {
            proj.RemoveFileFromBuild(mainTargetGuid, staleFileGuid);
            proj.RemoveFileFromBuild(unityFrameworkTarget, staleFileGuid);
            proj.RemoveFile(staleFileGuid);
            Debug.Log($"ChottuLinkPostProcessBuild: Removed stale reference to {staleFile}.");
        }

        // Write changes
        proj.WriteToFile(projPath);
    }

    /// <summary>
    /// Removes every existing PBX reference to ChottuLinkSDK.xcframework from both the
    /// main app and UnityFramework targets (link + embed). This dedupes:
    ///   - Unity 6+'s automatic add/embed of plugins under Assets/.../Plugins/iOS
    ///   - This script's own reference from a previous "Append" build
    /// so that the manual add/embed that follows is the only one.
    /// </summary>
    private static void RemoveExistingXCFrameworkReferences(PBXProject proj, string mainTargetGuid, string unityFrameworkTarget)
    {
        // Path variants Unity uses across versions when it auto-adds the plugin,
        // plus this script's own destination path.
        string[] candidatePaths =
        {
            "Frameworks/ChottuLinkSDK.xcframework",
            "Frameworks/ChottuLink/Plugins/iOS/ChottuLinkSDK.xcframework",
            "Libraries/ChottuLink/Plugins/iOS/ChottuLinkSDK.xcframework",
        };

        foreach (string path in candidatePaths)
        {
            string guid = proj.FindFileGuidByProjectPath(path);
            if (string.IsNullOrEmpty(guid))
                guid = proj.FindFileGuidByRealPath(path);

            if (string.IsNullOrEmpty(guid))
                continue;

            proj.RemoveFileFromBuild(mainTargetGuid, guid);
            proj.RemoveFileFromBuild(unityFrameworkTarget, guid);
            proj.RemoveFile(guid);
            Debug.Log($"ChottuLinkPostProcessBuild: Removed pre-existing xcframework reference at {path}.");
        }
    }
}
#endif
