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

namespace IndieExchange.Editor
{
#if UNITY_ANDROID
    public sealed class SecurityAndroidBuild : IPostGenerateGradleAndroidProject, IPreprocessBuildWithReport
    {
        public int callbackOrder => 10;
        public void OnPreprocessBuild(BuildReport report)
        {
            if (report.summary.platform == BuildTarget.Android && (int)PlayerSettings.Android.minSdkVersion < 23)
                PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel23;
        }
        public void OnPostGenerateGradleAndroidProject(string path)
        {
            var gradle = Path.Combine(path, "build.gradle");
            var text = File.ReadAllText(gradle);
            if (!text.Contains("com.google.android.play:integrity:1.6.0"))
                File.AppendAllText(gradle, "\ndependencies { implementation 'com.google.android.play:integrity:1.6.0' }\n");
            var proguard = Path.Combine(path, "proguard-unity.txt");
            if (!File.Exists(proguard) || !File.ReadAllText(proguard).Contains("com.indieexchange.security.IndieIntegrity"))
                File.AppendAllText(proguard, "\n-keep class com.indieexchange.security.IndieIntegrity { *; }\n");
        }
    }
#endif
    public static class SecurityIosBuild
    {
        [PostProcessBuild(10)]
        public static void OnBuilt(BuildTarget target, string path)
        {
#if UNITY_IOS
            if (target != BuildTarget.iOS) return;
            var projectPath = PBXProject.GetPBXProjectPath(path);
            var project = new PBXProject(); project.ReadFromFile(projectPath);
            project.AddFrameworkToProject(project.GetUnityFrameworkTargetGuid(), "DeviceCheck.framework", true);
            var main = project.GetUnityMainTargetGuid();
            var file = project.GetBuildPropertyForAnyConfig(main, "CODE_SIGN_ENTITLEMENTS");
            if (string.IsNullOrEmpty(file)) file = "IndieExchange.entitlements";
            if (file.Contains("$(")) throw new BuildFailedException("Indie Exchange: use a concrete CODE_SIGN_ENTITLEMENTS path so App Attest can be enabled safely.");
            var entitlements = new PlistDocument();
            var absolute = Path.Combine(path, file);
            if (File.Exists(absolute)) entitlements.ReadFromFile(absolute);
            else entitlements.Create();
            entitlements.root.SetString("com.apple.developer.devicecheck.appattest-environment", "production");
            Directory.CreateDirectory(Path.GetDirectoryName(absolute));
            entitlements.WriteToFile(absolute);
            project.SetBuildProperty(main, "CODE_SIGN_ENTITLEMENTS", file);
            project.WriteToFile(projectPath);
#endif
        }
    }
}
