#nullable enable
using System.Collections;
using UnityEngine;

namespace IGP.UnitySDK.Samples
{
    /// <summary>
    /// Waits for hosted room attach, websocket connect, then data plane connect.
    /// Useful for validating KCP setup from a real desktop-launched session.
    /// </summary>
    public sealed class IGPKcpConnectionExample : MonoBehaviour
    {
        [SerializeField] private IGPRuntimeManager? runtimeManager = null;
        [SerializeField] private float connectionTimeout = 20f;

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

        private void Start()
        {
            if (runtimeManager == null)
            {
                Debug.LogError("[IGP KCP Sample] IGPRuntimeManager 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 hosted session...");

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

            if (!runtimeManager.IsWebSocketConnected)
            {
                Debug.LogError("[IGP KCP Sample] WebSocket connection timed out.");
                yield break;
            }

            Debug.Log("[IGP KCP Sample] WebSocket connected. Waiting for data plane...");

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

            if (!runtimeManager.IsKcpConnected)
            {
                Debug.LogError("[IGP KCP Sample] Data plane connection timed out.");
                yield break;
            }

            var avgRtt = runtimeManager.KcpRTTStats != null ? runtimeManager.KcpRTTStats.AvgRTT * 1000f : 0f;
            Debug.Log($"[IGP KCP Sample] Connected. avgRTT={avgRtt:F0}ms, alive={runtimeManager.IsKcpAlive}");
        }
    }
}
