#if UNITY_ANDROID
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using UnityEditor;
using UnityEditor.Android;
using UnityEngine;

public class BuildPostProcessorVoSdk : IPostGenerateGradleAndroidProject
{
    public int callbackOrder => 0;

    public void OnPostGenerateGradleAndroidProject(string path)
    {
        Debug.Log("AndroidBuildPostProcessor running after gradle project generation");

        // 添加AndroidManifest权限
        AddManifestPermissions(path);

    }

    private void AddManifestPermissions(string gradleProjectPath)
    {
        string manifestPath = Path.Combine(gradleProjectPath, "src/main/AndroidManifest.xml");
        if (!File.Exists(manifestPath))
        {
            Debug.LogError("AndroidManifest.xml not found at: " + manifestPath);
            return;
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(manifestPath);

        // 更可靠的方式查找 manifest 节点
        XmlNode manifestNode = doc.SelectSingleNode("//manifest");
        if (manifestNode == null)
        {
            Debug.LogError("No manifest node found in AndroidManifest.xml");
            Debug.Log("Trying to parse document element as manifest...");
            manifestNode = doc.DocumentElement;
            if (manifestNode == null || manifestNode.Name != "manifest")
            {
                Debug.LogError("Failed to find manifest node, document element is: " +
                              (manifestNode?.Name ?? "null"));
                return;
            }
        }

        // 要添加的权限列表
        string[] permissions = new string[]
        {
            "android.permission.INTERNET",
            "android.permission.ACCESS_NETWORK_STATE",
            "android.permission.ACCESS_WIFI_STATE",
            "android.permission.WAKE_LOCK",
            //"android.permission.WRITE_EXTERNAL_STORAGE",
            //"android.permission.READ_PHONE_STATE",
        };

        // 添加权限
        foreach (var permission in permissions)
        {
            if (!PermissionExists(doc, permission))
            {
                XmlElement element = doc.CreateElement("uses-permission");
                element.SetAttribute("name", "http://schemas.android.com/apk/res/android", permission);
                manifestNode.AppendChild(element);
                Debug.Log("Added permission: " + permission);
            }
        }

        // 添加queries
        AddQueriesIfNeeded(doc, manifestNode);

        // 保存修改
        doc.Save(manifestPath);
        Debug.Log("Successfully updated AndroidManifest.xml");
    }

    private bool PermissionExists(XmlDocument doc, string permissionName)
    {
        XmlNodeList nodes = doc.GetElementsByTagName("uses-permission");
        foreach (XmlNode node in nodes)
        {
            var nameAttr = node.Attributes?["android:name"];
            if (nameAttr != null && nameAttr.Value == permissionName)
                return true;
        }
        return false;
    }

    private void AddQueriesIfNeeded(XmlDocument doc, XmlNode manifestNode)
    {
        // 检查是否已存在queries节点
        XmlNode queriesNode = doc.SelectSingleNode("//queries");
        if (queriesNode != null) return;

        // 创建queries节点
        queriesNode = doc.CreateElement("queries");

        // 添加package节点
        string[] packages = { "com.android.vending", "com.google.android.gms" };
        foreach (var package in packages)
        {
            XmlElement packageElement = doc.CreateElement("package");
            packageElement.SetAttribute("name", "http://schemas.android.com/apk/res/android", package);
            queriesNode.AppendChild(packageElement);
        }

        // 将queries节点添加到manifest中(application节点之前)
        XmlNode applicationNode = doc.SelectSingleNode("//application");
        if (applicationNode != null)
        {
            manifestNode.InsertBefore(queriesNode, applicationNode);
        }
        else
        {
            manifestNode.AppendChild(queriesNode);
        }
        Debug.Log("Added queries section to AndroidManifest.xml");
    }


}
#endif