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


namespace SuperAwesome.Unity.PostProcess
{
    /// <summary>
    /// Configures iOS build settings (disables Bitcode, enables Clang modules).
    /// The SuperAwesome SPM dependency is handled by EDM4U via SuperAwesomeDependencies.xml.
    /// NOTE: this deliberately never writes GADApplicationIdentifier into Info.plist —
    /// the AdMob App ID is the publisher's responsibility (set it in your own Info.plist
    /// from https://apps.admob.com). Injecting one here would overwrite the publisher's
    /// value and break AdMob / UMP consent, so the SDK must never touch it.
    /// </summary>
    public static class DisableBitcode
    {
        [PostProcessBuildAttribute(999)]
        public static void OnPostProcessBuild(BuildTarget buildTarget, string pathToBuildProject)
        {
#if UNITY_IOS
            if (buildTarget != BuildTarget.iOS) return;
            string projectPath = pathToBuildProject + "/Unity-iPhone.xcodeproj/project.pbxproj";
            PBXProject pbxProject = new PBXProject();
            pbxProject.ReadFromFile(projectPath);

            //Disabling Bitcode on all targets
            //Main
            string target = pbxProject.GetUnityMainTargetGuid();
            pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");
            //Unity Tests
            target = pbxProject.TargetGuidByName(PBXProject.GetUnityTestTargetName());
            pbxProject.SetBuildProperty(target, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(target, "CLANG_ENABLE_MODULES", "YES");
            //Unity Framework
            string frameworkTarget = pbxProject.GetUnityFrameworkTargetGuid();
            pbxProject.SetBuildProperty(frameworkTarget, "ENABLE_BITCODE", "NO");
            pbxProject.SetBuildProperty(frameworkTarget, "CLANG_ENABLE_MODULES", "YES");

            pbxProject.WriteToFile(projectPath);

            // NOTE: We deliberately do NOT set GADApplicationIdentifier in Info.plist.
            // The AdMob App ID belongs to the publisher — injecting one here (even a
            // placeholder, and even when none is present) overwrites the publisher's own
            // value and breaks AdMob initialisation / UMP consent. Publishers must add
            // their own App ID from https://apps.admob.com to their Info.plist.
#endif
        }
    }
}
