using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;

public class AdsterPostBuild
{
    [PostProcessBuildAttribute(45)]
    public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath)
    {
        if (buildTarget != BuildTarget.iOS) return;
        UpdateInfoPlist(buildPath);
        UpdateXcodeProject(buildPath);
        ShowInstructions(buildPath);
    }

    private static void UpdateInfoPlist(string buildPath)
    {
        string plistPath = Path.Combine(buildPath, "Info.plist");
        if (!File.Exists(plistPath)) { Debug.LogError($"Adster: Info.plist not found at {plistPath}"); return; }
        var plist = new PlistDocument(); plist.ReadFromFile(plistPath);
        var root = plist.root;
        var ats = root.CreateDict("NSAppTransportSecurity");
        ats.SetBoolean("NSAllowsArbitraryLoads", true);
        root.CreateArray("SKAdNetworkItems"); // Add IDs per Adster docs
        plist.WriteToFile(plistPath);
    }

    private static void UpdateXcodeProject(string buildPath)
    {
        string pbxPath = Path.Combine(buildPath, "Unity-iPhone.xcodeproj/project.pbxproj");
        if (!File.Exists(pbxPath)) { Debug.LogError($"Adster: Xcode project not found at {pbxPath}"); return; }
        var proj = new PBXProject(); proj.ReadFromFile(pbxPath);
        string uf = proj.GetUnityFrameworkTargetGuid();
        string mt = proj.GetUnityMainTargetGuid();
        proj.AddBuildProperty(uf, "SWIFT_VERSION", "5.0");
        proj.AddBuildProperty(uf, "CLANG_ENABLE_MODULES", "YES");
        proj.AddBuildProperty(uf, "DEFINES_MODULE", "YES");
        proj.AddBuildProperty(mt, "SWIFT_VERSION", "5.0");
        proj.AddBuildProperty(mt, "CLANG_ENABLE_MODULES", "YES");
        proj.AddBuildProperty(mt, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
        proj.AddBuildProperty(uf, "ENABLE_BITCODE", "NO");
        proj.AddBuildProperty(mt, "ENABLE_BITCODE", "NO");
        proj.AddBuildProperty(uf, "IPHONEOS_DEPLOYMENT_TARGET", "14.0");
        proj.AddBuildProperty(mt, "IPHONEOS_DEPLOYMENT_TARGET", "14.0");
        proj.WriteToFile(pbxPath);
        try
        {
            var text = File.ReadAllText(pbxPath);
            var pattern = "(?mi)^[^\\n]*SWIFT_OBJC_BRIDGING_HEADER\\s*=\\s*[^;]*;\\s*$\\r?\\n?";
            var stripped = System.Text.RegularExpressions.Regex.Replace(text, pattern, string.Empty);
            if (!ReferenceEquals(text, stripped)) File.WriteAllText(pbxPath, stripped);
        }
        catch { }
    }


    private static void ShowInstructions(string buildPath)
    {
        string msg = $"Adster iOS post-build complete.\n\nNext steps:\n1) cd '{buildPath}'\n2) pod install\n3) Open Unity-iPhone.xcworkspace\n4) Test on device\n\nDependencies are managed by External Dependency Manager.\nRemember to add required SKAdNetwork IDs per Adster docs.";
        Debug.Log(msg);
    }
}
