using System;
using System.Linq;
using System.Reflection;
using UnityEngine;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Inicializa XR loader no runtime via reflexão (para evitar dependência direta
    /// de XR Management no compile).
    ///
    /// Objetivo: garantir que, em Android/Quest com OpenXR instalado,
    /// o device/pose e input tenham шанс de ficar ativos sem depender de config manual.
    /// </summary>
    internal static class QuestXRLoaderInitializer
    {
        public static void TryInitializeXR()
        {
            bool foundXRManagementTypes = false;
            bool initAttempted = false;
            bool initSucceeded = false;

            try
            {
                // Garante habilitação de XR no Unity runtime (quando suportado).
                XRSettings.enabled = true;
            }
            catch
            {
                // ignore
            }

            try
            {
                // Procura tipos do XR Management em qualquer assembly carregada.
                // Ex.: UnityEngine.XR.Management.XRGeneralSettings
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                var targetType = assemblies
                    .SelectMany(a => SafeGetTypes(a))
                    .FirstOrDefault(t => t != null && t.FullName == "UnityEngine.XR.Management.XRGeneralSettings");

                if (targetType == null) return;
                foundXRManagementTypes = true;

                var instanceProp = targetType.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static);
                var instance = instanceProp?.GetValue(null);
                if (instance == null) return;

                var managerProp = targetType.GetProperty("Manager", BindingFlags.Public | BindingFlags.Instance);
                var manager = managerProp?.GetValue(instance);
                if (manager == null) return;

                // InitializeLoaderSync / InitializeLoader
                var initSync = manager.GetType().GetMethod("InitializeLoaderSync", BindingFlags.Public | BindingFlags.Instance);
                if (initSync != null)
                {
                    initAttempted = true;
                    initSync.Invoke(manager, null);
                    initSucceeded = true;
                }
                else
                {
                    var init = manager.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
                        .FirstOrDefault(m => m.Name == "InitializeLoader" && m.GetParameters().Length == 0);
                    if (init != null)
                    {
                        initAttempted = true;
                        init.Invoke(manager, null);
                        initSucceeded = true;
                    }
                }

                // StartSubsystems
                var startSubsystems = manager.GetType().GetMethod("StartSubsystems", BindingFlags.Public | BindingFlags.Instance);
                if (startSubsystems != null)
                {
                    initAttempted = true;
                    startSubsystems.Invoke(manager, null);
                }
            }
            catch
            {
                // ignore: a aplicação deve continuar em fallback se XR loader não estiver pronto.
            }

            Debug.Log($"[QuestXRLoaderInitializer] foundXRManagementTypes={foundXRManagementTypes} initAttempted={initAttempted} initSucceeded={initSucceeded}");
        }

        private static Type[] SafeGetTypes(Assembly a)
        {
            try { return a.GetTypes(); }
            catch { return Array.Empty<Type>(); }
        }
    }
}

