using UnityEngine;
using EventsAppQuest.Application.Services;
using EventsAppQuest.Core;

namespace EventsAppQuest.Presentation
{
    /// <summary>
    /// Base de runtime XR para a cena Quest: avalia e expõe o estado do runtime (modo, XR activo, fallback).
    /// Coloque num GameObject na cena QuestPresentation; executa cedo para que o controlador e o rig usem o modo correcto.
    /// Não inicializa MR, passthrough nem input real; apenas prepara o terreno para XR real.
    /// </summary>
    public class QuestXRRuntimeBootstrap : MonoBehaviour
    {
        private static QuestXRRuntimeStatus _cachedStatus;

        /// <summary>Estado do runtime XR (cache após primeiro GetStatus).</summary>
        public static QuestXRRuntimeStatus CachedStatus => _cachedStatus;

        private void Awake()
        {
            QuestXRLoaderInitializer.TryInitializeXR();
            RefreshStatus();
        }

        /// <summary>Força nova avaliação do estado (útil se o subsistema XR arrancar mais tarde).</summary>
        public static void RefreshStatus()
        {
            var registry = ServiceRegistry.Instance;
            var service = registry?.Get<IQuestXRRuntimeStatusService>();
            _cachedStatus = service?.GetStatus() ?? new QuestXRRuntimeStatus
            {
                RuntimeMode = QuestPresentationRuntimeMode.EditorFallback,
                IsXRActive = false,
                IsFallbackActive = true,
                XRInitMessage = "Sem serviço XR"
            };

#if UNITY_ANDROID || UNITY_EDITOR
            try
            {
                var deviceActive = UnityEngine.XR.XRSettings.isDeviceActive;
                var loadedName = UnityEngine.XR.XRSettings.loadedDeviceName;
                Debug.Log($"[QuestXRRuntimeBootstrap] RuntimeMode={_cachedStatus.RuntimeMode} IsXRActive={_cachedStatus.IsXRActive} IsFallbackActive={_cachedStatus.IsFallbackActive} Init='{_cachedStatus.XRInitMessage}' XR.isDeviceActive={deviceActive} XR.loadedDeviceName='{loadedName}'");
            }
            catch
            {
                Debug.Log($"[QuestXRRuntimeBootstrap] RuntimeMode={_cachedStatus.RuntimeMode} IsXRActive={_cachedStatus.IsXRActive} IsFallbackActive={_cachedStatus.IsFallbackActive} Init='{_cachedStatus.XRInitMessage}' (XRSettings unavailable)");
            }
#endif
        }
    }
}
