#if UNITY_ANDROID && UNITY_EDITOR
using System.IO;
using System.Xml;
using SGModule.Common;
using SGModule.Common.Helper;
using UnityEditor.Android;
using UnityEngine;

namespace SwhiteGames.Editor {
    public class HardwareAccelerationManager : IPostGenerateGradleAndroidProject {
        public int callbackOrder => 99;

        private static bool EnableHardwareAcceleration => ConfigManager.GameConfig.hardwareAcceleration;

        public void OnPostGenerateGradleAndroidProject(string basePath) {
            var manifestPath = GetManifestPath(basePath);
            if (!File.Exists(manifestPath)) {
                Log.Warning("HardwareAcceleration", $"Manifest not found at {manifestPath}");
                return;
            }

            var manifest = new AndroidManifestHelper(manifestPath);

            var changed = manifest.SetHardwareAccelerated(EnableHardwareAcceleration);

            if (changed) {
                manifest.Save();
                Log.Info("HardwareAcceleration", $"Updated manifest with hardwareAccelerated={EnableHardwareAcceleration}");
            }
        }

        private string GetManifestPath(string basePath) {
            return Path.Combine(basePath, "src/main/AndroidManifest.xml");
        }
    }

    internal class AndroidManifestHelper {
        private readonly XmlDocument _doc;
        private readonly XmlNamespaceManager _nsMgr;
        private const string AndroidNs = "http://schemas.android.com/apk/res/android";
        private readonly string _manifestPath;

        public AndroidManifestHelper(string path) {
            _manifestPath = path;
            _doc = new XmlDocument();
            _doc.Load(path);

            _nsMgr = new XmlNamespaceManager(_doc.NameTable);
            _nsMgr.AddNamespace("android", AndroidNs);
        }

        public bool SetHardwareAccelerated(bool enabled) {
            var activity = GetMainActivity();
            if (activity == null) {
                Debug.LogWarning("[HardwareAcceleration] Could not find main activity");
                return false;
            }

            return SetHardwareAccelerated(activity, enabled);
        }

        private bool SetHardwareAccelerated(XmlNode activity, bool enabled) {
            var value = enabled ? "true" : "false";
            var attr = (activity as XmlElement)?.GetAttributeNode("hardwareAccelerated", AndroidNs);

            if (attr == null) {
                attr = _doc.CreateAttribute("android", "hardwareAccelerated", AndroidNs);
                activity.Attributes?.Append(attr);
                attr.Value = value;
                return true;
            }

            if (attr.Value != value) {
                attr.Value = value;
                return true;
            }

            return false;
        }

        private XmlNode GetMainActivity() {
            return _doc.SelectSingleNode(
                "/manifest/application/activity[intent-filter/action/@android:name='android.intent.action.MAIN' and " +
                "intent-filter/category/@android:name='android.intent.category.LAUNCHER']",
                _nsMgr);
        }

        public void Save() {
            _doc.Save(_manifestPath);
        }
    }
}

#endif
