#nullable enable
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using IGP.Multiplayer.Core;
using IGP.Multiplayer.Network;
using Mirror;
using UnityEngine;
using IGPLog = IGP.UnitySDK.IGPLog;
using IGPLogLevel = IGP.UnitySDK.IGPLogLevel;

namespace IGP.Multiplayer.Mirror
{
    [DisallowMultipleComponent]
    [AddComponentMenu("Network/IGP Mirror Transport")]
    public sealed class IGPMirrorTransport : Transport
    {
        // These values preserve the logical Mirror channel across the IGP data plane.
        // They do not describe whether the effective transport was KCP, TCP, or UDP.
        internal const uint MirrorReliableChannelMessageType = 41010;
        internal const uint MirrorUnreliableChannelMessageType = 41011;
        internal const uint MirrorCompressedReliableChannelMessageType = 41012;
        internal const uint MirrorCompressedUnreliableChannelMessageType = 41013;
        internal const uint MirrorReliableApplicationFrameMessageType = 41014;
        private const int ReliablePacketMaxBytes = 256 * 1024;
        private const int DefaultUdpUnreliablePacketMaxBytes = 1200;
        private const int MaxQueuedMessages = 4096;
        private const int MaxQueuedMessageBytes = 16 * 1024 * 1024;
        private const int MaxQueuedMessagesPerPeer = 1024;
        private const int MaxQueuedMessageBytesPerPeer = 4 * 1024 * 1024;
        private const int MaxPeerLifecycleQueuedMessages = 256;
        private const int MaxPeerLifecycleQueuedMessageBytes = 1024 * 1024;
        private const int MaxDrainMessagesPerEarlyUpdate = 256;
        private const int MaxDrainBytesPerEarlyUpdate = 1024 * 1024;
        private const double MaxDrainSecondsPerEarlyUpdate = 0.002;
        private const float DefaultConnectRetryIntervalSeconds = 60f;
        private const float DefaultConnectTimeoutSeconds = 300f;
        private const int DefaultCompressionThresholdBytes = 0;
        private const float DefaultMinCompressionRatio = 1f;
        private const int DefaultReliableBatchThresholdBytes = 1024;
        private const float DefaultPeerSilenceTimeoutSeconds = 300f;
        private const float SuppressedLogIntervalSeconds = 5f;

        [Header("Runtime")]
        [SerializeField] private IGPMultiplayerRuntime? runtimeManager = null;
        private IIGPMultiplayerTransportBackend? runtimeBackend;

        [Header("Connection")]
        [SerializeField] private float connectRetryIntervalSeconds = DefaultConnectRetryIntervalSeconds;
        [SerializeField] private float connectTimeoutSeconds = DefaultConnectTimeoutSeconds;
        [Tooltip("Disconnect a Mirror peer after this many seconds without inbound data. Set higher for reconnect-heavy or large-payload sessions.")]
        [Min(1f)]
        [SerializeField] private float peerSilenceTimeoutSeconds = DefaultPeerSilenceTimeoutSeconds;

        [HideInInspector, SerializeField] private bool enablePayloadCompression = false;
        [HideInInspector, SerializeField] private int compressionThresholdBytes = DefaultCompressionThresholdBytes;
        [HideInInspector, SerializeField] private float minCompressionRatio = DefaultMinCompressionRatio;

        [Header("Batching")]
        [HideInInspector, SerializeField] private int reliableBatchThresholdBytes = DefaultReliableBatchThresholdBytes;

        private readonly object queueLock = new object();
        private readonly IGPNetworkAnomalyLogLimiter anomalyLogLimiter = new IGPNetworkAnomalyLogLimiter();
        private readonly Queue<QueuedMessage> messageQueue = new Queue<QueuedMessage>();
        private readonly Queue<QueuedMessage> peerLifecycleQueue = new Queue<QueuedMessage>();
        private readonly Dictionary<string, QueueUsage> queuedUsageByPlayerId =
            new Dictionary<string, QueueUsage>(StringComparer.Ordinal);
        private readonly Dictionary<int, string> connectionIdToPlayerId = new Dictionary<int, string>();
        private readonly Dictionary<string, int> playerIdToConnectionId =
            new Dictionary<string, int>(StringComparer.Ordinal);
        private readonly Dictionary<string, Guid?> serverConnectAttempts = new Dictionary<string, Guid?>(StringComparer.Ordinal);

        private bool runtimeBound;
        private bool realtimeConnectionFailureHandled;
        private bool backendWasReady;
        private bool udpUnavailableWarningEmitted;
        private bool serverActive;
        private int lifecycleCallbackDepth;
        private string mirrorMatchId = string.Empty;
        private bool configurationLogged;
        private int nextConnectionId = 1;
        private string? pendingClientAddress;
        private string? pendingClientTargetPlayerId;
        private Guid? pendingClientConnectAttemptId;
        private string? connectedServerPlayerId;
        private Guid? connectedClientConnectAttemptId;
        private int clientConnectionId;
        private float nextConnectAttemptAt;
        private float connectDeadlineAt;
        private float nextSuppressedConnectLogAt;
        private int queuedMessageBytes;
        private int queuedPeerLifecycleBytes;
        private long droppedUnreliableMessages;
        private long droppedUnreliableSends;
        private long reliableOverflowDisconnects;
        private float nextQueueDepthWarningAt;
        private float clientLastInboundFromHostAt;
        private readonly Dictionary<string, float> serverLastInboundByPlayerId =
            new Dictionary<string, float>(StringComparer.Ordinal);

        private struct QueuedMessage
        {
            public string RemotePlayerId;
            public uint MessageType;
            public byte[] Payload;
            public float EnqueuedAt;
        }

        private struct QueueUsage
        {
            public int Messages;
            public int Bytes;
        }



        private readonly struct PayloadSendDiagnostics
        {
            private PayloadSendDiagnostics(int originalBytes) { OriginalBytes = originalBytes; }
            public int OriginalBytes { get; }
            public static PayloadSendDiagnostics NotAttempted(int originalBytes) => new PayloadSendDiagnostics(originalBytes);
            public PayloadSendDiagnostics EnsureOriginalBytes(int fallbackBytes) =>
                OriginalBytes > 0 || fallbackBytes <= 0 ? this : NotAttempted(fallbackBytes);
        }

        public bool IsClientConnecting => !ClientConnected() && !string.IsNullOrWhiteSpace(pendingClientAddress);
        public string ClientTargetPlayerId => connectedServerPlayerId ?? pendingClientTargetPlayerId ?? string.Empty;
        public int ClientConnectionId => clientConnectionId;
        public int ServerConnectionCount => connectionIdToPlayerId.Count;
        [Obsolete("Mirror payload compression has been removed. This compatibility setting has no effect.")]
        public bool EnablePayloadCompression
        {
            get => false;
            set => enablePayloadCompression = value;
        }

        [Obsolete("Mirror payload compression has been removed. This compatibility setting has no effect.")]
        public int CompressionThresholdBytes
        {
            get => DefaultCompressionThresholdBytes;
            set => compressionThresholdBytes = value;
        }

        [Obsolete("Mirror payload compression has been removed. This compatibility setting has no effect.")]
        public float MinCompressionRatio
        {
            get => DefaultMinCompressionRatio;
            set => minCompressionRatio = value;
        }

        [Obsolete("Mirror reliable batching is fixed at 1024 bytes. This setting no longer changes behavior.")]
        public int ReliableBatchThresholdBytes
        {
            get => DefaultReliableBatchThresholdBytes;
            set => reliableBatchThresholdBytes = value;
        }

        public float PeerSilenceTimeoutSeconds
        {
            get => NormalizePeerSilenceTimeout(peerSilenceTimeoutSeconds);
            set => peerSilenceTimeoutSeconds = NormalizePeerSilenceTimeout(value);
        }

        public override bool Available() => true;

        public override bool ClientConnected() => !string.IsNullOrWhiteSpace(connectedServerPlayerId);

        public override void ClientConnect(string address)
        {
            const string path = "ClientConnect";
            bool runtimeReady = TryBindRuntime(
                AppendPath(path, "TryBindRuntime"),
                logFailure: true);
            LogConfigurationOnce(path);
            mirrorMatchId = runtimeManager?.MirrorMatchId ?? string.Empty;
            string normalizedAddress = string.IsNullOrWhiteSpace(address) ? "host" : address.Trim();
            string targetPlayerId = ResolveServerPlayerId(normalizedAddress);
            if (!runtimeReady)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed address={FormatValue(address)} normalizedAddress={normalizedAddress} " +
                    $"target={FormatValue(targetPlayerId)} reason=runtime-not-ready");
            }

            if (ClientConnected() &&
                !string.IsNullOrWhiteSpace(targetPlayerId) &&
                string.Equals(connectedServerPlayerId, targetPlayerId, StringComparison.Ordinal))
            {
                return;
            }

            if (ClientConnected())
            {
                CompleteClientDisconnect(sendDisconnectPacket: true, AppendPath(path, "CompleteClientDisconnect"));
            }

            bool isSamePendingTarget =
                !string.IsNullOrWhiteSpace(pendingClientAddress) &&
                (string.Equals(pendingClientAddress, normalizedAddress, StringComparison.OrdinalIgnoreCase) ||
                 (!string.IsNullOrWhiteSpace(targetPlayerId) &&
                  string.Equals(pendingClientTargetPlayerId, targetPlayerId, StringComparison.Ordinal)));

            if (!ClientConnected() && isSamePendingTarget)
            {
                return;
            }

