using System;
#if UNITY_IOS && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif

namespace Combo
{
    /// <summary>
    /// iOS 平台运行时信息。提供越狱检测与构建类型识别。
    /// 所有属性在非 iOS 平台始终返回默认值（<c>false</c> / <c>null</c>）。
    /// </summary>
    public static class IOSRuntime
    {
        private static readonly Lazy<bool> IsJailBrokenCache =
            new Lazy<bool>(LoadIsJailBroken, isThreadSafe: true);

        private static readonly Lazy<string> BuildTypeCache =
            new Lazy<string>(LoadBuildType, isThreadSafe: true);

        /// <summary>
        /// 当前设备是否已越狱。非 iOS 平台始终返回 <c>false</c>。
        /// </summary>
        public static bool IsJailBroken => IsJailBrokenCache.Value;

        /// <summary>
        /// 当前 App 的构建类型。非 iOS 平台始终返回 <c>null</c>。
        /// </summary>
        /// <remarks>
        /// 可能的取值
        /// <list type="bullet">
        /// <item><c>Simulator</c> — 模拟器运行环境。</item>
        /// <item><c>Development</c> — 开发包。。</item>
        /// <item><c>TestFlight</c> — TestFlight 包。</item>
        /// <item><c>AppStore</c> — App Store 正式包。</item>
        /// <item><c>AdHoc</c> — Ad Hoc 包。</item>
        /// <item><c>Enterprise</c> — 企业签 In-House 包。</item>
        /// <item><c>Unknown</c> — 无法识别包体构建方式。</item>
        /// </list>
        /// </remarks>
        public static string BuildType => BuildTypeCache.Value;

#if UNITY_IOS && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern IntPtr IOSRuntime_GetBuildType();

        [DllImport("__Internal")]
        private static extern int IOSRuntime_IsJailBroken();

        [DllImport("__Internal")]
        private static extern void IOSRuntime_Free(IntPtr ptr);
#endif

        private static bool LoadIsJailBroken()
        {
#if UNITY_IOS && !UNITY_EDITOR
            return IOSRuntime_IsJailBroken() != 0;
#else
            return false;
#endif
        }

        private static string LoadBuildType()
        {
#if UNITY_IOS && !UNITY_EDITOR
            IntPtr ptr = IOSRuntime_GetBuildType();
            if (ptr == IntPtr.Zero)
                return null;

            try
            {
                return Marshal.PtrToStringAnsi(ptr);
            }
            finally
            {
                IOSRuntime_Free(ptr);
            }
#else
            return null;
#endif
        }
    }
}
