#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Android;
using System.IO;
using UnityEngine;
using System;
using System.Xml;

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

    public void OnPostGenerateGradleAndroidProject(string buildPath)
    {
        // 1. Get the path to the Unity-generated CMakeLists.txt in the build folder
        // path parameter is: PROJECT_ROOT/Library/Bee/Android/Prj/Mono2x/Gradle/unityLibrary
        string targetCmakeFile = Path.Combine(buildPath, "src/main/cpp/CMakeLists.txt");

        if (!File.Exists(targetCmakeFile)) return;

        // 2. Locate your custom C++ folder in Assets
        // Application.dataPath gives the absolute path to "Assets"
        string myCppFolder = Path.GetFullPath(Path.Combine(Application.dataPath, "../Packages/com.omarator.mosissdk/Plugins/Android/cpp"));
        
        // 3. Calculate the relative path from the build's CMake location to your source
        // We need the directory where the target CMake file lives to calculate relative from it
        string targetCmakeDir = Path.GetDirectoryName(targetCmakeFile);
        string relativePathToMyCpp = GetRelativePath(targetCmakeDir, myCppFolder).Replace("\\", "/");

        // 4. Prepare the command
        string commandName = "my_plugin_build";
        string unityRoot = EditorApplication.applicationContentsPath;
        string lineToAdd = $"\nset(UNITY_ROOT \"{unityRoot}\")\nadd_subdirectory(\"{relativePathToMyCpp}\" \"{commandName}\")\n";

        // 5. Prevent multiple additions
        string currentContent = File.ReadAllText(targetCmakeFile);
        if (!currentContent.Contains(relativePathToMyCpp))
        {
            File.AppendAllText(targetCmakeFile, lineToAdd);
            Debug.Log($"[CMake] Added {relativePathToMyCpp} to build.");
        }
        ModifyManifest(buildPath);
    }

    // Helper for cross-platform relative paths
    private string GetRelativePath(string fromPath, string toPath)
    {
        Uri fromUri = new Uri(AppendSlash(fromPath));
        Uri toUri = new Uri(AppendSlash(toPath));
        Uri relativeUri = fromUri.MakeRelativeUri(toUri);
        return Uri.UnescapeDataString(relativeUri.ToString());
    }

    private string AppendSlash(string path)
    {
        if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            path += Path.DirectorySeparatorChar;
        return path;
    }

    public void ModifyManifest(string path)
    {
        // The manifest is located in the unityLibrary module
        string manifestPath = Path.Combine(path, "src/main/AndroidManifest.xml");
        
        XmlDocument doc = new XmlDocument();
        doc.Load(manifestPath);

        XmlNode root = doc.DocumentElement;
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("android", "http://schemas.android.com/apk/res/android");

        // 1. Check/Add Queries tag
        XmlNode queriesNode = root.SelectSingleNode("queries");
        if (queriesNode == null)
        {
            queriesNode = doc.CreateElement("queries");
            root.AppendChild(queriesNode);
        }

        // 2. Add the specific package if it's not there
        string targetPackage = "com.omixlab.mosis";
        if (queriesNode.SelectSingleNode($"package[@android:name='{targetPackage}']", nsmgr) == null)
        {
            XmlElement packageElem = doc.CreateElement("package");
            packageElem.SetAttribute("name", "http://schemas.android.com/apk/res/android", targetPackage);
            queriesNode.AppendChild(packageElem);
        }

        doc.Save(manifestPath);
        Debug.Log("[Manifest] Successfully injected <queries> tag.");
    }    
}
#endif