            pendingClientAddress = normalizedAddress;
            pendingClientTargetPlayerId = targetPlayerId;
            pendingClientConnectAttemptId = Guid.NewGuid();
            connectedClientConnectAttemptId = null;
            clientConnectionId = 0;
            nextConnectAttemptAt = 0f;
            connectDeadlineAt = 0f;
            nextSuppressedConnectLogAt = 0f;
            clientLastInboundFromHostAt = 0f;
            IGPLog.Info(
                "mirror-transport",
                path,
                $"pending target={FormatValue(targetPlayerId)} attemptId={pendingClientConnectAttemptId.Value:N} " +
                $"timeoutSeconds={connectTimeoutSeconds:F2} retryIntervalSeconds={connectRetryIntervalSeconds:F2}");
            ObserveRuntimeConnectionState();
        }

        public override void ClientSend(ArraySegment<byte> segment, int channelId = Channels.Reliable)
        {
            if (TryClientSend(segment, channelId)) return;
            if (NormalizeChannel(channelId) == Channels.Reliable && !string.IsNullOrEmpty(connectedServerPlayerId))
                FailReliablePeer(connectedServerPlayerId!, lastSendError, "Reliable Mirror message was not accepted.");
            else if (NormalizeChannel(channelId) == Channels.Reliable) NotifyClientError(lastSendError, "Mirror message was not accepted.");
        }

        /// <summary>True means local acceptance, not remote delivery. A rejected message is not retained.</summary>
        public bool TryClientSend(ArraySegment<byte> segment, int channelId = Channels.Reliable)
        {
            if (!ClientConnected() || string.IsNullOrWhiteSpace(connectedServerPlayerId))
                return RejectOutbound("TryClientSend", "client-not-connected", segment.Count);
            return TryAcceptPayload(connectedServerPlayerId!, segment, NormalizeChannel(channelId), true, clientConnectionId, "TryClientSend");
        }

        public override void ClientDisconnect()
        {
            const string path = "ClientDisconnect";
            IGPLog.Debug(
                "mirror-transport",
                path,
                "called");
            var runtime = runtimeManager;
            string match = mirrorMatchId;
            bool leave = lifecycleCallbackDepth == 0 && !serverActive && HasMirrorSession();
            CompleteClientDisconnect(sendDisconnectPacket: true, AppendPath(path, "CompleteClientDisconnect"),
                beforeNotify: leave ? () => runtime?.RequestMirrorLeave(match, path) : (Action?)null);
        }

        public override Uri ServerUri()
        {
            return new Uri("igp://host");
        }

        public override bool ServerActive() => serverActive;

        public override void ServerStart()
        {
            const string path = "ServerStart";
            bool runtimeReady = TryBindRuntime(
                AppendPath(path, "TryBindRuntime"),
                logFailure: true);
            mirrorMatchId = runtimeManager?.MirrorMatchId ?? string.Empty;
            LogConfigurationOnce(path);
            serverActive = true;
            LogAtLevel(
                runtimeReady ? IGPLogLevel.Info : IGPLogLevel.Warning,
                path,
                $"started runtimeReady={runtimeReady}");
            ObserveRuntimeConnectionState();
        }

        public override void ServerSend(int connectionId, ArraySegment<byte> segment, int channelId = Channels.Reliable)
        {
            if (TryServerSend(connectionId, segment, channelId)) return;
            if (NormalizeChannel(channelId) == Channels.Reliable && connectionIdToPlayerId.TryGetValue(connectionId,out var target))
                FailReliablePeer(target,lastSendError,"Reliable Mirror message was not accepted.");
            else if (NormalizeChannel(channelId) == Channels.Reliable) NotifyServerError(connectionId,lastSendError,"Mirror message was not accepted.");
        }

        /// <summary>True means local acceptance, not remote delivery. A rejected message is not retained.</summary>
        public bool TryServerSend(int connectionId, ArraySegment<byte> segment, int channelId = Channels.Reliable)
        {
            if (!serverActive || !connectionIdToPlayerId.TryGetValue(connectionId, out var remotePlayerId))
                return RejectOutbound("TryServerSend", "unknown-server-connection", segment.Count);
            return TryAcceptPayload(remotePlayerId, segment, NormalizeChannel(channelId), false, connectionId, "TryServerSend");
        }

        private bool TryAcceptPayload(string remotePlayerId, ArraySegment<byte> segment, int channel, bool fromClient, int connectionId, string path)
        {
            int limit = channel == Channels.Reliable ? ReliablePacketMaxBytes : ResolveUnreliablePacketMaxBytes();
            if (segment.Array == null || segment.Count <= 0 || segment.Count > limit)
                return RejectOutbound(path, "invalid-payload-size", segment.Count);

            if (channel == Channels.Reliable)
            {
                lastSendError=TransportError.InvalidSend;
                if (runtimeManager != null && !runtimeManager.CanQueueMirrorReliablePayload(remotePlayerId,segment.Count,MirrorReliableChannelMessageType)) return RejectOutbound(path,"game-payload-limit",segment.Count);
                byte[] owned=CopySegment(segment);
                var result=SendReliablePayload(remotePlayerId,owned);
                if(result!=IGPNetworkResult.kSuccess) {
                    lastSendError=result==IGPNetworkResult.kErrorWouldBlock ? TransportError.Congestion : TransportError.InvalidSend;
                    return RejectOutbound(path,result.ToString(),segment.Count);
                }
                runtimeManager?.ObserveMirrorMessageSubmitted(owned.Length);
                NotifyPayloadSent(fromClient,connectionId,owned,channel);
                return true;
            }

            byte[] payload = CopySegment(segment);
            if (TrySendPayload(remotePlayerId, payload, channel, path) != IGPNetworkResult.kSuccess)
            {
                droppedUnreliableSends++;
                return RejectOutbound(path, "unreliable-not-accepted", segment.Count);
            }
            NotifyPayloadSent(fromClient, connectionId, payload, channel);
            return true;
        }

        private bool RejectOutbound(string path, string reason, int bytes)
        {
            if (!reason.StartsWith("kError", StringComparison.Ordinal)) lastSendError = TransportError.InvalidSend;
            anomalyLogLimiter.ObserveEvent("outbound-rejected-" + reason, Now,
                () => $"event=send-rejected reason={reason} bytes={bytes}",
                message => IGPLog.Warning("mirror-transport", path, message));
            return false;
        }

        private void NotifyPayloadSent(bool fromClient, int connectionId, byte[] payload, int channel)
        {
            if (fromClient) OnClientDataSent?.Invoke(new ArraySegment<byte>(payload), channel);
            else OnServerDataSent?.Invoke(connectionId, new ArraySegment<byte>(payload), channel);
        }

        public override void ServerDisconnect(int connectionId)
        {
            const string path = "ServerDisconnect";
            if (!connectionIdToPlayerId.TryGetValue(connectionId, out var remotePlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"ignored reason=unknown_connection connectionId={connectionId}");
                return;
            }

            TrySendPeerLifecycle(
                remotePlayerId,
                IGPMirrorPeerProtocol.DisconnectMessageType,
                new byte[] { 1 },
                AppendPath(path, "TrySendPeerLifecycle"));
            RemoveServerConnection(
                connectionId,
                remotePlayerId,
                notifyMirror: true,
                AppendPath(path, "RemoveServerConnection"));
        }

        public override string ServerGetClientAddress(int connectionId)
        {
            const string path = "ServerGetClientAddress";
            if (connectionIdToPlayerId.TryGetValue(connectionId, out var remotePlayerId))
            {
                return remotePlayerId;
            }

            IGPLog.Warning(
                "mirror-transport",
                path,
                $"returning_empty reason=unknown_connection connectionId={connectionId}");
            return string.Empty;
        }

        public override void ServerStop()
        {
            const string path = "ServerStop";
            var runtime = runtimeManager;
            string match = mirrorMatchId;
            bool leave = lifecycleCallbackDepth == 0 && serverActive && HasMirrorSession();
            var activeConnections = new List<KeyValuePair<int, string>>(connectionIdToPlayerId);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"called activeConnections={activeConnections.Count} serverActive={serverActive}");
            foreach (var entry in activeConnections)
            {
                TrySendPeerLifecycle(
                    entry.Value,
                    IGPMirrorPeerProtocol.DisconnectMessageType,
                    new byte[] { 1 },
                    AppendPath(path, "TrySendPeerLifecycle"));
                RemoveServerConnection(
                    entry.Key,
                    entry.Value,
                    notifyMirror: false,
                    AppendPath(path, "RemoveServerConnection"));
            }

            serverActive = false;
            if (leave) runtime?.RequestMirrorLeave(match, path);
            IGPLog.Info(
                "mirror-transport",
                path,
                "stopped");
        }

        public override int GetMaxPacketSize(int channelId = Channels.Reliable)
        {
            return NormalizeChannel(channelId) == Channels.Unreliable
                ? ResolveUnreliablePacketMaxBytes()
                : ReliablePacketMaxBytes;
        }

        public override int GetBatchThreshold(int channelId = Channels.Reliable)
        {
            return NormalizeChannel(channelId) == Channels.Unreliable
                ? ResolveUnreliablePacketMaxBytes()
                : DefaultReliableBatchThresholdBytes;
        }

        public override void ClientEarlyUpdate()
        {
            if (NetworkClient.activeHost)
            {
                return;
            }

            TryBindRuntime();
            ObserveRuntimeConnectionState();
            if (!EnsureDataPlaneReady("ClientEarlyUpdate"))
            {
                return;
            }

            ProcessQueuedMessages(forServer: false, "ClientEarlyUpdate->ProcessQueuedMessages");
            CheckClientPeerSilence();
        }

        public override void ServerEarlyUpdate()
        {
            TryBindRuntime();
            ObserveRuntimeConnectionState();
            if (!EnsureDataPlaneReady("ServerEarlyUpdate"))
            {
                return;
            }

            ProcessQueuedMessages(forServer: true, "ServerEarlyUpdate->ProcessQueuedMessages");
            CheckServerPeerSilence();

        }

        public override void ClientLateUpdate()
        {
            const string path = "ClientLateUpdate";
            if (NetworkClient.activeHost)
            {
                return;
            }

            TryBindRuntime();
            ObserveRuntimeConnectionState();

            if (ClientConnected() || string.IsNullOrWhiteSpace(pendingClientAddress))
            {
                return;
            }

            if (!EnsureDataPlaneReady(path))
            {
                return;
            }

            if (connectDeadlineAt <= 0f)
            {
                connectDeadlineAt = Now + connectTimeoutSeconds;
            }

            pendingClientTargetPlayerId = ResolveServerPlayerId(pendingClientAddress!);
            if (string.IsNullOrWhiteSpace(pendingClientTargetPlayerId))
            {
                float pendingNow = Now;
                if (pendingNow >= nextSuppressedConnectLogAt)
                {
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"waiting reason=target_player_unresolved pendingAddress={FormatValue(pendingClientAddress)}");
                    nextSuppressedConnectLogAt = pendingNow + SuppressedLogIntervalSeconds;
                }

                return;
            }

            float now = Now;
            if (now >= connectDeadlineAt)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"timeout target={pendingClientTargetPlayerId} timeoutSeconds={connectTimeoutSeconds:F2}");
                NotifyClientError(
                    TransportError.Timeout,
                    $"Timed out connecting to hosted player `{pendingClientTargetPlayerId}`.");
                CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "CompleteClientDisconnect"));
                return;
            }

            if (now < nextConnectAttemptAt)
            {
                return;
            }

            pendingClientConnectAttemptId ??= Guid.NewGuid();
            var sendResult = TrySendPeerLifecycle(
                pendingClientTargetPlayerId!,
                IGPMirrorPeerProtocol.ConnectRequestMessageType,
                IGPMirrorPeerProtocol.EncodeConnectRequest(pendingClientConnectAttemptId.Value, GetLocalConnectCapabilities()),
                AppendPath(path, "TrySendPeerLifecycle"));
            nextConnectAttemptAt = now + connectRetryIntervalSeconds;

            if (sendResult == IGPNetworkResult.kSuccess)
            {
                return;
            }

            IGPLog.Warning(
                "mirror-transport",
                path,
                $"connect_request_failed target={pendingClientTargetPlayerId} " +
                $"attemptId={pendingClientConnectAttemptId.Value:N} result={sendResult}");
        }

        public override void Shutdown()
        {
            const string path = "Shutdown";
            var runtime = runtimeManager;
            string match = mirrorMatchId;
            bool leave = lifecycleCallbackDepth == 0 && HasMirrorSession();
            IGPLog.Debug(
                "mirror-transport",
                path,
                "called");
            ClientDisconnect();
            ServerStop();
            // Client callbacks may have re-entered Shutdown and cleared the server state.
            if (leave) runtime?.RequestMirrorLeave(match, path);
            ClearQueuedMessages();
            realtimeConnectionFailureHandled = false;
            UnbindRuntime(AppendPath(path, "UnbindRuntime"));
        }

        public override void OnApplicationQuit()
        {
            IGPLog.Debug(
                "mirror-transport",
                "OnApplicationQuit",
                "called");
            Shutdown();
            base.OnApplicationQuit();
        }

        private void OnDestroy()
        {
            runtimeManager?.UnregisterMirrorShutdown(this);
        }

        private void ProcessQueuedMessages(bool forServer, string path)
        {
            if (forServer && !serverActive)
            {
                int pendingMessages;
                int pendingBytes;
                lock (queueLock)
                {
                    pendingMessages = messageQueue.Count + peerLifecycleQueue.Count;
                    pendingBytes = queuedMessageBytes + queuedPeerLifecycleBytes;
                }

                if (pendingMessages > 0 && Now >= nextQueueDepthWarningAt)
                {
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"not_processing reason=server_not_active action=observe-only pending={pendingMessages} " +
                        $"pendingKB={(pendingBytes / 1024.0):F1}");
                    nextQueueDepthWarningAt = Now + IGPNetworkAnomalyLogLimiter.DefaultRepeatIntervalSeconds;
                }

                return;
            }

            long drainStartedAt = System.Diagnostics.Stopwatch.GetTimestamp();
            while (true)
            {
                QueuedMessage peerLifecycleMessage;
                lock (queueLock)
                {
                    if (peerLifecycleQueue.Count == 0)
                    {
                        break;
                    }
                    peerLifecycleMessage = peerLifecycleQueue.Dequeue();
                    queuedPeerLifecycleBytes = Math.Max(
                        0,
                        queuedPeerLifecycleBytes - (peerLifecycleMessage.Payload?.Length ?? 0));
                }

                DispatchQueuedMessage(peerLifecycleMessage, forServer, path);
            }

            int payloadMessages = 0;
            int payloadBytes = 0;
            while (payloadMessages < MaxDrainMessagesPerEarlyUpdate)
            {
                if (payloadMessages > 0 &&
                    (System.Diagnostics.Stopwatch.GetTimestamp() - drainStartedAt) /
                    (double)System.Diagnostics.Stopwatch.Frequency >= MaxDrainSecondsPerEarlyUpdate)
                {
                    break;
                }

                QueuedMessage item;
                int nextBytes;
                lock (queueLock)
                {
                    if (messageQueue.Count == 0)
                    {
                        break;
                    }
                    item = messageQueue.Peek();
                    nextBytes = item.Payload?.Length ?? 0;
                    if (payloadMessages > 0 && payloadBytes + nextBytes > MaxDrainBytesPerEarlyUpdate)
                    {
                        break;
                    }

                    messageQueue.Dequeue();
                    queuedMessageBytes = Math.Max(0, queuedMessageBytes - nextBytes);
                    DecrementPeerQueueUsage(item.RemotePlayerId, nextBytes);
                }

                payloadMessages += 1;
                payloadBytes += nextBytes;
                DispatchQueuedMessage(item, forServer, path);
            }
        }

        private void DispatchQueuedMessage(QueuedMessage message, bool forServer, string path)
        {
            if (forServer)
            {
                HandleServerMessage(message, AppendPath(path, "HandleServerMessage"));
            }
            else
            {
                HandleClientMessage(message, AppendPath(path, "HandleClientMessage"));
            }
        }

        private void HandleServerMessage(QueuedMessage message, string path)
        {
            switch (message.MessageType)
            {
                case IGPMirrorPeerProtocol.ConnectRequestMessageType:
                    if (!CanProcessPeerLifecycleMessage(AppendPath(path, "CanProcessPeerLifecycleMessage")))
                    {
                        return;
                    }

                    HandleServerConnectRequest(message, AppendPath(path, "HandleServerConnectRequest"));
                    break;
                case IGPMirrorPeerProtocol.DisconnectMessageType:
                    if (!CanProcessPeerLifecycleMessage(AppendPath(path, "CanProcessPeerLifecycleMessage")))
                    {
                        return;
                    }

                    HandleServerDisconnect(message, AppendPath(path, "HandleServerDisconnect"));
                    break;
                case MirrorReliableChannelMessageType:
                case MirrorUnreliableChannelMessageType:
                case MirrorReliableApplicationFrameMessageType:
                case MirrorCompressedReliableChannelMessageType:
                case MirrorCompressedUnreliableChannelMessageType:
                    if (!TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: true) ||
                        runtimeManager?.Network == null)
                    {
                        IGPLog.Warning(
                            "mirror-transport",
                            path,
                            $"ignored reason=runtime_unavailable remote={FormatValue(message.RemotePlayerId)} " +
                            $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length}");
                        return;
                    }

                    if (!playerIdToConnectionId.TryGetValue(message.RemotePlayerId, out var dataConnectionId))
                    {
                        IGPLog.Warning(
                            "mirror-transport",
                            path,
                            $"ignored reason=unknown_player_connection remote={FormatValue(message.RemotePlayerId)} " +
                            $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length}");
                        return;
                    }

                    if (!TryPrepareIncomingMirrorPayload(
                            message,
                            dataConnectionId,
                            AppendPath(path, "TryPrepareIncomingMirrorPayload"),
                            out var serverPayload,
                            out var serverChannel))
                    {
                        return;
                    }

                    serverLastInboundByPlayerId[message.RemotePlayerId] = Now;
                    OnServerDataReceived?.Invoke(
                        dataConnectionId,
                        new ArraySegment<byte>(serverPayload),
                        serverChannel);
                    ObserveLargePayload(
                        "receive",
                        message.MessageType,
                        serverPayload.Length,
                        message.Payload.Length,
                        message.RemotePlayerId);
                    break;
                default:
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"ignored reason=unknown_message_type remote={FormatValue(message.RemotePlayerId)} " +
                        $"messageType={message.MessageType} bytes={message.Payload.Length}");
                    break;
            }
        }

        private bool CanProcessPeerLifecycleMessage(string path)
        {
            if (!TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: true) ||
                runtimeManager?.Network == null)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    "rejected reason=runtime_unavailable");
                return false;
            }

            return true;
        }

        private void HandleClientMessage(QueuedMessage message, string path)
        {
            if (!IsMessageFromCurrentServer(message.RemotePlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"ignored reason=not_current_server remote={FormatValue(message.RemotePlayerId)} " +
                    $"connectedServer={FormatValue(connectedServerPlayerId)} " +
                    $"pendingServer={FormatValue(pendingClientTargetPlayerId)} " +
                    $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length}");
                return;
            }

            switch (message.MessageType)
            {
                case IGPMirrorPeerProtocol.ConnectAcceptMessageType:
                    HandleClientConnectAccept(message, AppendPath(path, "HandleClientConnectAccept"));
                    break;
                case IGPMirrorPeerProtocol.DisconnectMessageType:
                    HandleClientDisconnect(message, AppendPath(path, "HandleClientDisconnect"));
                    break;
                case MirrorReliableChannelMessageType:
                case MirrorUnreliableChannelMessageType:
                case MirrorReliableApplicationFrameMessageType:
                case MirrorCompressedReliableChannelMessageType:
                case MirrorCompressedUnreliableChannelMessageType:
                    if (!ClientConnected())
                    {
                        IGPLog.Warning(
                            "mirror-transport",
                            path,
                            $"ignored reason=client_not_connected remote={FormatValue(message.RemotePlayerId)} " +
                            $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length}");
                        return;
                    }

                    if (!TryPrepareIncomingMirrorPayload(
                            message,
                            connectionId: null,
                            AppendPath(path, "TryPrepareIncomingMirrorPayload"),
                            out var clientPayload,
                            out var clientChannel))
                    {
                        return;
                    }

                    clientLastInboundFromHostAt = Now;
                    OnClientDataReceived?.Invoke(
                        new ArraySegment<byte>(clientPayload),
                        clientChannel);
                    ObserveLargePayload(
                        "receive",
                        message.MessageType,
                        clientPayload.Length,
                        message.Payload.Length,
                        message.RemotePlayerId);
                    break;
                default:
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"ignored reason=unknown_message_type remote={FormatValue(message.RemotePlayerId)} " +
                        $"messageType={message.MessageType} bytes={message.Payload.Length}");
                    break;
            }
        }

        private bool IsMessageFromCurrentServer(string remotePlayerId)
        {
            if (!string.IsNullOrWhiteSpace(connectedServerPlayerId))
            {
                return string.Equals(connectedServerPlayerId, remotePlayerId, StringComparison.Ordinal);
            }

            if (!string.IsNullOrWhiteSpace(pendingClientTargetPlayerId))
            {
                return string.Equals(pendingClientTargetPlayerId, remotePlayerId, StringComparison.Ordinal);
            }

            return false;
        }

        private void HandleServerConnectRequest(QueuedMessage message, string path)
        {
            float now = Now;
            var connectRequest = IGPMirrorPeerProtocol.DecodeConnectRequest(message.Payload);
            Guid? connectAttemptId = connectRequest.AttemptId;
            bool remoteSupportsRawReliable = HasCapability(
                connectRequest.Capabilities,
                IGPMirrorPeerProtocol.CapabilityRawReliable256KiB);
            IGPLog.Info(
                "mirror-transport",
                path,
                $"called remote={FormatValue(message.RemotePlayerId)} " +
                $"attemptId={FormatAttemptId(connectAttemptId)} bytes={message.Payload.Length} " +
                $"rawReliable256KiB={remoteSupportsRawReliable}");
            if (!remoteSupportsRawReliable)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=logical-connect-rejected reason=missing-raw-reliable-256kib " +
                    $"remote={FormatValue(message.RemotePlayerId)} capabilities={connectRequest.Capabilities}");
                TrySendPeerLifecycle(
                    message.RemotePlayerId,
                    IGPMirrorPeerProtocol.DisconnectMessageType,
                    new byte[] { 2 },
                    AppendPath(path, "RejectUnsupportedPeer"));
                return;
            }

            if (playerIdToConnectionId.TryGetValue(message.RemotePlayerId, out int previousConnection) &&
                serverConnectAttempts.TryGetValue(message.RemotePlayerId, out var previousAttempt) && previousAttempt != connectAttemptId)
            {
                RemoveServerConnection(previousConnection, message.RemotePlayerId, true, AppendPath(path, "ReplaceLogicalConnection"));
                // The disconnected callback can stop the server or install another connection.
                if (!serverActive || playerIdToConnectionId.ContainsKey(message.RemotePlayerId)) return;
            }
            serverConnectAttempts[message.RemotePlayerId] = connectAttemptId;
            serverLastInboundByPlayerId[message.RemotePlayerId] = now;
            bool isNewConnection =
                !playerIdToConnectionId.TryGetValue(message.RemotePlayerId, out var connectionId);

            if (isNewConnection)
            {
                connectionId = nextConnectionId++;
                playerIdToConnectionId[message.RemotePlayerId] = connectionId;
                connectionIdToPlayerId[connectionId] = message.RemotePlayerId;

                NotifyServerConnected(connectionId, message.RemotePlayerId, AppendPath(path, "NotifyServerConnected"));
            }

            if (!serverActive || !connectionIdToPlayerId.TryGetValue(connectionId, out var currentPlayer) ||
                currentPlayer != message.RemotePlayerId) return;
            TrySendPeerLifecycle(
                message.RemotePlayerId,
                IGPMirrorPeerProtocol.ConnectAcceptMessageType,
                IGPMirrorPeerProtocol.EncodeConnectAccept(
                    connectionId,
                    connectAttemptId,
                    IGPMirrorPeerProtocol.CapabilityRawReliable256KiB),
                AppendPath(path, "TrySendPeerLifecycle"));
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"connect_accept_sent remote={message.RemotePlayerId} " +
                $"connectionId={connectionId} attemptId={FormatAttemptId(connectAttemptId)} " +
                $"isNewConnection={isNewConnection} rawReliable256KiB=true");
        }

        private void HandleServerDisconnect(QueuedMessage message, string path)
        {
            if (playerIdToConnectionId.TryGetValue(message.RemotePlayerId, out var disconnectedConnectionId))
            {
                IGPLog.Info(
                    "mirror-transport",
                    path,
                    $"called remote={message.RemotePlayerId} connectionId={disconnectedConnectionId}");
                RemoveServerConnection(
                    disconnectedConnectionId,
                    message.RemotePlayerId,
                    notifyMirror: true,
                    AppendPath(path, "RemoveServerConnection"));
                return;
            }

            IGPLog.Warning(
                "mirror-transport",
                path,
                $"ignored reason=unknown_player_connection remote={FormatValue(message.RemotePlayerId)}");
        }

        private void HandleClientConnectAccept(QueuedMessage message, string path)
        {
            var connectAccept = IGPMirrorPeerProtocol.DecodeConnectAccept(message.Payload);
            int acceptedConnectionId = connectAccept.ConnectionId;
            Guid? acceptedAttemptId = connectAccept.AttemptId;
            bool acceptedRawReliable = HasCapability(
                connectAccept.Capabilities,
                IGPMirrorPeerProtocol.CapabilityRawReliable256KiB);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"called server={FormatValue(message.RemotePlayerId)} connectionId={acceptedConnectionId} " +
                $"attemptId={FormatAttemptId(acceptedAttemptId)} bytes={message.Payload.Length} " +
                $"rawReliable256KiB={acceptedRawReliable}");

            if (ClientConnected())
            {
                if (IsDuplicateConnectedAccept(message.RemotePlayerId, acceptedConnectionId, acceptedAttemptId))
                {
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"ignored reason=duplicate_connect_accept server={FormatValue(message.RemotePlayerId)} " +
                        $"connectionId={acceptedConnectionId} attemptId={FormatAttemptId(acceptedAttemptId)}");
                    return;
                }

                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"ignored reason=already_connected server={message.RemotePlayerId} " +
                    $"connectionId={acceptedConnectionId} " +
                    $"attemptId={FormatAttemptId(acceptedAttemptId)}");
                return;
            }

            if (pendingClientConnectAttemptId.HasValue &&
                acceptedAttemptId.HasValue &&
                pendingClientConnectAttemptId.Value != acceptedAttemptId.Value)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"ignored reason=stale_connect_accept server={message.RemotePlayerId} " +
                    $"connectionId={acceptedConnectionId} expectedAttemptId={pendingClientConnectAttemptId.Value:N} " +
                    $"actualAttemptId={acceptedAttemptId.Value:N}");
                return;
            }

            if (!acceptedRawReliable)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=logical-connect-rejected reason=missing-raw-reliable-256kib " +
                    $"server={FormatValue(message.RemotePlayerId)} capabilities={connectAccept.Capabilities}");
                NotifyClientError(
                    TransportError.InvalidReceive,
                    "IGP Mirror peer does not support RawReliable256KiB.");
                CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "UnsupportedPeerDisconnect"));
                return;
            }

            connectedServerPlayerId = message.RemotePlayerId;
            connectedClientConnectAttemptId = acceptedAttemptId ?? pendingClientConnectAttemptId;
            clientLastInboundFromHostAt = Now;
            pendingClientAddress = null;
            pendingClientTargetPlayerId = null;
            pendingClientConnectAttemptId = null;
            clientConnectionId = acceptedConnectionId;

            OnClientConnected?.Invoke();
            IGPLog.Info(
                "mirror-transport",
                path,
                $"connected server={message.RemotePlayerId} connectionId={acceptedConnectionId} " +
                $"attemptId={FormatAttemptId(connectedClientConnectAttemptId)} " +
                $"rawReliable256KiB=true");
        }

        private void HandleClientDisconnect(QueuedMessage message, string path)
        {
            IGPLog.Info(
                "mirror-transport",
                path,
                $"called server={FormatValue(message.RemotePlayerId)} bytes={message.Payload.Length}");
            CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "CompleteClientDisconnect"));
        }

        private bool HasMirrorSession()
        {
            return runtimeManager != null && !string.IsNullOrEmpty(mirrorMatchId) &&
                mirrorMatchId == runtimeManager.MirrorMatchId &&
                (serverActive || !string.IsNullOrEmpty(connectedServerPlayerId) || !string.IsNullOrEmpty(pendingClientAddress));
        }

        private void NotifyClientError(TransportError error, string message)
        {
            lifecycleCallbackDepth++;
            try { OnClientError?.Invoke(error, message); }
            finally { lifecycleCallbackDepth--; }
        }

        private void NotifyServerError(int connectionId, TransportError error, string message)
        {
            lifecycleCallbackDepth++;
            try { OnServerError?.Invoke(connectionId, error, message); }
            finally { lifecycleCallbackDepth--; }
        }

        private void NotifyClientDisconnected()
        {
            lifecycleCallbackDepth++;
            try { OnClientDisconnected?.Invoke(); }
            finally { lifecycleCallbackDepth--; }
        }

        private void NotifyServerDisconnected(int connectionId)
        {
            lifecycleCallbackDepth++;
            try { OnServerDisconnected?.Invoke(connectionId); }
            finally { lifecycleCallbackDepth--; }
        }

        private void CompleteClientDisconnect(bool sendDisconnectPacket, string path, Action? beforeNotify = null)
        {
            var remotePlayerId = connectedServerPlayerId ?? pendingClientTargetPlayerId;
            var hadState =
                !string.IsNullOrWhiteSpace(remotePlayerId) || !string.IsNullOrWhiteSpace(pendingClientAddress);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"called sendDisconnectPacket={sendDisconnectPacket} hadState={hadState} " +
                $"remote={FormatValue(remotePlayerId)} pendingAddress={FormatValue(pendingClientAddress)}");

            if (sendDisconnectPacket && !string.IsNullOrWhiteSpace(remotePlayerId))
            {
                TrySendPeerLifecycle(
                    remotePlayerId!,
                    IGPMirrorPeerProtocol.DisconnectMessageType,
                    new byte[] { 1 },
                    AppendPath(path, "TrySendPeerLifecycle"));
            }
            else if (sendDisconnectPacket)
            {
                IGPLog.Debug(
                    "mirror-transport",
                    path,
                    "disconnect_packet_skipped reason=no_remote_player");
            }

            if (!string.IsNullOrWhiteSpace(remotePlayerId))
            {
                RemoveQueuedMessagesForPeer(remotePlayerId!);
            }

            pendingClientAddress = null;
            pendingClientTargetPlayerId = null;
            pendingClientConnectAttemptId = null;
            connectedServerPlayerId = null;
            connectedClientConnectAttemptId = null;
            clientConnectionId = 0;
            nextConnectAttemptAt = 0f;
            connectDeadlineAt = 0f;
            nextSuppressedConnectLogAt = 0f;
            clientLastInboundFromHostAt = 0f;

            if (!string.IsNullOrWhiteSpace(remotePlayerId)) runtimeManager?.CancelMirrorPeerDelivery(remotePlayerId!);
            try { beforeNotify?.Invoke(); } catch(Exception ex) { IGPLog.Error("mirror-transport",path,ex.GetType().Name); }
            if (hadState)
            {
                NotifyClientDisconnected();
                IGPLog.Info(
                    "mirror-transport",
                    path,
                    "client_disconnected_notified");
            }
        }

        private void RemoveServerConnection(int connectionId, string remotePlayerId, bool notifyMirror, string path)
        {
            RemoveQueuedMessagesForPeer(remotePlayerId);
            playerIdToConnectionId.Remove(remotePlayerId);
            connectionIdToPlayerId.Remove(connectionId);
            serverLastInboundByPlayerId.Remove(remotePlayerId);
            serverConnectAttempts.Remove(remotePlayerId);
            runtimeManager?.CancelMirrorPeerDelivery(remotePlayerId);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"removed connectionId={connectionId} remote={FormatValue(remotePlayerId)} notifyMirror={notifyMirror}");

            if (notifyMirror)
            {
                NotifyServerDisconnected(connectionId);
                IGPLog.Info(
                    "mirror-transport",
                    path,
                    $"server_disconnected_notified connectionId={connectionId}");
            }
        }

        private void NotifyServerConnected(int connectionId, string remotePlayerId, string path)
        {
#if IGP_MIRROR_HAS_SERVER_CONNECTED_WITH_ADDRESS
            OnServerConnectedWithAddress?.Invoke(connectionId, remotePlayerId);
#else
#pragma warning disable CS0618
            OnServerConnected?.Invoke(connectionId);
#pragma warning restore CS0618
#endif
            IGPLog.Info(
                "mirror-transport",
                path,
                $"server_connected_notified connectionId={connectionId} remote={FormatValue(remotePlayerId)}");
        }

        private static float Now => Time.unscaledTime;

        private IGPNetworkResult SendReliablePayload(string remotePlayerId, byte[] payload)
        {
            if (runtimeManager?.Network == null) return IGPNetworkResult.kErrorInvalidState;
            return runtimeManager.Network.SendReliableData(runtimeManager.PlayerId, remotePlayerId,payload,(uint)payload.Length,MirrorReliableChannelMessageType);
        }
        private TransportError lastSendError = TransportError.InvalidSend;
        private void FailReliablePeer(string player, TransportError error, string reason) {
            if (connectedServerPlayerId==player) CompleteClientDisconnect(false,"DeliveryFailure",()=> {
                TrySendPeerLifecycle(player,IGPMirrorPeerProtocol.DisconnectMessageType,new byte[]{1},"DeliveryFailure");
                NotifyClientError(error,reason);
            });
            if(playerIdToConnectionId.TryGetValue(player,out int connection)) {
                RemoveServerConnection(connection,player,false,"DeliveryFailure");
                TrySendPeerLifecycle(player,IGPMirrorPeerProtocol.DisconnectMessageType,new byte[]{1},"DeliveryFailure");
                try { NotifyServerError(connection,error,reason); } finally { NotifyServerDisconnected(connection); }
            }
        }
        private void HandleDeliveryError(IGPMultiplayerErrorEvent error)
        {
            if (error.Source != "delivery" || !error.IsTerminal || string.IsNullOrEmpty(error.TargetPlayerId)) return;
            FailReliablePeer(error.TargetPlayerId!, error.Message == "CONGESTION" ? TransportError.Congestion :
                error.Stage == "receive" ? TransportError.InvalidReceive : TransportError.InvalidSend, error.Code);
        }
        private static double ElapsedSeconds(long startedAt, long now) =>
            Math.Max(0, now - startedAt) / (double)System.Diagnostics.Stopwatch.Frequency;

        private IGPNetworkResult TrySendPayload(string remotePlayerId, byte[] payload, int channelId, string path)
        {
            var sendDiagnostics = PayloadSendDiagnostics.NotAttempted(payload.Length);
            if (channelId != Channels.Unreliable)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    "event=invalid-send-path reason=reliable-bypassed-direct-submit");
                return IGPNetworkResult.kErrorInvalidState;
            }

            return TrySendUnreliable(
                remotePlayerId,
                MirrorUnreliableChannelMessageType,
                payload,
                AppendPath(path, "TrySendUnreliable"),
                sendDiagnostics);
        }

        private IGPNetworkResult TrySendPeerLifecycle(
            string remotePlayerId,
            uint messageType,
            byte[] payload,
            string path,
            PayloadSendDiagnostics sendDiagnostics = default)
        {
            sendDiagnostics = sendDiagnostics.EnsureOriginalBytes(payload.Length);
            if (string.IsNullOrWhiteSpace(remotePlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed reason=empty_remote message={DescribeMessageType(messageType)} bytes={payload.Length}");
                return IGPNetworkResult.kErrorInvalidState;
            }

            if (!TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: true) ||
                runtimeManager?.Network == null)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed reason=runtime_unavailable target={FormatValue(remotePlayerId)} " +
                    $"message={DescribeMessageType(messageType)} bytes={payload.Length}");
                return IGPNetworkResult.kErrorInvalidState;
            }

            if (!runtimeManager.IsReliableConnected)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed reason=reliable_not_connected target={FormatValue(remotePlayerId)} " +
                    $"message={DescribeMessageType(messageType)} bytes={payload.Length}");
                return IGPNetworkResult.kErrorNetworkError;
            }

            var safePayload = payload.Length == 0 ? new byte[] { 0 } : payload;
            var result = runtimeManager.Network.SendReliableData(
                runtimeManager.PlayerId,
                remotePlayerId,
                safePayload,
                (uint)safePayload.Length,
                messageType);
            if (result == IGPNetworkResult.kSuccess)
            {
                ObserveLargePayload(
                    "send",
                    messageType,
                    sendDiagnostics.OriginalBytes,
                    safePayload.Length,
                    remotePlayerId);
            }
            IGPLogLevel messageLevel = ResolvePayloadSendLogLevel(result, messageType, sendDiagnostics, safePayload.Length);
            if (messageLevel != IGPLogLevel.Debug && ShouldLog(messageLevel))
            {
                LogAtLevel(
                    messageLevel,
                    path,
                    FormatPayloadSendLogMessage(
                        runtimeManager.PlayerId,
                        remotePlayerId,
                        messageType,
                        ResolveReliableTransportName(),
                        safePayload,
                        result,
                        sendDiagnostics));
            }

            return result;
        }

        private IGPNetworkResult TrySendUnreliable(
            string remotePlayerId,
            uint messageType,
            byte[] payload,
            string path,
            PayloadSendDiagnostics sendDiagnostics = default)
        {
            sendDiagnostics = sendDiagnostics.EnsureOriginalBytes(payload.Length);
            if (string.IsNullOrWhiteSpace(remotePlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed reason=empty_remote message={DescribeMessageType(messageType)} bytes={payload.Length}");
                return IGPNetworkResult.kErrorInvalidState;
            }

            if (!TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: true) ||
                runtimeManager?.Network == null)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"failed reason=runtime_unavailable target={FormatValue(remotePlayerId)} " +
                    $"message={DescribeMessageType(messageType)} bytes={payload.Length}");
                return IGPNetworkResult.kErrorInvalidState;
            }

            if (!runtimeManager.IsUnreliableUdpConnected)
            {
                if (!udpUnavailableWarningEmitted)
                {
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"unavailable reason=udp_unreliable_not_ready logicalChannel=unreliable " +
                        $"target={FormatValue(remotePlayerId)} " +
                        $"message={DescribeMessageType(messageType)} bytes={payload.Length}");
                    udpUnavailableWarningEmitted = true;
                }

                return IGPNetworkResult.kErrorServiceNotAvailable;
            }

            udpUnavailableWarningEmitted = false;
            var safePayload = payload.Length == 0 ? new byte[] { 0 } : payload;
            IGPNetworkResult result = runtimeManager.Network.SendUnreliableData(
                runtimeManager.PlayerId,
                remotePlayerId,
                safePayload,
                (uint)safePayload.Length,
                messageType);
            const string effectiveTransport = "udp";
            if (result == IGPNetworkResult.kSuccess)
            {
                ObserveLargePayload(
                    "send",
                    messageType,
                    sendDiagnostics.OriginalBytes,
                    safePayload.Length,
                    remotePlayerId);
            }
            IGPLogLevel messageLevel = ResolvePayloadSendLogLevel(result, messageType, sendDiagnostics, safePayload.Length);
            if (messageLevel != IGPLogLevel.Debug && ShouldLog(messageLevel))
            {
                LogAtLevel(
                    messageLevel,
                    path,
                    FormatPayloadSendLogMessage(
                        runtimeManager.PlayerId,
                        remotePlayerId,
                        messageType,
                        effectiveTransport,
                        safePayload,
                        result,
                        sendDiagnostics));
            }

            return result;
        }

        private bool EnsureDataPlaneReady(string path)
        {
            return TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: false) &&
                runtimeManager?.IsRealtimeReady == true;
        }

        private bool TryBindRuntime(string path = "TryBindRuntime", bool logFailure = false)
        {
            if (runtimeBound && runtimeManager != null && runtimeManager.Network != null)
            {
                return true;
            }

            if (runtimeManager == null)
            {
                var candidates = FindObjectsByType<IGPMultiplayerRuntime>(FindObjectsSortMode.None);
                if (candidates.Length == 1)
                {
                    runtimeManager = candidates[0];
                }
                else
                {
                    if (logFailure)
                    {
                        IGPLog.Error(
                            "mirror-transport",
                            path,
                            $"failed reason=runtime_binding_ambiguous count={candidates.Length}; assign Runtime explicitly");
                    }
                    return false;
                }
            }
            if (runtimeManager?.Network == null)
            {
                if (logFailure)
                {
                    IGPLog.Warning(
                        "mirror-transport",
                        path,
                        $"failed reason=runtime_or_network_missing runtimeManagerAssigned={runtimeManager != null}");
                }

                return false;
            }

            if (!runtimeBound)
            {
                runtimeBackend = (IIGPMultiplayerTransportBackend)runtimeManager;
                runtimeBackend.DataReceived += HandleNetworkData;
                runtimeBackend.PeerActivity += HandlePeerActivity;
                runtimeManager.PeerRetired += HandlePeerRetired;
                runtimeManager.ErrorOccurred += HandleDeliveryError;
                runtimeBackend.ConnectionChanged += HandleRealtimeConnectionStateChanged;
                runtimeManager.RegisterMirrorShutdown(this, HasMirrorSession, Shutdown);
                backendWasReady = runtimeBackend.IsReady;
                runtimeBound = true;
                IGPLog.Debug(
                    "mirror-transport",
                    path,
                    $"bound playerId={FormatValue(runtimeManager.PlayerId)} eventOnlyReceive=true");
            }

            return true;
        }

        private void UnbindRuntime(string path)
        {
            runtimeManager?.UnregisterMirrorShutdown(this);
            if (!runtimeBound || runtimeManager == null)
            {
                IGPLog.Debug(
                    "mirror-transport",
                    path,
                    $"skipped runtimeBound={runtimeBound} runtimeAvailable={runtimeManager?.Network != null}");
                runtimeBound = false;
                return;
            }

            if (runtimeBackend != null)
            {
                runtimeBackend.DataReceived -= HandleNetworkData;
                runtimeBackend.PeerActivity -= HandlePeerActivity;
                runtimeManager.PeerRetired -= HandlePeerRetired;
                runtimeManager.ErrorOccurred -= HandleDeliveryError;
                runtimeBackend.ConnectionChanged -= HandleRealtimeConnectionStateChanged;
            }
            runtimeBackend = null;
            backendWasReady = false;
            runtimeBound = false;
            IGPLog.Debug(
                "mirror-transport",
                path,
                "unbound");
        }

        private void HandleRealtimeConnectionStateChanged(IGPRealtimeConnectionState state)
        {
            if (state == IGPRealtimeConnectionState.Ready)
            {
                if (string.IsNullOrEmpty(mirrorMatchId)) mirrorMatchId = runtimeManager?.MirrorMatchId ?? string.Empty;
                backendWasReady = true;
                realtimeConnectionFailureHandled = false;
                return;
            }

            if (!backendWasReady)
            {
                return;
            }

            backendWasReady = false;

            bool hasClientState = !string.IsNullOrWhiteSpace(connectedServerPlayerId);
            bool hasServerState = connectionIdToPlayerId.Count > 0;
            bool hasPendingClient = !string.IsNullOrWhiteSpace(pendingClientAddress);
            bool hasQueuedMessages;
            lock (queueLock)
            {
                hasQueuedMessages = messageQueue.Count > 0 || peerLifecycleQueue.Count > 0;
            }


            if (!hasClientState && !hasServerState && !hasPendingClient && !hasQueuedMessages)
            {
                return;
            }

            const string path = "HandleRealtimeConnectionStateChanged";
            if (!realtimeConnectionFailureHandled)
            {
                realtimeConnectionFailureHandled = true;
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    "disconnecting reason=realtime_connection_failed");
            }

            bool failed = state != IGPRealtimeConnectionState.Idle && state != IGPRealtimeConnectionState.WaitingForRoom;
            var disconnected = new List<KeyValuePair<int,string>>(connectionIdToPlayerId);
            foreach(var entry in disconnected) RemoveServerConnection(entry.Key,entry.Value,false,path);
            ClearQueuedMessages();
            try {
                if (hasClientState || hasPendingClient)
                    CompleteClientDisconnect(false,path,failed ? ()=>NotifyClientError(TransportError.ConnectionClosed,"Reliable Game connection ended.") : (Action?)null);
            } catch(Exception ex) { IGPLog.Error("mirror-transport",path,ex.GetType().Name); }
            foreach(var entry in disconnected) {
                try { try { if(failed) NotifyServerError(entry.Key,TransportError.ConnectionClosed,"Reliable Game connection ended."); } finally { NotifyServerDisconnected(entry.Key); } }
                catch(Exception ex) { IGPLog.Error("mirror-transport",path,ex.GetType().Name); }
            }
        }

        private void ObserveRuntimeConnectionState()
        {
            if (runtimeManager != null)
            {
                HandleRealtimeConnectionStateChanged(runtimeManager.RealtimeConnectionState);
            }
        }

        private void CheckClientPeerSilence()
        {
            if (!ClientConnected() || clientLastInboundFromHostAt <= 0f)
            {
                return;
            }

            float timeoutSeconds = PeerSilenceTimeoutSeconds;
            if (Now - clientLastInboundFromHostAt <= timeoutSeconds)
            {
                return;
            }

            string serverPlayerId = connectedServerPlayerId ?? string.Empty;
            IGPLog.Error(
                "mirror-transport",
                "CheckClientPeerSilence",
                $"disconnecting reason=host_inbound_silence timeoutSeconds={timeoutSeconds:F0} " +
                $"server={FormatValue(serverPlayerId)}");
            if (!string.IsNullOrWhiteSpace(serverPlayerId))
            {
                runtimeManager?.Network?.CloseSession(runtimeManager.PlayerId, serverPlayerId);
            }

            CompleteClientDisconnect(
                sendDisconnectPacket: false,
                "CheckClientPeerSilence->CompleteClientDisconnect");
        }

        private void CheckServerPeerSilence()
        {
            if (!serverActive || connectionIdToPlayerId.Count == 0)
            {
                return;
            }

            float now = Now;
            float timeoutSeconds = PeerSilenceTimeoutSeconds;
            foreach (var entry in new List<KeyValuePair<int, string>>(connectionIdToPlayerId))
            {
                if (!serverLastInboundByPlayerId.TryGetValue(entry.Value, out var lastInboundAt) ||
                    lastInboundAt <= 0f ||
                    now - lastInboundAt <= timeoutSeconds)
                {
                    continue;
                }

                IGPLog.Error(
                    "mirror-transport",
                    "CheckServerPeerSilence",
                    $"disconnecting reason=peer_inbound_silence timeoutSeconds={timeoutSeconds:F0} " +
                    $"connectionId={entry.Key} remote={FormatValue(entry.Value)}");
                runtimeManager?.Network?.CloseSession(runtimeManager.PlayerId, entry.Value);
                RemoveServerConnection(
                    entry.Key,
                    entry.Value,
                    notifyMirror: true,
                    "CheckServerPeerSilence->RemoveServerConnection");
            }
        }

        private void HandlePeerRetired(string playerId)
        {
            RemoveQueuedMessagesForPeer(playerId);
            FailReliablePeer(playerId,TransportError.ConnectionClosed,"Peer Game connection ended.");
        }

        private void HandlePeerActivity(IGPPeerActivity activity)
        {
            if (!IsTransportMessageType(activity.message_type))
            {
                return;
            }

            string remotePlayerId = activity.remote_peer.id;
            if (string.IsNullOrWhiteSpace(remotePlayerId))
            {
                return;
            }

            float now = Now;
            if (serverActive && playerIdToConnectionId.ContainsKey(remotePlayerId))
            {
                serverLastInboundByPlayerId[remotePlayerId] = now;
            }

            if (ClientConnected() && IsMessageFromCurrentServer(remotePlayerId))
            {
                clientLastInboundFromHostAt = now;
            }
        }

        private void HandleNetworkData(IGPDataReceived data)
        {
            const string path = "HandleNetworkData";
            string remotePlayerId = data.remote_peer.id ?? string.Empty;
            if (!IsTransportMessageType(data.message_type))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"ignored reason=non_transport_message remote={FormatValue(remotePlayerId)} " +
                    $"messageType={data.message_type} bytes={(data.data != null ? data.data.Length : 0)}");
                return;
            }

            var payload = data.data != null ? (byte[])data.data.Clone() : Array.Empty<byte>();
            var queuedMessage = new QueuedMessage
            {
                RemotePlayerId = remotePlayerId,
                MessageType = data.message_type,
                Payload = payload,
                EnqueuedAt = Now,
            };
            bool disconnectReliablePeer = false;
            bool droppedUnreliable = false;
            lock (queueLock)
            {
                if (!IsDataPlaneMessageType(data.message_type))
                {
                    if (peerLifecycleQueue.Count < MaxPeerLifecycleQueuedMessages &&
                        queuedPeerLifecycleBytes + payload.Length <= MaxPeerLifecycleQueuedMessageBytes)
                    {
                        peerLifecycleQueue.Enqueue(queuedMessage);
                        queuedPeerLifecycleBytes += payload.Length;
                    }
                    else
                    {
                        reliableOverflowDisconnects += 1;
                        disconnectReliablePeer = true;
                    }
                }
                else
                {
                    queuedUsageByPlayerId.TryGetValue(remotePlayerId, out var peerUsage);
                    bool exceedsLimit = messageQueue.Count + 1 > MaxQueuedMessages ||
                        queuedMessageBytes + payload.Length > MaxQueuedMessageBytes ||
                        peerUsage.Messages + 1 > MaxQueuedMessagesPerPeer ||
                        peerUsage.Bytes + payload.Length > MaxQueuedMessageBytesPerPeer;
                    if (!exceedsLimit)
                    {
                        messageQueue.Enqueue(queuedMessage);
                        queuedMessageBytes += payload.Length;
                        peerUsage.Messages += 1;
                        peerUsage.Bytes += payload.Length;
                        queuedUsageByPlayerId[remotePlayerId] = peerUsage;
                    }
                    else if (IsReliableDataPlaneMessageType(data.message_type))
                    {
                        reliableOverflowDisconnects += 1;
                        disconnectReliablePeer = true;
                    }
                    else
                    {
                        droppedUnreliableMessages += 1;
                        droppedUnreliable = true;
                    }
                }
            }

            if (droppedUnreliable)
            {

                anomalyLogLimiter.ObserveEvent(
                    "mirror-inbound-unreliable-dropped",
                    Now,
                    () => $"inbound_dropped reason=queue_full channel=unreliable remote={FormatValue(remotePlayerId)} " +
                          $"bytes={payload.Length} droppedTotal={droppedUnreliableMessages}",
                    message => IGPLog.Warning("mirror-transport", path, message));
            }
            if (disconnectReliablePeer)
            {
                anomalyLogLimiter.ObserveEvent(
                    "mirror-inbound-reliable-overflow",
                    Now,
                    () => $"disconnecting reason=reliable_inbound_queue_overflow remote={FormatValue(remotePlayerId)} " +
                          $"bytes={payload.Length} disconnectsTotal={reliableOverflowDisconnects}",
                    message => IGPLog.Error("mirror-transport", path, message));
                DisconnectPeerForInboundOverflow(remotePlayerId, AppendPath(path, "QueueOverflow"));
            }
        }

        private void DecrementPeerQueueUsage(string remotePlayerId, int bytes)
        {
            if (!queuedUsageByPlayerId.TryGetValue(remotePlayerId, out var usage))
            {
                return;
            }

            usage.Messages = Math.Max(0, usage.Messages - 1);
            usage.Bytes = Math.Max(0, usage.Bytes - bytes);
            if (usage.Messages == 0)
            {
                queuedUsageByPlayerId.Remove(remotePlayerId);
            }
            else
            {
                queuedUsageByPlayerId[remotePlayerId] = usage;
            }
        }

        private void RemoveQueuedMessagesForPeer(string remotePlayerId)
        {
            if (string.IsNullOrWhiteSpace(remotePlayerId))
            {
                return;
            }

            lock (queueLock)
            {
                RemoveQueuedMessagesForPeerLocked(remotePlayerId);
            }

        }

        private void RemoveQueuedMessagesForPeerLocked(string remotePlayerId)
        {
            int payloadCount = messageQueue.Count;
            for (int i = 0; i < payloadCount; i++)
            {
                QueuedMessage item = messageQueue.Dequeue();
                if (string.Equals(item.RemotePlayerId, remotePlayerId, StringComparison.Ordinal))
                {
                    int bytes = item.Payload?.Length ?? 0;
                    queuedMessageBytes = Math.Max(0, queuedMessageBytes - bytes);
                    DecrementPeerQueueUsage(remotePlayerId, bytes);
                }
                else
                {
                    messageQueue.Enqueue(item);
                }
            }

            int peerLifecycleCount = peerLifecycleQueue.Count;
            for (int i = 0; i < peerLifecycleCount; i++)
            {
                QueuedMessage item = peerLifecycleQueue.Dequeue();
                if (!string.Equals(item.RemotePlayerId, remotePlayerId, StringComparison.Ordinal))
                {
                    peerLifecycleQueue.Enqueue(item);
                }
                else
                {
                    queuedPeerLifecycleBytes = Math.Max(
                        0,
                        queuedPeerLifecycleBytes - (item.Payload?.Length ?? 0));
                }
            }
        }

        private void DisconnectPeerForInboundOverflow(string remotePlayerId, string path)
        {

            RemoveQueuedMessagesForPeer(remotePlayerId);
            FailReliablePeer(remotePlayerId, TransportError.Congestion, "Mirror receive capacity exceeded.");
        }

        private void ClearQueuedMessages()
        {
            lock (queueLock)
            {
                if (messageQueue.Count > 0 || peerLifecycleQueue.Count > 0 ||
                    queuedMessageBytes > 0 || queuedPeerLifecycleBytes > 0)
                {
                    IGPLog.Debug(
                        "mirror-transport",
                        "ClearQueuedMessages",
                        $"cleared pending={messageQueue.Count + peerLifecycleQueue.Count} " +
                        $"bytes={queuedMessageBytes + queuedPeerLifecycleBytes}");
                }

                messageQueue.Clear();
                peerLifecycleQueue.Clear();
                queuedUsageByPlayerId.Clear();
                queuedMessageBytes = 0;
                queuedPeerLifecycleBytes = 0;
                nextQueueDepthWarningAt = 0f;
            }



            anomalyLogLimiter.Reset();
        }

        private void ObserveLargePayload(
            string direction,
            uint messageType,
            int originalBytes,
            int wireBytes,
            string remotePlayerId)
        {
            if (!ShouldLog(IGPLogLevel.Warning))
            {
                anomalyLogLimiter.Reset();
                return;
            }

            if (!IsLargePayloadSummaryCandidate(messageType, originalBytes, wireBytes))
            {
                return;
            }

            anomalyLogLimiter.ObserveEvent(
                $"large-payload-{direction}",
                Now,
                () => $"direction={direction} remote={FormatValue(remotePlayerId)} " +
                      $"message={DescribeMessageType(messageType)} originalBytes={originalBytes} wireBytes={wireBytes} " +
                      $"thresholdBytes={IGPNetworkAnomalyThresholds.LargeReliablePayloadBytes}",
                message => IGPLog.Warning(
                    "mirror-transport",
                    "ObserveLargePayload",
                    message));
        }

        private static bool IsTransportMessageType(uint messageType)
        {
            return messageType == IGPMirrorPeerProtocol.ConnectRequestMessageType ||
                   messageType == IGPMirrorPeerProtocol.ConnectAcceptMessageType ||
                   messageType == IGPMirrorPeerProtocol.DisconnectMessageType ||
                   messageType == MirrorReliableApplicationFrameMessageType ||
                   messageType == MirrorReliableChannelMessageType ||
                   messageType == MirrorUnreliableChannelMessageType ||
                   messageType == MirrorCompressedReliableChannelMessageType ||
                   messageType == MirrorCompressedUnreliableChannelMessageType;
        }



        private static bool IsReliableDataPlaneMessageType(uint messageType)
        {
            return messageType == MirrorReliableChannelMessageType ||
                   messageType == MirrorCompressedReliableChannelMessageType ||
                   messageType == MirrorReliableApplicationFrameMessageType;
        }

        private static bool IsDataPlaneMessageType(uint messageType)
        {
            return IsReliableDataPlaneMessageType(messageType) ||
                   messageType == MirrorUnreliableChannelMessageType ||
                   messageType == MirrorCompressedUnreliableChannelMessageType;
        }

        private static int GetMirrorChannel(uint messageType)
        {
            return messageType == MirrorUnreliableChannelMessageType ||
                   messageType == MirrorCompressedUnreliableChannelMessageType
                ? Channels.Unreliable
                : Channels.Reliable;
        }

        private bool IsDuplicateConnectedAccept(
            string serverPlayerId,
            int acceptedConnectionId,
            Guid? acceptedAttemptId)
        {
            if (!string.Equals(connectedServerPlayerId, serverPlayerId, StringComparison.Ordinal) ||
                clientConnectionId != acceptedConnectionId)
            {
                return false;
            }

            return !acceptedAttemptId.HasValue ||
                   !connectedClientConnectAttemptId.HasValue ||
                   acceptedAttemptId.Value == connectedClientConnectAttemptId.Value;
        }

        private bool TryPrepareIncomingMirrorPayload(
            QueuedMessage message, int? connectionId, string path, out byte[] payload, out int channel)
        {
            channel = GetMirrorChannel(message.MessageType);
            payload = message.Payload;
            bool raw = message.MessageType == MirrorReliableChannelMessageType || message.MessageType == MirrorUnreliableChannelMessageType;
            int limit = channel == Channels.Reliable ? ReliablePacketMaxBytes : ResolveUnreliablePacketMaxBytes();
            if (raw && payload.Length > 0 && payload.Length <= limit)
            {
                runtimeManager?.ObserveMirrorMessageReceived();
                return true;
            }
            IGPLog.Error("mirror-transport", path,
                $"event=receive-rejected reason=invalid-raw-payload messageType={message.MessageType} bytes={payload.Length} limit={limit}");
            FailReliablePeer(message.RemotePlayerId,TransportError.InvalidReceive,"Invalid raw Mirror payload.");
            return false;
        }

        private uint GetLocalConnectCapabilities()
        {
            return IGPMirrorPeerProtocol.CapabilityRawReliable256KiB;
        }

        private static bool HasCapability(uint capabilities, uint capability)
        {
            return (capabilities & capability) == capability;
        }

        private static string FormatAttemptId(Guid? connectAttemptId)
        {
            return connectAttemptId.HasValue ? connectAttemptId.Value.ToString("N") : "none";
        }

        private string ResolveServerPlayerId(string address)
        {
            if (runtimeManager == null)
            {
                return string.Empty;
            }

            if (string.IsNullOrWhiteSpace(address) ||
                string.Equals(address, "host", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(address, "localhost", StringComparison.OrdinalIgnoreCase))
            {
                return runtimeManager.CurrentPeerContext?.HostPlayerId ?? string.Empty;
            }

            return address.Trim();
        }

        private string FormatPayloadSendLogMessage(
            string localPlayerId,
            string remotePlayerId,
            uint messageType,
            string effectiveTransport,
            byte[] safePayload,
            IGPNetworkResult result,
            PayloadSendDiagnostics sendDiagnostics)
        {
            int wireBytes = safePayload.Length;
            int originalBytes = sendDiagnostics.OriginalBytes;
            string eventName = IsDataPlaneMessageType(messageType) ? "payload-send" : "peer-lifecycle-send";

            return $"event={eventName} direction=send local={FormatValue(localPlayerId)} " +
                   $"target={FormatValue(remotePlayerId)} message={DescribeMessageType(messageType)} " +
                   $"messageType={messageType} logicalChannel={DescribeMessageChannel(messageType)} " +
                   $"effectiveTransport={effectiveTransport} originalBytes={originalBytes} " +
                   $"wireBytes={wireBytes} bytes={wireBytes} " +
                   $"large={IsLargePayloadSummaryCandidate(messageType, originalBytes, wireBytes)} " +
                   $"result={result}";
        }



        private static IGPLogLevel ResolvePayloadSendLogLevel(
            IGPNetworkResult result,
            uint messageType,
            PayloadSendDiagnostics sendDiagnostics,
            int wireBytes)
        {
            if (result != IGPNetworkResult.kSuccess)
            {
                return IGPLogLevel.Warning;
            }

            if (IsConnectionLifecycleMessageType(messageType))
            {
                return IGPLogLevel.Info;
            }

            return IGPLogLevel.Debug;
        }

        private static bool IsLargePayloadSummaryCandidate(uint messageType, int originalBytes, int wireBytes)
        {
            return IsReliableDataPlaneMessageType(messageType) &&
                   (originalBytes > IGPNetworkAnomalyThresholds.LargeReliablePayloadBytes ||
                    wireBytes > IGPNetworkAnomalyThresholds.LargeReliablePayloadBytes);
        }

        private static bool IsConnectionLifecycleMessageType(uint messageType)
        {
            return messageType == IGPMirrorPeerProtocol.ConnectRequestMessageType ||
                   messageType == IGPMirrorPeerProtocol.ConnectAcceptMessageType ||
                   messageType == IGPMirrorPeerProtocol.DisconnectMessageType;
        }



        private string ResolveReliableTransportName()
        {
            return runtimeManager?.CurrentReliableTransport == IGPRealtimeTransport.Tcp ? "tcp" : "kcp";
        }

        private void LogConfigurationOnce(string path)
        {
            if (configurationLogged || !ShouldLog(IGPLogLevel.Info))
            {
                return;
            }

            configurationLogged = true;
            IGPLog.Info(
                "mirror-transport",
                path,
                $"event=configuration reliableBatchThresholdBytes={DefaultReliableBatchThresholdBytes} " +
                $"reliablePacketMaxBytes={ReliablePacketMaxBytes} outboundQueue=false " +
                $" compression=false  " +
                $"unreliablePacketMaxBytes={ResolveUnreliablePacketMaxBytes()}");
        }

        private bool ShouldLog(IGPLogLevel messageLevel)
        {
            return IGPLog.ShouldLog(messageLevel);
        }

        private static void LogAtLevel(IGPLogLevel level, string path, string message)
        {
            switch (level)
            {
                case IGPLogLevel.Error:
                    IGPLog.Error("mirror-transport", path, message);
                    break;
                case IGPLogLevel.Warning:
                    IGPLog.Warning("mirror-transport", path, message);
                    break;
                case IGPLogLevel.Info:
                    IGPLog.Info("mirror-transport", path, message);
                    break;
                case IGPLogLevel.Debug:
                    IGPLog.Debug("mirror-transport", path, message);
                    break;
            }
        }

        private static float NormalizePeerSilenceTimeout(float value) => Math.Max(1f, value);


        private static int NormalizeReliableBatchThreshold(int value)
        {
            return Math.Min(ReliablePacketMaxBytes, Math.Max(1, value));
        }

        private int ResolveUnreliablePacketMaxBytes()
        {
            return Math.Max(1, runtimeManager?.UnreliableUdpPayloadMaxBytes ?? DefaultUdpUnreliablePacketMaxBytes);
        }

        private static string AppendPath(string path, string next)
        {
            return string.IsNullOrWhiteSpace(path) ? next : $"{path}->{next}";
        }

        private static string FormatValue(string? value)
        {
            return string.IsNullOrWhiteSpace(value) ? "none" : value;
        }

        private static string DescribeMessageType(uint messageType)
        {
            switch (messageType)
            {
                case IGPMirrorPeerProtocol.ConnectRequestMessageType: return "ConnectRequest";
                case IGPMirrorPeerProtocol.ConnectAcceptMessageType: return "ConnectAccept";
                case IGPMirrorPeerProtocol.DisconnectMessageType: return "Disconnect";
                case MirrorReliableChannelMessageType: return "MirrorReliableChannelData";
                case MirrorUnreliableChannelMessageType: return "MirrorUnreliableChannelData";
                case MirrorCompressedReliableChannelMessageType: return "MirrorCompressedReliableChannelData";
                case MirrorCompressedUnreliableChannelMessageType: return "MirrorCompressedUnreliableChannelData";
                case MirrorReliableApplicationFrameMessageType: return "MirrorReliableApplicationFrameV1";
                default: return $"Unknown({messageType})";
            }
        }

        private static string DescribeMessageChannel(uint messageType)
        {
            return IsDataPlaneMessageType(messageType)
                ? DescribeChannel(GetMirrorChannel(messageType))
                : "mirror-peer-lifecycle";
        }

        private static string DescribeChannel(int channelId)
        {
            return channelId == Channels.Unreliable ? "unreliable" : "reliable";
        }

        private static int NormalizeChannel(int channelId)
        {
            return channelId == Channels.Unreliable ? Channels.Unreliable : Channels.Reliable;
        }

        private static byte[] CopySegment(ArraySegment<byte> segment)
        {
            var buffer = new byte[segment.Count];
            if (segment.Count > 0 && segment.Array != null)
            {
                Buffer.BlockCopy(segment.Array, segment.Offset, buffer, 0, segment.Count);
            }

            return buffer;
        }
    }
}
