using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

public static class iOSAdKitPostBuildProcessor
{
    [PostProcessBuildAttribute(45)]
    public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath)
    {
        setDaroKey(buildTarget, buildPath);

        // 프로젝트의 타겟들 
        string mainTarget = "main";
        string unityFrameworkTarget = "unityframework";

        if (buildTarget == BuildTarget.iOS)
        {
#if UNITY_IOS
            System.Diagnostics.Debugger.Break();

            // We need to tell the Unity build to look at the write build file path and specifically reference the exposed Swift header file for it to work 
            var projectPath = buildPath + "/Unity-iPhone.xcodeproj/project.pbxproj";
            var project = new PBXProject();
            project.ReadFromFile(projectPath);
#if UNITY_2019_3_OR_NEWER
            var targets = new Dictionary<string, string>(){
                                                    {mainTarget, project.GetUnityMainTargetGuid()}, // 메인 타겟
                                                    {unityFrameworkTarget, project.GetUnityFrameworkTargetGuid()} // 유니티 프레임워크 타겟
                                                    }; 
#else
            var targetName = PBXProject.GetUnityTargetName();
            var targets = new Dictionary<string, string>(){
                                                    {mainTarget, project.TargetGuidByName(targetName)} // 메인 타겟
                                                     };  
#endif

            // We specifically reference the generated Swift to Objective-C header 
            //linker flag setting
            foreach (string target in targets.Values) {
                project.AddBuildProperty(target, "OTHER_CFLAGS", "-Wextern-initializer -Wunguarded-availability-new -Wmissing-declarations");
                project.AddBuildProperty(target, "OTHER_LDFLAGS", "-ObjC -lz -fobjc-arc");

                project.SetBuildProperty(target, "ENABLE_BITCODE","NO");

                project.SetBuildProperty(target, "SWIFT_VERSION", "5");

                project.SetBuildProperty(target, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "NO");
                project.SetBuildProperty(target, "LD_RUNPATH_SEARCH_PATHS", "$(inherited) @executable_path/Frameworks");
            }

            // main target에만 해당 옵션 추가
            project.SetBuildProperty(targets[mainTarget], "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");

            project.WriteToFile(projectPath);

            // We now set up a plist
            string plistPath = buildPath + "/Info.plist";
            PlistDocument plist = new PlistDocument(); 
            plist.ReadFromFile(plistPath);
            PlistElementDict rootDict = plist.root;

            // Set the IDFA request description
            //string trackingDescription = "Your data will be used to provide you a better and personalized ad experience.";
            // rootDict.SetString("NSUserTrackingUsageDescription", trackingDescription);

            // Set GADApplicationIdentifier (Please contact Daro for your own ADMOB APPID)
            rootDict.SetString("GADApplicationIdentifier", "ca-app-pub-8005039264598613~3257129747");

            // Set DaroAppKey (Please contact DARO for your own Daro App Key)
            rootDict.SetString("DaroAppKey", "dc6abd0b-3550-4380-8fa3-6601065cc5a3");

            // Set GADNativeAdValidatorEnabled (nativeAd Validator showing)
            rootDict.SetBoolean("GADNativeAdValidatorEnabled", false);

            // Set SKAdNetwork (2.1.3 - 2025/01/21)
            var skAdNetworkArray = rootDict.CreateArray("SKAdNetworkItems");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "cstr6suwn9.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "4fzdc2evr5.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "4pfyvq9l8r.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "2fnua5tdw4.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "ydx93a7ass.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "5a6flpkh64.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "p78axxw29g.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "v72qych5uu.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "ludvb6z3bs.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "cp8zw746q7.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "3sh42y64q3.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "c6k4g5qg8m.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "s39g8k73mm.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "3qy4746246.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "f38h382jlk.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "hs6bdukanm.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "v4nxqhlyqp.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "wzmmz9fp6w.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "yclnxrl5pm.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "t38b2kh725.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "7ug5zh24hu.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "gta9lk7p23.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "vutu7akeur.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "y5ghdn5j9k.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "n6fk4nfna4.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "v9wttpbfk9.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "n38lu8286q.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "47vhws6wlr.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "kbd757ywx3.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "9t245vhmpl.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "eh6m2bh4zr.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "a2p9lx4jpn.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "22mmun2rn5.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "4468km3ulz.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "2u9pt9hc89.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "8s468mfl3y.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "klf5c3l5u5.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "ppxm28t8ap.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "ecpz2srf59.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "uw77j35x4d.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "pwa73g5rt2.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "mlmmfzh3r3.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "578prtvx9j.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "4dzt52r2t5.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "e5fvkxwrpn.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "8c4e2ghe7u.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "zq492l623r.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "3rd42ekr43.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "3qcr597p9d.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "mj797d8u6f.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "55644vm79v.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "6yxyv74ff7.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "55y65gfgn7.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "cwn433xbcr.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "nu4557a4je.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "w7jznl3r6g.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "577p5t736z.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "6rd35atwn8.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "7bxrt786m8.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "7fbxrn65az.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "dt3cjx1a9i.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "fz2k2k5tej.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "jk2fsx2rgz.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "r8lj5b58b5.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "tmhh9296z4.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "k6y4y55b64.skadnetwork");
            skAdNetworkArray.AddDict().SetString("SKAdNetworkIdentifier", "qwpu75vrh2.skadnetwork");

            plist.WriteToFile(plistPath);
#endif  // UNITY_IOS
        }
    }

    public static void setDaroKey(BuildTarget target, string pathToBuiltProject)
    {
        if (target != BuildTarget.iOS) return;

#if UNITY_IOS
        // 1. 프로젝트 파일 불러오기
        string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
        PBXProject proj = new PBXProject();
        proj.ReadFromFile(projPath);

#if UNITY_2019_3_OR_NEWER
        string targetGuid = proj.GetUnityMainTargetGuid();
#else
        string targetGuid = proj.TargetGuidByName("Unity-iPhone");
#endif
        const string DARO_APP_KEY_FILE = "ios-daro-key.txt";

        // 2. 추가할 파일 경로 지정
        string srcPath = Path.Combine(Application.dataPath, "HIVEAdKit/Plugins/iOS/" + DARO_APP_KEY_FILE);  // Unity 프로젝트 안 경로

        // 3. 파일이 없으면 그냥 무시
        if (!File.Exists(srcPath))
        {
            // ios-daro-key.txt 파일이 존재하지 않아 Xcode 프로젝트에 추가하지 않음
            return;
        }

        // 4. Resources 폴더 경로 (빌드된 Xcode 프로젝트 내부)
        string resourcesDir = Path.Combine(pathToBuiltProject, "Resources");

        // 폴더 없으면 생성
        if (!Directory.Exists(resourcesDir))
        {
            Directory.CreateDirectory(resourcesDir);
        }

        // 5. 복사할 위치
        string dstPath = Path.Combine(resourcesDir, DARO_APP_KEY_FILE);

        // 파일 복사
        File.Copy(srcPath, dstPath, true);

        // 6. Xcode 프로젝트에 리소스로 추가
        string relativePath = "Resources/" + DARO_APP_KEY_FILE;
        string fileGuid = proj.AddFile(relativePath, relativePath, PBXSourceTree.Source);
        proj.AddFileToBuild(targetGuid, fileGuid);

        // 7. 변경 사항 저장
        File.WriteAllText(projPath, proj.WriteToString());
#endif        
    }
}