
#if UNITY_IOS

using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace tysdk.editor
{

    public class iOSPostBuildProcessor
    {

        //[MenuItem("Tools/XcodeProcessTest")]
        //public static void Test()
        //{
            //var path = Path.Join(Directory.GetCurrentDirectory(),"bin/ft_xcode_0_26_20250512133516");
            //ProcessXCodeProj(path);
        //}

        [PostProcessBuild(1000)]
        public static void ChangeXcodeSettings(BuildTarget buildTarget, string pathToBuiltProject)
        {
            if (buildTarget == BuildTarget.iOS)
            {
                UnityEngine.Debug.Log($"ChangeXcodeSettings {pathToBuiltProject}");
                ProcessXCodeProj(pathToBuiltProject);
            }
        }

        private static void ProcessXCodeProj(string pathToBuiltProject)
        {
            string pbxprojPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
            PBXProject proj = new PBXProject();
            proj.ReadFromFile(pbxprojPath);

            string target = proj.GetUnityMainTargetGuid();
            XCodeSetSigingAndCapbilities(target, proj, pathToBuiltProject);
            ProcessBuildSettings(proj);
            XcodeOverwriteFiles(pathToBuiltProject, proj);
            ProceeFirebasePlist(target, proj, pathToBuiltProject);

            UnityEngine.Debug.Log($"XCodeProj {pbxprojPath}");
            File.WriteAllText(pbxprojPath, proj.WriteToString());

            ProcessLocalization(pbxprojPath);

            ProcessPlist(pathToBuiltProject);

        }

        // const string knowRegions = "knownRegions = (\n\t\t\t\ten,\n\t\t\t\tfr,\n\t\t\t\tde,\n\t\t\t\tes,\n\t\t\t\tid,\n\t\t\t\t\"zh-Hans\",\n\t\t\t\t\"zh-Hant\", \n\t\t\t\t\"zh-Hant\", \n\t\t\t);";
    
        const string developmentRegion = "developmentRegion = en;";

        private static void ProcessLocalization(string pbxProjPath)
        {
            var raw = File.ReadAllText(pbxProjPath);
            Regex developmentRegionRegex = new Regex(@"developmentRegion\s*=\s*(\w+);");
            Regex knownRegionsRegex = new Regex(@"knownRegions\s*=\s*\(([^)]+)\);");
            raw = developmentRegionRegex.Replace(raw, developmentRegion);
            raw = knownRegionsRegex.Replace(raw, MakeRegionsStr("en", "fr", "de", "es", "id", "zh-Hans", "zh-Hant", "nl", "it", "ja", "ko", "ms", "pl", "pt", "th", "tr", "ar"));
            File.WriteAllText(pbxProjPath, raw);
        }

        private static string MakeRegionsStr(params string[] regions)
        {
            var sb = new System.Text.StringBuilder();
            foreach (var region in regions)
            {
              sb.Append($"\n\t\t\t\t{region},");
            }
            var str = sb.ToString();
            return $"knownRegions = ({str.Substring(0,str.Length-1)}\t\t\t);";
        }

        private static void XcodeOverwriteFiles(string projPath, PBXProject proj)
        {

            string mainAppPath = Path.Combine(projPath, "MainApp", "main.mm");
            string mainContent = File.ReadAllText(mainAppPath);
            string newContent = mainContent.Replace("#include <UnityFramework/UnityFramework.h>", @"#include ""../UnityFramework/UnityFramework.h""");
            File.WriteAllText(mainAppPath, newContent);

            mainAppPath = Path.Combine(projPath, "Classes", "Preprocessor.h");
            mainContent = File.ReadAllText(mainAppPath);
            newContent = mainContent.Replace("#define UNITY_USES_REMOTE_NOTIFICATIONS 0", "#define UNITY_USES_REMOTE_NOTIFICATIONS 1");
            File.WriteAllText(mainAppPath, newContent);
        }

        private static void ProceeFirebasePlist(string target, PBXProject proj, string root)
        {
            var plistPath = Path.Combine("Packages/tysdk/Files", "GoogleService-Info.plist");
            File.Copy(plistPath, $"{root}/GoogleService-Info.plist", true);
            var plistGuid = proj.AddFile("GoogleService-Info.plist", "GoogleService-Info.plist", PBXSourceTree.Source);
            proj.AddFileToBuild(target, plistGuid);
        }

        private static void XCodeSetSigingAndCapbilities(string target, PBXProject proj, string root)
        {
            var entitlementsContent = File.ReadAllText("Packages/tysdk/Files/Unity-iPhone.entitlements");
            File.WriteAllText($"{root}/Unity-iPhone/Unity-iPhone.entitlements", entitlementsContent);

            proj.AddCapability(target, PBXCapabilityType.SignInWithApple, "Unity-iPhone/Unity-iPhone.entitlements");
            proj.AddCapability(target, PBXCapabilityType.KeychainSharing, "Unity-iPhone/Unity-iPhone.entitlements");
            proj.AddCapability(target, PBXCapabilityType.PushNotifications, "Unity-iPhone/Unity-iPhone.entitlements");
            proj.AddCapability(target, PBXCapabilityType.AssociatedDomains, "Unity-iPhone/Unity-iPhone.entitlements");
        }

        private static void ProcessBuildSettings(PBXProject proj)
        {
            string target = proj.TargetGuidByName("GameAssembly");
            proj.AddBuildProperty(target, "OTHER_LDFLAGS", "-all_load");

            target = proj.TargetGuidByName("UnityFramework");
            proj.SetBuildProperty(target, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "NO");
            proj.AddBuildProperty(target, "OTHER_LDFLAGS", "-ObjC");
            proj.AddFrameworkToProject(target, "AppTrackingTransparency.framework", false);

            proj.AddFrameworkToProject(target, "StoreKit.framework", false);
            proj.AddFrameworkToProject(target, "CFNetwork.framework", false);
            proj.AddFrameworkToProject(target, "CoreTelephony.framework", false);
            proj.AddFrameworkToProject(target, "Security.framework", false);
            proj.AddFrameworkToProject(target, "SystemConfiguration.framework", false);
            proj.AddFrameworkToProject(target, "libc++.tbd", false);
            proj.AddFrameworkToProject(target, "libsqlite3.tbd", false);
            proj.AddFrameworkToProject(target, "libz.tbd", false);
            proj.AddFrameworkToProject(target, "Accelerate.framework", false);
            proj.AddFrameworkToProject(target, "AuthenticationServices.framework", false);
            proj.AddFrameworkToProject(target, "SafariServices.framework", false);
            proj.AddFrameworkToProject(target, "LocalAuthentication.framework", false);
            proj.AddFrameworkToProject(target, "CoreGraphics.framework", false);
            proj.AddFrameworkToProject(target, "WebKit.framework", false);
            //Add AdSupport Framework
            proj.AddFrameworkToProject(target, "AdSupport.framework", false);
        }

        private static void ProcessPlist(string root)
        {
            string plistPath = root + "/Info.plist";
            PlistDocument plist = new PlistDocument();
            plist.ReadFromString(File.ReadAllText(plistPath));
            PlistElementDict infoDict = plist.root;

            PlistElementArray urlTypesArray = null;
            if (!infoDict.values.ContainsKey("CFBundleURLTypes"))
            {
                urlTypesArray = infoDict.CreateArray("CFBundleURLTypes");
            }
            else
            {
                urlTypesArray = infoDict.values["CFBundleURLTypes"].AsArray();
            }

            if (!infoDict.values.ContainsKey("NSUserActivityTypes"))
            {
                PlistElementArray userActivityTypes = infoDict.CreateArray("NSUserActivityTypes");
                userActivityTypes.AddString("INSendMessageIntent");
            }
            else
            {
                PlistElementArray userActivityTypes = infoDict.values["NSUserActivityTypes"].AsArray();
                userActivityTypes.AddString("INSendMessageIntent");
            }

            PlistElementArray queriesSchemesArray = null;
            if (!infoDict.values.ContainsKey("LSApplicationQueriesSchemes"))
            {
                queriesSchemesArray = infoDict.CreateArray("LSApplicationQueriesSchemes");
            }
            else
            {
                queriesSchemesArray = infoDict.values["LSApplicationQueriesSchemes"].AsArray();
            }

            // AAT
            var trackingDescription = "Data will be used to deliver personalized content to you";
            infoDict.SetString("NSUserTrackingUsageDescription", trackingDescription);

            // Photo Library
            infoDict.SetBoolean("PHPhotoLibraryPreventAutomaticLimitedAccessAlert", true);
            var photoLibraryUsageDescription = "The app requires your consent to add photos or videos to the photo gallery so that you can manage and share them more easily. We are committed to protecting your privacy and complying with relevant laws and regulations.";
            infoDict.SetString("NSPhotoLibraryUsageDescription", photoLibraryUsageDescription);

            // UIFileSharing
            infoDict.SetBoolean("UIFileSharingEnabled", true);

            // Google
            string googleClientID = "com.googleusercontent.apps.481260393117-88n0v3ht8ashhk0r5ri47hced7o5qj62";
            CreateURLTypes(urlTypesArray.AddDict(), "google", googleClientID);

            //Facebook
            {
                string faceBookAppId = "162066986963808";
                string faceBookDisPlayname = "arkgame";
                string facebookClientToken = "5fe59b0d985ad7acb51f48081e69d45b";
                PlistElementDict facebookDic = urlTypesArray.AddDict();
                PlistElementArray fbSchmes = facebookDic.CreateArray("CFBundleURLSchemes");

                CreateURLTypes(urlTypesArray.AddDict(), "fb", $"fb{faceBookAppId}");

                infoDict.SetString("FacebookAppID", faceBookAppId);
                infoDict.SetString("FacebookDisplayName", faceBookDisPlayname);
                infoDict.SetString("FacebookClientToken", facebookClientToken);
                //白名单
                queriesSchemesArray.AddString("fb-messenger-share-api");
                queriesSchemesArray.AddString("fbauth2");
                queriesSchemesArray.AddString("fbauth");
                queriesSchemesArray.AddString("fbshareextension");
                queriesSchemesArray.AddString("fbapi");
                queriesSchemesArray.AddString("fbapi20130214");
                queriesSchemesArray.AddString("fbapi20130410");
                queriesSchemesArray.AddString("fbapi20130702");
                queriesSchemesArray.AddString("fbapi20131010");
                queriesSchemesArray.AddString("fbapi20131219");
                queriesSchemesArray.AddString("fbapi20140410");
                queriesSchemesArray.AddString("fbapi20140116");
                queriesSchemesArray.AddString("fbapi20150313");
                queriesSchemesArray.AddString("fbapi20150629");
                queriesSchemesArray.AddString("fbapi20160328");
            }
            AddSKAdNetworkIdentifier(infoDict);

            // "en", "fr", "de", "es", "id", "zh-Hans", "zh-Hant", "nl", "it", "ja", "ko", "ms", "pl", "pt", "th", "tr", "ar"
            var localization = infoDict.CreateArray("CFBundleLocalizations");
            localization.AddString("en");
            localization.AddString("fr");
            localization.AddString("de");
            localization.AddString("es");
            localization.AddString("id");
            localization.AddString("zh_CN");
            localization.AddString("zh_TW");
            localization.AddString("nl");
            localization.AddString("it");
            localization.AddString("ja");
            localization.AddString("ko");
            localization.AddString("ms");
            localization.AddString("pl");
            localization.AddString("pt");
            localization.AddString("th");
            localization.AddString("tr");
            localization.AddString("ar");

            //CoMo 
            //<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE</key> <true/>
            // <key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE</key> <true/>
            // <key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA</key> <true/>
            // <key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS</key> <true/>
            infoDict.SetBoolean("GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE", true);
            infoDict.SetBoolean("GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE", true);
            infoDict.SetBoolean("GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA", true);
            infoDict.SetBoolean("GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS", true);

            File.WriteAllText(plistPath, plist.WriteToString());

        }

        private static void AddSKAdNetworkIdentifier(PlistElementDict infoDict)
        {

            List<string> skadnetworks = new List<string>() {
                "22mmun2rn5.skadnetwork", "238da6jt44.skadnetwork", "24t9a8vw3c.skadnetwork", "24zw6aqk47.skadnetwork", "252b5q8x7y.skadnetwork", "275upjj5gd.skadnetwork",
                "294l99pt4k.skadnetwork", "2fnua5tdw4.skadnetwork", "2u9pt9hc89.skadnetwork", "32z4fx6l9h.skadnetwork", "3l6bd9hu43.skadnetwork", "3qcr597p9d.skadnetwork",
                "3qy4746246.skadnetwork", "3rd42ekr43.skadnetwork", "3sh42y64q3.skadnetwork", "424m5254lk.skadnetwork", "4468km3ulz.skadnetwork", "44jx6755aq.skadnetwork",
                "44n7hlldy6.skadnetwork", "47vhws6wlr.skadnetwork", "488r3q3dtq.skadnetwork", "4dzt52r2t5.skadnetwork", "4fzdc2evr5.skadnetwork", "4mn522wn87.skadnetwork",
                "4pfyvq9l8r.skadnetwork", "4w7y6s5ca2.skadnetwork", "523jb4fst2.skadnetwork", "52fl2v3hgk.skadnetwork", "54nzkqm89y.skadnetwork", "578prtvx9j.skadnetwork",
                "5a6flpkh64.skadnetwork", "5f5u5tfb26.skadnetwork", "5l3tpt7t6e.skadnetwork", "5lm9lj6jb7.skadnetwork", "5tjdwbrq8w.skadnetwork", "6964rsfnh4.skadnetwork",
                "6g9af3uyq4.skadnetwork", "6p4ks3rnbw.skadnetwork", "6v7lgmsu45.skadnetwork", "6xzpu9s2p8.skadnetwork", "6yxyv74ff7.skadnetwork", "737z793b9f.skadnetwork",
                "74b6s63p6l.skadnetwork", "7953jerfzd.skadnetwork", "79pbpufp6p.skadnetwork", "7fmhfwg9en.skadnetwork", "7rz58n8ntl.skadnetwork", "7ug5zh24hu.skadnetwork",
                "84993kbrcf.skadnetwork", "89z7zv988g.skadnetwork", "8c4e2ghe7u.skadnetwork", "8m87ys6875.skadnetwork", "8r8llnkz5a.skadnetwork", "8s468mfl3y.skadnetwork",
                "97r2b46745.skadnetwork", "9b89h5y424.skadnetwork", "9g2aggbj52.skadnetwork", "9nlqeag3gk.skadnetwork", "9rd848q2bz.skadnetwork", "9t245vhmpl.skadnetwork",
                "9vvzujtq5s.skadnetwork", "9yg77x724h.skadnetwork", "a2p9lx4jpn.skadnetwork", "a7xqa6mtl2.skadnetwork", "a8cz6cu7e5.skadnetwork", "av6w8kgt66.skadnetwork",
                "b9bk5wbcq9.skadnetwork", "bxvub5ada5.skadnetwork", "c3frkrj4fj.skadnetwork", "c6k4g5qg8m.skadnetwork", "cg4yq2srnc.skadnetwork", "cj5566h2ga.skadnetwork",
                "cp8zw746q7.skadnetwork", "cs644xg564.skadnetwork", "cstr6suwn9.skadnetwork", "cwn433xbcr.skadnetwork", "dbu4b84rxf.skadnetwork", "dkc879ngq3.skadnetwork",
                "dzg6xy7pwj.skadnetwork", "e5fvkxwrpn.skadnetwork", "ecpz2srf59.skadnetwork", "eh6m2bh4zr.skadnetwork", "ejvt5qm6ak.skadnetwork", "f38h382jlk.skadnetwork",
                "f73kdq92p3.skadnetwork", "f7s53z58qe.skadnetwork", "feyaarzu9v.skadnetwork", "g28c52eehv.skadnetwork", "g2y4y55b64.skadnetwork", "g6gcrrvk4p.skadnetwork",
                "ggvn48r87g.skadnetwork", "glqzh8vgby.skadnetwork", "gta8lk7p23.skadnetwork", "gta9lk7p23.skadnetwork", "h65wbv5k3f.skadnetwork", "hb56zgv37p.skadnetwork",
                "hdw39hrw9y.skadnetwork", "hs6bdukanm.skadnetwork", "k674qkevps.skadnetwork", "k6y4y55b64.skadnetwork", "kbd757ywx3.skadnetwork", "kbmxgpxpgc.skadnetwork",
                "klf5c3l5u5.skadnetwork", "krvm3zuq6h.skadnetwork", "lr83yxwka7.skadnetwork", "ludvb6z3bs.skadnetwork", "m297p6643m.skadnetwork", "m5mvw97r93.skadnetwork",
                "m8dbw4sv7c.skadnetwork", "mj797d8u6f.skadnetwork", "mlmmfzh3r3.skadnetwork", "mls7yz5dvl.skadnetwork", "mp6xlyr22a.skadnetwork", "mqn7fxpca7.skadnetwork",
                "mtkv5xtk9e.skadnetwork", "n38lu8286q.skadnetwork", "n66cz3y3bx.skadnetwork", "n6fk4nfna4.skadnetwork", "n9x2a789qt.skadnetwork", "nzq8sh4pbs.skadnetwork",
                "p78axxw29g.skadnetwork", "ppxm28t8ap.skadnetwork", "prcb7njmu6.skadnetwork", "pwa73g5rt2.skadnetwork", "pwdxu55a5a.skadnetwork", "qqp299437r.skadnetwork",
                "qu637u8glc.skadnetwork", "r45fhb6rf7.skadnetwork", "rvh3l7un93.skadnetwork", "rx5hdcabgc.skadnetwork", "s39g8k73mm.skadnetwork", "s69wq72ugq.skadnetwork",
                "su67r6k2v3.skadnetwork", "t38b2kh725.skadnetwork", "t6d3zquu66.skadnetwork", "tl55sbb4fm.skadnetwork", "tvvz7th9br.skadnetwork", "u679fj5vs4.skadnetwork",
                "uw77j35x4d.skadnetwork", "v4nxqhlyqp.skadnetwork", "v72qych5uu.skadnetwork", "v79kvwwj4g.skadnetwork", "v9wttpbfk9.skadnetwork", "vcra2ehyfk.skadnetwork",
                "vutu7akeur.skadnetwork", "w9q455wk68.skadnetwork", "wg4vff78zm.skadnetwork", "wzmmz9fp6w.skadnetwork", "x44k69ngh6.skadnetwork", "x5l83yy675.skadnetwork",
                "x8jxxk4ff5.skadnetwork", "x8uqf25wch.skadnetwork", "xga6mpmplv.skadnetwork", "xy9t38ct57.skadnetwork", "y45688jllp.skadnetwork", "y5ghdn5j9k.skadnetwork",
                "yclnxrl5pm.skadnetwork", "ydx93a7ass.skadnetwork", "z24wtl6j62.skadnetwork", "zmvfpc5aq8.skadnetwork", "zq492l623r.skadnetwork"
            };
            var items = infoDict.CreateArray("SKAdNetworkItems");
            var key = "SKAdNetworkIdentifier";
            foreach (var identifier in skadnetworks)
            {
                items.AddDict().SetString(key, identifier);
            }
        }

        private static void CreateURLTypes(PlistElementDict dict, string name, string scheme1)
        {
            dict.SetString("CFBundleTypeRole", "Editor"); dict.SetString("CFBundleURLName", name);
            dict.CreateArray("CFBundleURLSchemes"); 
            PlistElementArray schemes = dict.values["CFBundleURLSchemes"].AsArray(); 
            schemes.AddString(scheme1);
        }
    }
}
#endif
