using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
#if UNITY_IOS
using UnityEditor.iOS.Xcode;
#endif
using System.IO;
using UnityEngine;

/// <summary>
/// Post-process build to add eagle0:// URL scheme for OAuth deep links.
/// Works on macOS and iOS builds.
/// </summary>
public class DeepLinkPostProcessor : IPostprocessBuildWithReport {
    private const string UrlScheme = "eagle0";

    public int callbackOrder => 0;

    public void OnPostprocessBuild(BuildReport report) {
        var target = report.summary.platform;

        if (target == BuildTarget.StandaloneOSX) {
            AddUrlSchemeToMacOS(report.summary.outputPath);
        } else if (target == BuildTarget.iOS) {
            AddUrlSchemeToiOS(report.summary.outputPath);
        }
    }

    private void AddUrlSchemeToMacOS(string buildPath) {
        // For .app bundles, Info.plist is in Contents/
        var infoPlistPath = Path.Combine(buildPath, "Contents", "Info.plist");

        if (!File.Exists(infoPlistPath)) {
            Debug.LogWarning($"[DeepLink] Info.plist not found at {infoPlistPath}");
            return;
        }

        // Read the plist
        var plistContent = File.ReadAllText(infoPlistPath);

        // Check if URL scheme already exists
        if (plistContent.Contains($"<string>{UrlScheme}</string>")) {
            Debug.Log("[DeepLink] URL scheme already present in Info.plist");
            return;
        }

        // Find the closing </dict> tag and insert before it
        // We need to add CFBundleURLTypes array with our URL scheme
        var urlTypesEntry =
                $@"
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleURLName</key>
			<string>net.eagle0.oauth</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>{UrlScheme}</string>
			</array>
		</dict>
	</array>";

        // Find the last </dict> in the file (closing the root dict)
        var lastDictIndex = plistContent.LastIndexOf("</dict>");
        if (lastDictIndex == -1) {
            Debug.LogError("[DeepLink] Could not find </dict> in Info.plist");
            return;
        }

        // Insert before the closing </dict>
        plistContent = plistContent.Insert(lastDictIndex, urlTypesEntry + "\n");

        File.WriteAllText(infoPlistPath, plistContent);
        Debug.Log($"[DeepLink] Added {UrlScheme}:// URL scheme to macOS Info.plist");
    }

    private void AddUrlSchemeToiOS(string buildPath) {
#if UNITY_IOS
        var infoPlistPath = Path.Combine(buildPath, "Info.plist");

        if (!File.Exists(infoPlistPath)) {
            Debug.LogWarning($"[DeepLink] Info.plist not found at {infoPlistPath}");
            return;
        }

        var plist = new PlistDocument();
        plist.ReadFromFile(infoPlistPath);

        // Get or create CFBundleURLTypes array
        var urlTypes = plist.root["CFBundleURLTypes"];
        PlistElementArray urlTypesArray;

        if (urlTypes == null) {
            urlTypesArray = plist.root.CreateArray("CFBundleURLTypes");
        } else {
            urlTypesArray = urlTypes.AsArray();
        }

        // Check if our URL scheme already exists
        foreach (var element in urlTypesArray.values) {
            var dict = element.AsDict();
            var schemes = dict?["CFBundleURLSchemes"]?.AsArray();
            if (schemes != null) {
                foreach (var scheme in schemes.values) {
                    if (scheme.AsString() == UrlScheme) {
                        Debug.Log("[DeepLink] URL scheme already present in iOS Info.plist");
                        return;
                    }
                }
            }
        }

        // Add our URL type
        var newUrlType = urlTypesArray.AddDict();
        newUrlType.SetString("CFBundleURLName", "net.eagle0.oauth");
        var schemesArray = newUrlType.CreateArray("CFBundleURLSchemes");
        schemesArray.AddString(UrlScheme);

        // Set export compliance to avoid manual step in App Store Connect
        // We don't use non-exempt encryption (only standard OS-provided HTTPS)
        plist.root.SetBoolean("ITSAppUsesNonExemptEncryption", false);

        plist.WriteToFile(infoPlistPath);
        Debug.Log($"[DeepLink] Added {UrlScheme}:// URL scheme to iOS Info.plist");
        Debug.Log("[DeepLink] Set ITSAppUsesNonExemptEncryption=false for export compliance");
#else
        Debug.Log("[DeepLink] iOS support not available in this Unity installation");
#endif
    }
}
