using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
#if UNITY_IOS || UNITY_TVOS
using UnityEditor.iOS.Xcode;
#endif

namespace Davanci.Nexus.Editor
{
    // Adds NSUserTrackingUsageDescription to the iOS Info.plist (required for ATT / IDFA).
    public static class NexusPostBuildProcessor
    {
        const string TrackingDescription =
            "We use this to measure ad performance and improve your experience.";

        // Last iOS build folder, so Davanci Doctor can verify CocoaPods resolved there.
        public const string LastIosBuildKey = "Davanci.Nexus.LastIosBuildPath";

        [PostProcessBuild(100)]
        public static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath)
        {
            if (buildTarget == BuildTarget.iOS)
                EditorPrefs.SetString(LastIosBuildKey, buildPath);
#if UNITY_IOS || UNITY_TVOS
            if (buildTarget == BuildTarget.iOS || buildTarget == BuildTarget.tvOS)
            {
                UpdateInfoPlist(buildPath);
                if (buildTarget == BuildTarget.iOS)
                    AddICloudKvsEntitlement(buildPath);
            }
#endif
        }

#if UNITY_IOS || UNITY_TVOS
        static void UpdateInfoPlist(string buildPath)
        {
            string plistPath = Path.Combine(buildPath, "Info.plist");
            if (!File.Exists(plistPath))
            {
                Debug.LogWarning($"[Nexus] Info.plist not found at {plistPath}");
                return;
            }

            var plist = new PlistDocument();
            plist.ReadFromString(File.ReadAllText(plistPath));
            var root = plist.root;

            const string key = "NSUserTrackingUsageDescription";
            if (!root.values.ContainsKey(key))
            {
                root.SetString(key, TrackingDescription);
                Debug.Log($"[Nexus] Added {key} to Info.plist");
            }

            File.WriteAllText(plistPath, plist.WriteToString());
            Debug.Log("[Nexus] Info.plist updated.");
        }

        // Adds the iCloud Key-Value Store entitlement so NexusICloudProvider can read/write
        // NSUbiquitousKeyValueStore. Only runs when Cloud Save is enabled in NexusConfig, so
        // games that don't opt in never get an iCloud capability they'd have to provision.
        // Writing the entitlements file + CODE_SIGN_ENTITLEMENTS (rather than
        // ProjectCapabilityManager) avoids that API's churn across Unity versions; Xcode's
        // automatic signing enables iCloud on the App ID when it sees this entitlement.
        static void AddICloudKvsEntitlement(string buildPath)
        {
            var cfg = NexusConfig.Load();
            if (cfg == null || !cfg.enableCloudSave) return;

            string pbxPath = PBXProject.GetPBXProjectPath(buildPath);
            var project = new PBXProject();
            project.ReadFromString(File.ReadAllText(pbxPath));
            string mainGuid = project.GetUnityMainTargetGuid();

            const string entitlementsFile = "Nexus.entitlements";
            string entitlementsPath = Path.Combine(buildPath, entitlementsFile);

            var entitlements = new PlistDocument();
            if (File.Exists(entitlementsPath))
                entitlements.ReadFromString(File.ReadAllText(entitlementsPath));

            const string kvsKey = "com.apple.developer.ubiquity-kvstore-identifier";
            if (!entitlements.root.values.ContainsKey(kvsKey))
                entitlements.root.SetString(kvsKey, "$(TeamIdentifierPrefix)$(CFBundleIdentifier)");
            File.WriteAllText(entitlementsPath, entitlements.WriteToString());

            project.AddFile(entitlementsFile, entitlementsFile);
            project.SetBuildProperty(mainGuid, "CODE_SIGN_ENTITLEMENTS", entitlementsFile);
            File.WriteAllText(pbxPath, project.WriteToString());

            Debug.Log("[Nexus] Added iCloud Key-Value Store entitlement.");
        }
#endif
    }
}
