#if UNITY_EDITOR
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEditor.Callbacks;

namespace Aidlab
{
    internal static class AidlabMacOSPostprocess
    {
        [PostProcessBuild(1000)]
        private static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
        {
            if (target != BuildTarget.StandaloneOSX)
                return;

            string plistPath = Path.Combine(pathToBuiltProject, "Contents", "Info.plist");
            if (!File.Exists(plistPath))
                return;

            var doc = new XmlDocument();
            doc.Load(plistPath);

            XmlNode dict = doc.SelectSingleNode("/plist/dict");
            if (dict == null)
                return;

            EnsureString(dict, "NSBluetoothAlwaysUsageDescription", "Bluetooth access is required to connect to Aidlab devices.");

            doc.Save(plistPath);
        }

        private static void EnsureString(XmlNode dict, string key, string value)
        {
            foreach (XmlNode node in dict.ChildNodes)
            {
                if (node.Name == "key" && node.InnerText == key)
                    return;
            }

            XmlElement keyNode = dict.OwnerDocument.CreateElement("key");
            keyNode.InnerText = key;
            dict.AppendChild(keyNode);

            XmlElement stringNode = dict.OwnerDocument.CreateElement("string");
            stringNode.InnerText = value;
            dict.AppendChild(stringNode);
        }
    }
}
#endif

