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

namespace IGP.Multiplayer
{
    /// <summary>
    /// 房间管理器 - 仅负责当前宿主房间控制。
    /// 房间创建和加入由 Curio desktop 宿主统一管理，不再由 SDK 暴露。
    /// </summary>
    public class IGPRoomManager : MonoBehaviour
    {
        private const string LogScope = "room-manager";

        [Header("References")]
        [SerializeField] private IGPMultiplayerRuntime? arenaManager;
        
        void Start()
        {
            if (this == null) return;
            if (arenaManager == null)
            {
                arenaManager = FindAnyObjectByType<IGPMultiplayerRuntime>();
            }
            
            if (arenaManager == null)
            {
                IGPLog.Error(LogScope, "start", "event=runtime-manager-not-found");
                enabled = false;
                return;
            }
        }

        /// <summary>
        /// 离开当前房间
        /// </summary>
        public async Task LeaveCurrentRoomAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    IGPLog.Error(LogScope, "leave", "event=runtime-manager-not-found");
                    throw new System.InvalidOperationException("IGPMultiplayerRuntime not initialized. Make sure IGPMultiplayerRuntime exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    IGPLog.Warning(LogScope, "leave", "event=not-in-room");
                    return;
                }

                if (IGPLog.ShouldLog(IGPLogLevel.Info))
                {
                    IGPLog.Info(
                        LogScope,
                        "leave",
                        $"event=request roomId={IGPLog.FormatValue(arenaManager.CurrentRoomId)}");
                }
                await arenaManager.LeaveHostedRoomAsync();

                IGPLog.Info(LogScope, "leave", "event=succeeded");
            }
            catch (System.Exception ex)
            {
                if (IGPLog.ShouldLog(IGPLogLevel.Error))
                {
                    IGPLog.Error(
                        LogScope,
                        "leave",
                        $"event=failed error={IGPLog.FormatValue(ex.Message)}");
                }
                throw;
            }
        }

        /// <summary>
        /// 通知宿主结束当前对局。
        /// </summary>
        public async Task FinishCurrentGameAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    IGPLog.Error(LogScope, "finish", "event=runtime-manager-not-found");
                    throw new InvalidOperationException("IGPMultiplayerRuntime not initialized. Make sure IGPMultiplayerRuntime exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    IGPLog.Warning(LogScope, "finish", "event=not-in-room");
                    return;
                }

                if (IGPLog.ShouldLog(IGPLogLevel.Info))
                {
                    IGPLog.Info(
                        LogScope,
                        "finish",
                        $"event=request roomId={IGPLog.FormatValue(arenaManager.CurrentRoomId)}");
                }
                await arenaManager.FinishHostedGameAsync();
            }
            catch (Exception ex)
            {
                if (IGPLog.ShouldLog(IGPLogLevel.Error))
                {
                    IGPLog.Error(
                        LogScope,
                        "finish",
                        $"event=failed error={IGPLog.FormatValue(ex.Message)}");
                }
                throw;
            }
        }

        /// <summary>
        /// 通知宿主在 finished 后重开当前房间。
        /// </summary>
        public async Task RequestRematchAsync()
        {
            try
            {
                if (arenaManager == null)
                {
                    IGPLog.Error(LogScope, "rematch", "event=runtime-manager-not-found");
                    throw new InvalidOperationException("IGPMultiplayerRuntime not initialized. Make sure IGPMultiplayerRuntime exists in the scene.");
                }

                if (string.IsNullOrEmpty(arenaManager.CurrentRoomId))
                {
                    IGPLog.Warning(LogScope, "rematch", "event=not-in-room");
                    return;
                }

                if (IGPLog.ShouldLog(IGPLogLevel.Info))
                {
                    IGPLog.Info(
                        LogScope,
                        "rematch",
                        $"event=request roomId={IGPLog.FormatValue(arenaManager.CurrentRoomId)}");
                }
                await arenaManager.RequestRematchAsync();
            }
            catch (Exception ex)
            {
                if (IGPLog.ShouldLog(IGPLogLevel.Error))
                {
                    IGPLog.Error(
                        LogScope,
                        "rematch",
                        $"event=failed error={IGPLog.FormatValue(ex.Message)}");
                }
                throw;
            }
        }

    }
}
