#nullable enable
using UnityEngine;
using System;
using System.Threading.Tasks;
using IGP.UnitySDK.Models;

namespace IGP.UnitySDK
{
    /// <summary>
    /// 房间管理器 - 仅负责当前宿主房间控制。
    /// 房间创建和加入由 Curio desktop 宿主统一管理，不再由 SDK 暴露。
    /// </summary>
    public class IGPRoomManager : MonoBehaviour
    {
        [Header("References")]
        [SerializeField] private IGPRuntimeManager? arenaManager;
        
        void Start()
        {
            if (this == null) return;
            if (arenaManager == null)
            {
                arenaManager = FindAnyObjectByType<IGPRuntimeManager>();
            }
            
            if (arenaManager == null)
            {
                Debug.LogError("[IGPRoomManager] IGPRuntimeManager not found!");
                enabled = false;
                return;
            }
        }

        /// <summary>
        /// 离开当前房间
        /// </summary>
        public async Task LeaveCurrentRoomAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    Debug.LogError("[IGPRoomManager] IGPRuntimeManager is null! Cannot leave room.");
                    throw new System.InvalidOperationException("IGPRuntimeManager not initialized. Make sure IGPRuntimeManager exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    Debug.LogWarning("[IGPRoomManager] Not in any room");
                    return;
                }

                Debug.Log($"[IGPRoomManager] Leaving room: {arenaManager.CurrentRoomId}");
                await arenaManager.LeaveHostedRoomAsync();

                Debug.Log("[IGPRoomManager] Left room successfully");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[IGPRoomManager] Failed to leave room: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 通知宿主结束当前对局。
        /// </summary>
        public async Task FinishCurrentGameAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    Debug.LogError("[IGPRoomManager] IGPRuntimeManager is null! Cannot finish game.");
                    throw new InvalidOperationException("IGPRuntimeManager not initialized. Make sure IGPRuntimeManager exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    Debug.LogWarning("[IGPRoomManager] Not in any room");
                    return;
                }

                Debug.Log($"[IGPRoomManager] Finishing game in room: {arenaManager.CurrentRoomId}");
                await arenaManager.FinishHostedGameAsync();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGPRoomManager] Failed to finish game: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 通知宿主在 finished 后重开当前房间。
        /// </summary>
        public async Task RequestRematchAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    Debug.LogError("[IGPRoomManager] IGPRuntimeManager is null! Cannot request rematch.");
                    throw new InvalidOperationException("IGPRuntimeManager not initialized. Make sure IGPRuntimeManager exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    Debug.LogWarning("[IGPRoomManager] Not in any room");
                    return;
                }

                Debug.Log($"[IGPRoomManager] Requesting rematch for room: {arenaManager.CurrentRoomId}");
                await arenaManager.RequestRematchAsync();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGPRoomManager] Failed to request rematch: {ex.Message}");
                throw;
            }
        }

    }
}
