#nullable enable
using System.Collections;
using UnityEngine;

namespace IGP.Multiplayer.Samples
{
    /// <summary>
    /// Observes the RoomNode data plane established by the configured multiplayer transport.
    /// </summary>
    public sealed class IGPKcpConnectionExample : MonoBehaviour
    {
        [SerializeField] private IGPMultiplayerRuntime? runtimeManager = null;
        [SerializeField] private float connectionTimeout = 20f;

        private void Awake()
        {
            runtimeManager ??= GetComponent<IGPMultiplayerRuntime>();
        }

        private void Start()
        {
            if (runtimeManager == null)
            {
                Debug.LogError("[IGP KCP Sample] IGPMultiplayerRuntime missing on this GameObject.");
                return;
            }

            StartCoroutine(RunExampleSequence());
        }

        private IEnumerator RunExampleSequence()
        {
            yield return new WaitForEndOfFrame();

            Debug.Log("[IGP KCP Sample] Waiting for hosted room context...");

            float timer = 0f;
            while (string.IsNullOrEmpty(runtimeManager!.CurrentRoomId) && timer < connectionTimeout)
            {
                yield return new WaitForSeconds(0.5f);
                timer += 0.5f;
            }

            if (string.IsNullOrEmpty(runtimeManager.CurrentRoomId))
            {
                Debug.LogError("[IGP KCP Sample] Timed out waiting for hosted room.");
                yield break;
            }

            Debug.Log($"[IGP KCP Sample] Room {runtimeManager.CurrentRoomCode} attached. Waiting for the multiplayer transport...");

            timer = 0f;
            while (!runtimeManager.IsRealtimeReady && timer < connectionTimeout)
            {
                yield return new WaitForSeconds(0.5f);
                timer += 0.5f;
            }

            if (!runtimeManager.IsRealtimeReady)
            {
                Debug.LogError("[IGP KCP Sample] Timed out waiting for the multiplayer transport data plane.");
                yield break;
            }

            var appRtt = runtimeManager.AppRTTStats;
            var kcpStats = runtimeManager.KcpTransportStats;
            var appRttText = appRtt != null && appRtt.SampleCount > 0 ? $"{appRtt.AvgRTT * 1000f:F0}ms" : "--";
            var kcpRttText = kcpStats.HasSmoothedRtt ? $"{kcpStats.SmoothedRttMs}ms" : "--";
            Debug.Log($"[IGP KCP Sample] Connected. appRTT={appRttText}, kcpSrtt={kcpRttText}, alive={runtimeManager.IsKcpAlive}");
        }
    }
}
