#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.Multiplayer.IGPMultiplayerLog;
using IGPLogLevel = IGP.Multiplayer.IGPMultiplayerLogLevel;

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 = 512 * 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 = 2 * 1024;
        private const float DefaultMinCompressionRatio = 0.90f;
        private const int DefaultReliableBatchThresholdBytes = 1024;
        private const int MaxOutboundMessagesPerPeer = 1024;
        private const int MaxOutboundBytesPerPeer = 4 * 1024 * 1024;
        private const double MaxOutboundAgeSeconds = 15.0;
        private const int MinReliableSendRate = 1;
        private const int MaxReliableSendRate = 60;
        private const int DefaultReliableSendRate = 30;
        private const float DefaultPeerSilenceTimeoutSeconds = 300f;
        private const float SuppressedLogIntervalSeconds = 5f;
        private const int MessageLogHexPreviewMaxBytes = 64;
        private const int EstimatedReliableDataPlanePayloadMaxBytes = 12 * 1024;
        private const int EstimatedReliableChunkMaxBytes = 11_520;

        [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 = true;
        [HideInInspector, SerializeField] private int compressionThresholdBytes = DefaultCompressionThresholdBytes;
        [HideInInspector, SerializeField] private float minCompressionRatio = DefaultMinCompressionRatio;

        [Header("Batching")]
        [Tooltip("Use SDK UDP for the Mirror unreliable channel. Unavailable UDP packets are dropped and never fall back to the reliable transport.")]
        [SerializeField] private bool useRawUdpUnreliableLane = true;
        [Tooltip("Reliable application frames sent per second. This does not change the reliable transport tick or UDP sends.")]
        [Range(MinReliableSendRate, MaxReliableSendRate)]
        [SerializeField] private int reliableSendRate = DefaultReliableSendRate;
        [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, bool> serverPayloadCompressionByPlayerId =
            new Dictionary<string, bool>(StringComparer.Ordinal);
        private readonly object outboundQueueLock = new object();
        private readonly Dictionary<string, OutboundPeerQueue> outboundQueuesByPlayerId =
            new Dictionary<string, OutboundPeerQueue>(StringComparer.Ordinal);

        private bool runtimeBound;
        private bool realtimeConnectionFailureHandled;
        private bool backendWasReady;
        private bool udpUnavailableWarningEmitted;
        private bool serverActive;
        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 long nextApplicationFrameFlushAt;
        private long lastApplicationFrameSchedulerAt;

        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 sealed class OutboundPeerQueue
        {
            public readonly Queue<OutboundPayload> Payloads = new Queue<OutboundPayload>();
            public int Bytes;
            public PreparedApplicationFrame? PreparedFrame;
            public bool WouldBlockActive;
            public long WouldBlockSince;
            public long NextWouldBlockLogAt;
            public long NextSendFailureLogAt;
        }

        private readonly struct OutboundPayload
        {
            public OutboundPayload(byte[] payload, long enqueuedAt, bool fromClient, int connectionId)
            {
                Payload = payload;
                EnqueuedAt = enqueuedAt;
                FromClient = fromClient;
                ConnectionId = connectionId;
            }

            public byte[] Payload { get; }
            public long EnqueuedAt { get; }
            public bool FromClient { get; }
            public int ConnectionId { get; }
        }

        private sealed class PreparedApplicationFrame
        {
            public PreparedApplicationFrame(IGPMirrorApplicationFrame.EncodedFrame encoded, int payloadBytes)
            {
                Encoded = encoded;
                PayloadBytes = payloadBytes;
            }

            public IGPMirrorApplicationFrame.EncodedFrame Encoded { get; }
            public int PayloadBytes { get; }
        }

        private sealed class ReliableHeadGroup
        {
            public readonly byte[] Payload;
            public readonly List<string> PlayerIds = new List<string>();

            public ReliableHeadGroup(byte[] payload)
            {
                Payload = payload;
            }
        }

        private readonly struct PayloadSendDiagnostics
        {
            public PayloadSendDiagnostics(
                int originalBytes,
                bool compressionAttempted,
                bool compressionAccepted,
                IGPMirrorPayloadCompression.Diagnostics compression)
            {
                OriginalBytes = originalBytes;
                CompressionAttempted = compressionAttempted;
                CompressionAccepted = compressionAccepted;
                Compression = compression;
            }

            public int OriginalBytes { get; }
            public bool CompressionAttempted { get; }
            public bool CompressionAccepted { get; }
            public IGPMirrorPayloadCompression.Diagnostics Compression { get; }

            public static PayloadSendDiagnostics NotAttempted(int originalBytes)
            {
                return new PayloadSendDiagnostics(originalBytes, false, false, default);
            }

            public PayloadSendDiagnostics EnsureOriginalBytes(int fallbackBytes)
            {
                return 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("Reliable application frames always select compression automatically. This setting no longer changes behavior.")]
        public bool EnablePayloadCompression
        {
            get => true;
            set => enablePayloadCompression = value;
        }

        [Obsolete("Reliable application frames always select compression automatically. This setting no longer changes behavior.")]
        public int CompressionThresholdBytes
        {
            get => DefaultCompressionThresholdBytes;
            set => compressionThresholdBytes = value;
        }

        [Obsolete("Reliable application frames always select compression automatically. This setting no longer changes behavior.")]
        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 bool UseRawUdpUnreliableLane
        {
            get => useRawUdpUnreliableLane;
            set
            {
                if (useRawUdpUnreliableLane != value)
                {
                    udpUnavailableWarningEmitted = false;
                }

                useRawUdpUnreliableLane = value;
            }
        }

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

        /// <summary>
        /// Reliable application-frame send rate in Hz, clamped to the range 1..60.
        /// </summary>
        public int ReliableSendRate
        {
            get => NormalizeReliableSendRate(reliableSendRate);
            set
            {
                reliableSendRate = NormalizeReliableSendRate(value);
                nextApplicationFrameFlushAt = 0;
            }
        }

        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);
            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)
        {
            const string path = "ClientSend";
            int normalizedChannel = NormalizeChannel(channelId);
            if (!ClientConnected() || string.IsNullOrWhiteSpace(connectedServerPlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"rejected reason=client_not_connected channel={DescribeChannel(normalizedChannel)} " +
                    $"bytes={segment.Count} connectedServer={FormatValue(connectedServerPlayerId)}");
                OnClientError?.Invoke(TransportError.InvalidSend, "IGP client transport is not connected.");
                return;
            }

            var payload = CopySegment(segment);
            string serverPlayerId = connectedServerPlayerId!;
            if (normalizedChannel == Channels.Reliable)
            {
                if (TryEnqueueReliablePayload(serverPlayerId, payload, fromClient: true, connectionId: 0, out var queueReason))
                {
                    return;
                }

                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=outbound-queue-fault action=disconnect-peer side=client remote={FormatValue(serverPlayerId)} " +
                    $"reason={queueReason} bytes={payload.Length} limitMessages={MaxOutboundMessagesPerPeer} " +
                    $"limitBytes={MaxOutboundBytesPerPeer} maxAgeSeconds={MaxOutboundAgeSeconds:F0}");
                OnClientError?.Invoke(TransportError.InvalidSend, $"Reliable outbound queue failed: {queueReason}.");
                CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "OutboundQueueDisconnect"));
                return;
            }

            var sendResult = TrySendPayload(serverPlayerId, payload, normalizedChannel, AppendPath(path, "TrySendPayload"));
            if (sendResult != IGPNetworkResult.kSuccess)
            {
                if (normalizedChannel == Channels.Unreliable)
                {
                    droppedUnreliableSends += 1;
                    anomalyLogLimiter.ObserveEvent(
                        "mirror-outbound-unreliable-dropped",
                        Now,
                        () => $"unreliable_send_dropped reason=backpressure bytes={payload.Length} droppedTotal={droppedUnreliableSends}",
                        message => IGPLog.Warning("mirror-transport", path, message));
                    return;
                }

                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"client_error_invoked reason=send_failed result={sendResult}");
                OnClientError?.Invoke(TransportError.InvalidSend, "Failed to send Mirror payload over IGP.");
                return;
            }

            OnClientDataSent?.Invoke(new ArraySegment<byte>(payload), normalizedChannel);
        }

        public override void ClientDisconnect()
        {
            const string path = "ClientDisconnect";
            IGPLog.Debug(
                "mirror-transport",
                path,
                "called");
            CompleteClientDisconnect(sendDisconnectPacket: true, AppendPath(path, "CompleteClientDisconnect"));
        }

        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);
            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)
        {
            const string path = "ServerSend";
            int normalizedChannel = NormalizeChannel(channelId);
            if (!connectionIdToPlayerId.TryGetValue(connectionId, out var remotePlayerId))
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"rejected reason=unknown_connection connectionId={connectionId} " +
                    $"channel={DescribeChannel(normalizedChannel)} bytes={segment.Count}");
                OnServerError?.Invoke(connectionId, TransportError.InvalidSend, "Unknown IGP client connection.");
                return;
            }

            var payload = CopySegment(segment);
            if (normalizedChannel == Channels.Reliable)
            {
                if (TryEnqueueReliablePayload(remotePlayerId, payload, fromClient: false, connectionId: connectionId, out var queueReason))
                {
                    return;
                }

                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=outbound-queue-fault action=disconnect-peer side=server connectionId={connectionId} " +
                    $"remote={FormatValue(remotePlayerId)} reason={queueReason} bytes={payload.Length} " +
                    $"limitMessages={MaxOutboundMessagesPerPeer} limitBytes={MaxOutboundBytesPerPeer} " +
                    $"maxAgeSeconds={MaxOutboundAgeSeconds:F0}");
                OnServerError?.Invoke(connectionId, TransportError.InvalidSend, $"Reliable outbound queue failed: {queueReason}.");
                RemoveServerConnection(
                    connectionId,
                    remotePlayerId,
                    notifyMirror: true,
                    AppendPath(path, "OutboundQueueDisconnect"));
                return;
            }

            var sendResult = TrySendPayload(remotePlayerId, payload, normalizedChannel, AppendPath(path, "TrySendPayload"));
            if (sendResult != IGPNetworkResult.kSuccess)
            {
                if (normalizedChannel == Channels.Unreliable)
                {
                    droppedUnreliableSends += 1;
                    anomalyLogLimiter.ObserveEvent(
                        "mirror-outbound-unreliable-dropped",
                        Now,
                        () => $"unreliable_send_dropped reason=backpressure connectionId={connectionId} bytes={payload.Length} " +
                              $"droppedTotal={droppedUnreliableSends}",
                        message => IGPLog.Warning("mirror-transport", path, message));
                    return;
                }

                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"server_error_invoked reason=send_failed connectionId={connectionId} result={sendResult}");
                OnServerError?.Invoke(connectionId, TransportError.InvalidSend, "Failed to send Mirror payload over IGP.");
                return;
            }

            OnServerDataSent?.Invoke(connectionId, new ArraySegment<byte>(payload), normalizedChannel);
        }

        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 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;
            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();
            FlushReliableApplicationFrames("ServerEarlyUpdate->FlushReliableApplicationFrames");
        }

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

            TryBindRuntime();
            ObserveRuntimeConnectionState();
            FlushReliableApplicationFrames(AppendPath(path, "FlushReliableApplicationFrames"));

            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}");
                OnClientError?.Invoke(
                    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";
            IGPLog.Debug(
                "mirror-transport",
                path,
                "called");
            CompleteClientDisconnect(sendDisconnectPacket: true, AppendPath(path, "CompleteClientDisconnect"));
            ServerStop();
            ClearQueuedMessages();
            realtimeConnectionFailureHandled = false;
            UnbindRuntime(AppendPath(path, "UnbindRuntime"));
        }

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

        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 MirrorReliableApplicationFrameMessageType:
                    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 frameConnectionId))
                    {
                        IGPLog.Warning(
                            "mirror-transport",
                            path,
                            $"ignored reason=unknown_player_connection remote={FormatValue(message.RemotePlayerId)} " +
                            $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length}");
                        return;
                    }

                    if (!TryDecodeApplicationFrame(message, frameConnectionId, path, out var serverFramePayloads))
                    {
                        return;
                    }

                    serverLastInboundByPlayerId[message.RemotePlayerId] = Now;
                    runtimeManager?.ObserveMirrorApplicationFrameReceived(serverFramePayloads.Count);
                    for (int i = 0; i < serverFramePayloads.Count; i++)
                    {
                        OnServerDataReceived?.Invoke(
                            frameConnectionId,
                            new ArraySegment<byte>(serverFramePayloads[i]),
                            Channels.Reliable);
                    }
                    break;
                case MirrorReliableChannelMessageType:
                case MirrorUnreliableChannelMessageType:
                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 MirrorReliableApplicationFrameMessageType:
                    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 (!TryDecodeApplicationFrame(message, null, path, out var clientFramePayloads))
                    {
                        return;
                    }

                    clientLastInboundFromHostAt = Now;
                    runtimeManager?.ObserveMirrorApplicationFrameReceived(clientFramePayloads.Count);
                    for (int i = 0; i < clientFramePayloads.Count; i++)
                    {
                        OnClientDataReceived?.Invoke(
                            new ArraySegment<byte>(clientFramePayloads[i]),
                            Channels.Reliable);
                    }
                    break;
                case MirrorReliableChannelMessageType:
                case MirrorUnreliableChannelMessageType:
                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 remoteSupportsCompression = HasCapability(
                connectRequest.Capabilities,
                IGPMirrorPeerProtocol.CapabilityPayloadCompression);
            bool remoteSupportsApplicationFrame = HasCapability(
                connectRequest.Capabilities,
                IGPMirrorPeerProtocol.CapabilityApplicationFrameV1);
            IGPLog.Info(
                "mirror-transport",
                path,
                $"called remote={FormatValue(message.RemotePlayerId)} " +
                $"attemptId={FormatAttemptId(connectAttemptId)} bytes={message.Payload.Length} " +
                $"remoteCompression={remoteSupportsCompression} applicationFrameV1={remoteSupportsApplicationFrame}");
            if (!remoteSupportsApplicationFrame)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=logical-connect-rejected reason=missing-application-frame-v1 " +
                    $"remote={FormatValue(message.RemotePlayerId)} capabilities={connectRequest.Capabilities}");
                TrySendPeerLifecycle(
                    message.RemotePlayerId,
                    IGPMirrorPeerProtocol.DisconnectMessageType,
                    new byte[] { 2 },
                    AppendPath(path, "RejectUnsupportedPeer"));
                return;
            }

            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"));
            }

            serverPayloadCompressionByPlayerId[message.RemotePlayerId] = true;
            TrySendPeerLifecycle(
                message.RemotePlayerId,
                IGPMirrorPeerProtocol.ConnectAcceptMessageType,
                IGPMirrorPeerProtocol.EncodeConnectAccept(
                    connectionId,
                    connectAttemptId,
                    IGPMirrorPeerProtocol.CapabilityApplicationFrameV1),
                AppendPath(path, "TrySendPeerLifecycle"));
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"connect_accept_sent remote={message.RemotePlayerId} " +
                $"connectionId={connectionId} attemptId={FormatAttemptId(connectAttemptId)} " +
                $"isNewConnection={isNewConnection} applicationFrameV1=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 acceptedCompression = HasCapability(
                connectAccept.Capabilities,
                IGPMirrorPeerProtocol.CapabilityPayloadCompression);
            bool acceptedApplicationFrame = HasCapability(
                connectAccept.Capabilities,
                IGPMirrorPeerProtocol.CapabilityApplicationFrameV1);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"called server={FormatValue(message.RemotePlayerId)} connectionId={acceptedConnectionId} " +
                $"attemptId={FormatAttemptId(acceptedAttemptId)} bytes={message.Payload.Length} " +
                $"compression={acceptedCompression} applicationFrameV1={acceptedApplicationFrame}");

            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 (!acceptedApplicationFrame)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=logical-connect-rejected reason=missing-application-frame-v1 " +
                    $"server={FormatValue(message.RemotePlayerId)} capabilities={connectAccept.Capabilities}");
                OnClientError?.Invoke(
                    TransportError.InvalidReceive,
                    "IGP Mirror peer does not support ApplicationFrameV1.");
                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)} " +
                $"applicationFrameV1=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 void CompleteClientDisconnect(bool sendDisconnectPacket, string path)
        {
            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 (hadState)
            {
                OnClientDisconnected?.Invoke();
                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);
            serverPayloadCompressionByPlayerId.Remove(remotePlayerId);
            IGPLog.Debug(
                "mirror-transport",
                path,
                $"removed connectionId={connectionId} remote={FormatValue(remotePlayerId)} notifyMirror={notifyMirror}");

            if (notifyMirror)
            {
                OnServerDisconnected?.Invoke(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 bool TryEnqueueReliablePayload(
            string remotePlayerId,
            byte[] payload,
            bool fromClient,
            int connectionId,
            out string reason)
        {
            reason = string.Empty;
            long now = System.Diagnostics.Stopwatch.GetTimestamp();
            lock (outboundQueueLock)
            {
                if (!outboundQueuesByPlayerId.TryGetValue(remotePlayerId, out var queue))
                {
                    queue = new OutboundPeerQueue();
                    outboundQueuesByPlayerId.Add(remotePlayerId, queue);
                }

                if (queue.Payloads.Count > 0 &&
                    ElapsedSeconds(queue.Payloads.Peek().EnqueuedAt, now) > MaxOutboundAgeSeconds)
                {
                    reason = "oldest-payload-expired";
                    return false;
                }

                if (queue.Payloads.Count + 1 > MaxOutboundMessagesPerPeer)
                {
                    reason = "message-limit";
                    return false;
                }

                if (queue.Bytes + payload.Length > MaxOutboundBytesPerPeer)
                {
                    reason = "byte-limit";
                    return false;
                }

                queue.Payloads.Enqueue(new OutboundPayload(payload, now, fromClient, connectionId));
                queue.Bytes += payload.Length;
                runtimeManager?.ObserveMirrorApplicationFrameQueue(
                    queue.Payloads.Count,
                    queue.Bytes,
                    ElapsedSeconds(queue.Payloads.Peek().EnqueuedAt, now));

                return true;
            }
        }

        private void FlushReliableApplicationFrames(string path)
        {
            long now = System.Diagnostics.Stopwatch.GetTimestamp();
            if (lastApplicationFrameSchedulerAt != 0)
            {
                long gapTicks = now - lastApplicationFrameSchedulerAt;
                runtimeManager?.ObserveMirrorApplicationFrameSchedulerGap(
                    gapTicks / (double)System.Diagnostics.Stopwatch.Frequency);
            }
            lastApplicationFrameSchedulerAt = now;

            if (nextApplicationFrameFlushAt != 0 && now < nextApplicationFrameFlushAt)
            {
                return;
            }

            nextApplicationFrameFlushAt = now + SecondsToStopwatchTicks(1.0 / ReliableSendRate);
            if (!EnsureDataPlaneReady(path))
            {
                return;
            }

            List<string> peers;
            lock (outboundQueueLock)
            {
                peers = new List<string>(outboundQueuesByPlayerId.Keys);
            }

            HashSet<string> groupedPeers = FlushReliableBroadcastHeads(peers, now, path);

            for (int i = 0; i < peers.Count; i++)
            {
                if (!groupedPeers.Contains(peers[i]))
                {
                    FlushReliableApplicationFrameForPeer(peers[i], now, path);
                }
            }
        }

        private HashSet<string> FlushReliableBroadcastHeads(List<string> peers, long now, string path)
        {
            var handled = new HashSet<string>(StringComparer.Ordinal);
            if (runtimeManager?.UsesDataPlaneEnvelopeV1 != true || runtimeManager.Network == null)
            {
                return handled;
            }

            var candidates = new List<KeyValuePair<string, byte[]>>();
            lock (outboundQueueLock)
            {
                foreach (string playerId in peers)
                {
                    if (!outboundQueuesByPlayerId.TryGetValue(playerId, out var queue) ||
                        queue.Payloads.Count == 0 || queue.PreparedFrame != null)
                    {
                        continue;
                    }
                    OutboundPayload head = queue.Payloads.Peek();
                    if (head.FromClient || ElapsedSeconds(head.EnqueuedAt, now) > MaxOutboundAgeSeconds)
                    {
                        continue;
                    }
                    candidates.Add(new KeyValuePair<string, byte[]>(playerId, head.Payload));
                }
            }

            List<ReliableHeadGroup> groups = GroupReliableHeads(candidates);
            foreach (ReliableHeadGroup group in groups)
            {
                if (group.PlayerIds.Count < 2) continue;
                byte[] frame = IGPMirrorApplicationFrame.Encode(new[] { group.Payload }).WireData;
                IGPNetworkResult result = runtimeManager.Network.SendReliableDataToPlayers(
                    runtimeManager.PlayerId,
                    group.PlayerIds,
                    frame,
                    (uint)frame.Length,
                    MirrorReliableApplicationFrameMessageType);
                if (result == IGPNetworkResult.kErrorWouldBlock)
                {
                    foreach (string playerId in group.PlayerIds) handled.Add(playerId);
                    continue;
                }
                if (result != IGPNetworkResult.kSuccess) continue;

                var accepted = new List<OutboundPayload>(group.PlayerIds.Count);
                lock (outboundQueueLock)
                {
                    foreach (string playerId in group.PlayerIds)
                    {
                        if (!outboundQueuesByPlayerId.TryGetValue(playerId, out var queue) ||
                            queue.Payloads.Count == 0 || queue.PreparedFrame != null ||
                            !PayloadEquals(queue.Payloads.Peek().Payload, group.Payload))
                        {
                            continue;
                        }
                        OutboundPayload item = queue.Payloads.Dequeue();
                        queue.Bytes = Math.Max(0, queue.Bytes - item.Payload.Length);
                        accepted.Add(item);
                        handled.Add(playerId);
                        if (queue.Payloads.Count == 0) outboundQueuesByPlayerId.Remove(playerId);
                    }
                }
                foreach (OutboundPayload item in accepted)
                {
                    OnServerDataSent?.Invoke(item.ConnectionId, new ArraySegment<byte>(item.Payload), Channels.Reliable);
                }
            }
            return handled;
        }

        private static List<ReliableHeadGroup> GroupReliableHeads(IReadOnlyList<KeyValuePair<string, byte[]>> heads)
        {
            var groups = new List<ReliableHeadGroup>();
            for (int headIndex = 0; headIndex < heads.Count; headIndex++)
            {
                KeyValuePair<string, byte[]> head = heads[headIndex];
                ReliableHeadGroup? group = null;
                for (int groupIndex = 0; groupIndex < groups.Count; groupIndex++)
                {
                    if (PayloadEquals(groups[groupIndex].Payload, head.Value))
                    {
                        group = groups[groupIndex];
                        break;
                    }
                }
                if (group == null)
                {
                    group = new ReliableHeadGroup(head.Value);
                    groups.Add(group);
                }
                group.PlayerIds.Add(head.Key);
            }
            return groups;
        }

        private static bool PayloadEquals(byte[] left, byte[] right)
        {
            if (ReferenceEquals(left, right)) return true;
            if (left == null || right == null || left.Length != right.Length) return false;
            for (int index = 0; index < left.Length; index++)
            {
                if (left[index] != right[index]) return false;
            }
            return true;
        }

        private void FlushReliableApplicationFrameForPeer(string remotePlayerId, long now, string path)
        {
            PreparedApplicationFrame? prepared;
            lock (outboundQueueLock)
            {
                if (!outboundQueuesByPlayerId.TryGetValue(remotePlayerId, out var queue) || queue.Payloads.Count == 0)
                {
                    return;
                }

                runtimeManager?.ObserveMirrorApplicationFrameQueue(
                    queue.Payloads.Count,
                    queue.Bytes,
                    ElapsedSeconds(queue.Payloads.Peek().EnqueuedAt, now));
                if (ElapsedSeconds(queue.Payloads.Peek().EnqueuedAt, now) > MaxOutboundAgeSeconds)
                {
                    prepared = null;
                }
                else
                {
                    if (queue.PreparedFrame == null)
                    {
                        queue.PreparedFrame = BuildApplicationFrame(queue);
                        runtimeManager?.ObserveMirrorApplicationFrameCreated(
                            queue.PreparedFrame.Encoded.PayloadCount,
                            queue.PreparedFrame.Encoded.RawBytes,
                            queue.PreparedFrame.Encoded.WireData.Length,
                            queue.PreparedFrame.Encoded.Compressed);
                    }

                    prepared = queue.PreparedFrame;
                }
            }

            if (prepared == null)
            {
                DisconnectPeerForOutboundQueueFault(remotePlayerId, "oldest-payload-expired", path);
                return;
            }

            IGPNetworkResult result = TrySendApplicationFrame(remotePlayerId, prepared.Encoded.WireData, path);
            if (result == IGPNetworkResult.kErrorWouldBlock)
            {
                ObserveApplicationFrameWouldBlock(remotePlayerId, now, prepared, path);
                return;
            }

            if (result != IGPNetworkResult.kSuccess)
            {
                ObserveApplicationFrameSendFailure(remotePlayerId, now, prepared, result, path);
                return;
            }

            var acceptedPayloads = new List<OutboundPayload>(prepared.Encoded.PayloadCount);
            double blockedSeconds = 0;
            lock (outboundQueueLock)
            {
                if (!outboundQueuesByPlayerId.TryGetValue(remotePlayerId, out var queue) ||
                    !ReferenceEquals(queue.PreparedFrame, prepared))
                {
                    return;
                }

                if (queue.WouldBlockActive)
                {
                    blockedSeconds = ElapsedSeconds(queue.WouldBlockSince, now);
                }

                for (int i = 0; i < prepared.Encoded.PayloadCount; i++)
                {
                    OutboundPayload item = queue.Payloads.Dequeue();
                    queue.Bytes = Math.Max(0, queue.Bytes - item.Payload.Length);
                    acceptedPayloads.Add(item);
                }

                queue.PreparedFrame = null;
                queue.WouldBlockActive = false;
                queue.WouldBlockSince = 0;
                queue.NextWouldBlockLogAt = 0;
                queue.NextSendFailureLogAt = 0;
                if (queue.Payloads.Count == 0)
                {
                    outboundQueuesByPlayerId.Remove(remotePlayerId);
                }
            }

            if (blockedSeconds > 0)
            {
                IGPLog.Info(
                    "mirror-transport",
                    path,
                    $"event=application-frame-backpressure-recovered remote={FormatValue(remotePlayerId)} " +
                    $"blockedSeconds={blockedSeconds:F3} payloads={prepared.Encoded.PayloadCount} " +
                    $"wireBytes={prepared.Encoded.WireData.Length}");
            }

            for (int i = 0; i < acceptedPayloads.Count; i++)
            {
                OutboundPayload item = acceptedPayloads[i];
                if (item.FromClient)
                {
                    OnClientDataSent?.Invoke(new ArraySegment<byte>(item.Payload), Channels.Reliable);
                }
                else
                {
                    OnServerDataSent?.Invoke(item.ConnectionId, new ArraySegment<byte>(item.Payload), Channels.Reliable);
                }
            }
        }

        private static PreparedApplicationFrame BuildApplicationFrame(OutboundPeerQueue queue)
        {
            var payloads = new List<byte[]>();
            int rawBodyBytes = 0;
            int payloadBytes = 0;
            int normalBodyLimit = EstimatedReliableChunkMaxBytes - IGPMirrorApplicationFrame.HeaderBytes;
            foreach (OutboundPayload item in queue.Payloads)
            {
                int nextBodyBytes = checked(rawBodyBytes + IGPMirrorApplicationFrame.PayloadLengthBytes + item.Payload.Length);
                if (payloads.Count > 0 && nextBodyBytes > normalBodyLimit)
                {
                    break;
                }

                payloads.Add(item.Payload);
                rawBodyBytes = nextBodyBytes;
                payloadBytes += item.Payload.Length;
                if (payloads.Count >= IGPMirrorApplicationFrame.MaxPayloadCount)
                {
                    break;
                }
            }

            return new PreparedApplicationFrame(IGPMirrorApplicationFrame.Encode(payloads), payloadBytes);
        }

        private IGPNetworkResult TrySendApplicationFrame(string remotePlayerId, byte[] wireData, string path)
        {
            if (!TryBindRuntime(AppendPath(path, "TryBindRuntime"), logFailure: false) ||
                runtimeManager?.Network == null || !runtimeManager.IsReliableConnected)
            {
                return IGPNetworkResult.kErrorNetworkError;
            }

            return runtimeManager.Network.SendReliableData(
                runtimeManager.PlayerId,
                remotePlayerId,
                wireData,
                (uint)wireData.Length,
                MirrorReliableApplicationFrameMessageType);
        }

        private void ObserveApplicationFrameWouldBlock(
            string remotePlayerId,
            long now,
            PreparedApplicationFrame prepared,
            string path)
        {
            bool shouldLog = false;
            double blockedSeconds = 0;
            int queuedMessages = 0;
            int queuedBytes = 0;
            lock (outboundQueueLock)
            {
                if (!outboundQueuesByPlayerId.TryGetValue(remotePlayerId, out var queue))
                {
                    return;
                }

                if (!queue.WouldBlockActive)
                {
                    queue.WouldBlockActive = true;
                    queue.WouldBlockSince = now;
                    shouldLog = true;
                }
                else if (now >= queue.NextWouldBlockLogAt)
                {
                    shouldLog = true;
                }

                if (shouldLog)
                {
                    queue.NextWouldBlockLogAt = now + SecondsToStopwatchTicks(SuppressedLogIntervalSeconds);
                }

                blockedSeconds = ElapsedSeconds(queue.WouldBlockSince, now);
                queuedMessages = queue.Payloads.Count;
                queuedBytes = queue.Bytes;
            }

            if (shouldLog)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"event=application-frame-backpressure action=retain-and-retry remote={FormatValue(remotePlayerId)} " +
                    $"blockedSeconds={blockedSeconds:F3} framePayloads={prepared.Encoded.PayloadCount} " +
                    $"frameWireBytes={prepared.Encoded.WireData.Length} queuedMessages={queuedMessages} " +
                    $"queuedBytes={queuedBytes} result={IGPNetworkResult.kErrorWouldBlock}");
            }
        }

        private void ObserveApplicationFrameSendFailure(
            string remotePlayerId,
            long now,
            PreparedApplicationFrame prepared,
            IGPNetworkResult result,
            string path)
        {
            bool shouldLog = false;
            lock (outboundQueueLock)
            {
                if (outboundQueuesByPlayerId.TryGetValue(remotePlayerId, out var queue) &&
                    now >= queue.NextSendFailureLogAt)
                {
                    queue.NextSendFailureLogAt = now + SecondsToStopwatchTicks(SuppressedLogIntervalSeconds);
                    shouldLog = true;
                }
            }

            if (shouldLog)
            {
                IGPLog.Warning(
                    "mirror-transport",
                    path,
                    $"event=application-frame-send-deferred action=retain-until-data-plane-state-change " +
                    $"remote={FormatValue(remotePlayerId)} result={result} payloads={prepared.Encoded.PayloadCount} " +
                    $"wireBytes={prepared.Encoded.WireData.Length} dataPlaneReady={runtimeManager?.IsRealtimeReady == true}");
            }
        }

        private void DisconnectPeerForOutboundQueueFault(string remotePlayerId, string reason, string path)
        {
            IGPLog.Error(
                "mirror-transport",
                path,
                $"event=outbound-queue-fault action=disconnect-peer remote={FormatValue(remotePlayerId)} reason={reason}");
            if (string.Equals(connectedServerPlayerId, remotePlayerId, StringComparison.Ordinal))
            {
                OnClientError?.Invoke(TransportError.InvalidSend, $"Reliable outbound queue failed: {reason}.");
                CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "CompleteClientDisconnect"));
                return;
            }

            if (playerIdToConnectionId.TryGetValue(remotePlayerId, out int connectionId))
            {
                OnServerError?.Invoke(connectionId, TransportError.InvalidSend, $"Reliable outbound queue failed: {reason}.");
                RemoveServerConnection(connectionId, remotePlayerId, notifyMirror: true, AppendPath(path, "RemoveServerConnection"));
                return;
            }

            RemoveOutboundApplicationFramesForPeer(remotePlayerId);
        }

        private void RemoveOutboundApplicationFramesForPeer(string remotePlayerId)
        {
            lock (outboundQueueLock)
            {
                outboundQueuesByPlayerId.Remove(remotePlayerId);
            }
        }

        private static long SecondsToStopwatchTicks(double seconds)
        {
            return (long)Math.Ceiling(seconds * System.Diagnostics.Stopwatch.Frequency);
        }

        private static double ElapsedSeconds(long startedAt, long now)
        {
            return 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-application-frame-scheduler");
                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 (!useRawUdpUnreliableLane || !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;
                runtimeBackend.ConnectionChanged += HandleRealtimeConnectionStateChanged;
                backendWasReady = runtimeBackend.IsReady;
                runtimeBound = true;
                IGPLog.Debug(
                    "mirror-transport",
                    path,
                    $"bound playerId={FormatValue(runtimeManager.PlayerId)} eventOnlyReceive=true");
            }

            return true;
        }

        private void UnbindRuntime(string path)
        {
            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;
                runtimeBackend.ConnectionChanged -= HandleRealtimeConnectionStateChanged;
            }
            runtimeBackend = null;
            backendWasReady = false;
            runtimeBound = false;
            IGPLog.Debug(
                "mirror-transport",
                path,
                "unbound");
        }

        private void HandleRealtimeConnectionStateChanged(IGPRealtimeConnectionState state)
        {
            if (state == IGPRealtimeConnectionState.Ready)
            {
                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;
            }
            lock (outboundQueueLock)
            {
                hasQueuedMessages = hasQueuedMessages || outboundQueuesByPlayerId.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");
            }

            if (hasClientState)
            {
                CompleteClientDisconnect(
                    sendDisconnectPacket: false,
                    AppendPath(path, "CompleteClientDisconnect"));
            }
            else if (!string.IsNullOrWhiteSpace(pendingClientAddress))
            {
                connectDeadlineAt = 0f;
                nextConnectAttemptAt = 0f;
            }

            foreach (var entry in new List<KeyValuePair<int, string>>(connectionIdToPlayerId))
            {
                RemoveServerConnection(
                    entry.Key,
                    entry.Value,
                    notifyMirror: true,
                    AppendPath(path, "RemoveServerConnection"));
            }

            ClearQueuedMessages();
        }

        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 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);
            }
            RemoveOutboundApplicationFramesForPeer(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)
        {
            bool disconnected = false;
            if (string.Equals(connectedServerPlayerId, remotePlayerId, StringComparison.Ordinal) ||
                string.Equals(pendingClientTargetPlayerId, remotePlayerId, StringComparison.Ordinal))
            {
                CompleteClientDisconnect(sendDisconnectPacket: false, AppendPath(path, "CompleteClientDisconnect"));
                disconnected = true;
            }

            if (playerIdToConnectionId.TryGetValue(remotePlayerId, out int connectionId))
            {
                RemoveServerConnection(
                    connectionId,
                    remotePlayerId,
                    notifyMirror: true,
                    AppendPath(path, "RemoveServerConnection"));
                disconnected = true;
            }

            if (!disconnected)
            {
                RemoveQueuedMessagesForPeer(remotePlayerId);
            }
        }

        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;
            }

            lock (outboundQueueLock)
            {
                outboundQueuesByPlayerId.Clear();
            }

            nextApplicationFrameFlushAt = 0;

            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} " +
                      $"fragmented={wireBytes > EstimatedReliableDataPlanePayloadMaxBytes}",
                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 IsCompressedDataMessageType(uint messageType)
        {
            return 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;
            if (!IsCompressedDataMessageType(message.MessageType))
            {
                return true;
            }

            try
            {
                int maxOriginalBytes = channel == Channels.Unreliable
                    ? ResolveUnreliablePacketMaxBytes()
                    : ReliablePacketMaxBytes;
                payload = IGPMirrorPayloadCompression.Decompress(message.Payload, maxOriginalBytes);
                return true;
            }
            catch (Exception ex)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"failed reason=decompress_failed remote={FormatValue(message.RemotePlayerId)} " +
                    $"message={DescribeMessageType(message.MessageType)} bytes={message.Payload.Length} " +
                    $"error={ex.Message}");
                if (connectionId.HasValue)
                {
                    OnServerError?.Invoke(
                        connectionId.Value,
                        TransportError.InvalidReceive,
                        "Failed to decompress Mirror payload.");
                }
                else
                {
                    OnClientError?.Invoke(
                        TransportError.InvalidReceive,
                        "Failed to decompress Mirror payload.");
                }

                return false;
            }
        }

        private bool TryDecodeApplicationFrame(
            QueuedMessage message,
            int? connectionId,
            string path,
            out IReadOnlyList<byte[]> payloads)
        {
            payloads = Array.Empty<byte[]>();
            try
            {
                payloads = IGPMirrorApplicationFrame.Decode(message.Payload);
                return true;
            }
            catch (Exception ex)
            {
                IGPLog.Error(
                    "mirror-transport",
                    path,
                    $"event=application-frame-decode-failed action=disconnect-peer " +
                    $"remote={FormatValue(message.RemotePlayerId)} bytes={message.Payload.Length} error={ex.Message}");
                if (connectionId.HasValue)
                {
                    OnServerError?.Invoke(
                        connectionId.Value,
                        TransportError.InvalidReceive,
                        "Failed to decode Mirror application frame.");
                    RemoveServerConnection(
                        connectionId.Value,
                        message.RemotePlayerId,
                        notifyMirror: true,
                        AppendPath(path, "DecodeFailureDisconnect"));
                }
                else
                {
                    OnClientError?.Invoke(
                        TransportError.InvalidReceive,
                        "Failed to decode Mirror application frame.");
                    CompleteClientDisconnect(
                        sendDisconnectPacket: false,
                        AppendPath(path, "DecodeFailureDisconnect"));
                }

                return false;
            }
        }

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

        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.CurrentRoomData.hostId;
            }

            return address.Trim();
        }

        private string FormatPayloadDetail(byte[]? payload)
        {
            if (!IGPLog.ShouldLog(IGPLogLevel.Debug))
            {
                return string.Empty;
            }

            int byteCount = payload?.Length ?? 0;

            // Always log a checksum so identical resends share a stable fingerprint
            // (duplicate detection); additionally show the raw hex for small payloads
            // so the content is directly readable.
            string content = byteCount <= MessageLogHexPreviewMaxBytes
                ? $"hex={ToHex(payload, byteCount)}"
                : $"checksum={Fnv1a32(payload, byteCount):X8}";

            return $" {content}";
        }

        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;
            bool includeDebugDetail = ShouldLog(IGPLogLevel.Debug);
            bool mirrorReliableChannelData = IsReliableDataPlaneMessageType(messageType);
            bool fragmented = mirrorReliableChannelData && wireBytes > EstimatedReliableDataPlanePayloadMaxBytes;
            int estimatedFragments = mirrorReliableChannelData ? EstimateReliableFragments(wireBytes) : 1;
            string payloadDetail = includeDebugDetail ? FormatPayloadDetail(safePayload) : string.Empty;
            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} compressed={IsCompressedDataMessageType(messageType)} " +
                   $"{FormatCompressionDecision(sendDiagnostics, includeDebugDetail)} " +
                   $"large={IsLargePayloadSummaryCandidate(messageType, originalBytes, wireBytes)} " +
                   $"fragmented={fragmented} estimatedFragments={estimatedFragments} result={result}{payloadDetail}";
        }

        private string FormatCompressionDecision(
            PayloadSendDiagnostics sendDiagnostics,
            bool includeDebugDetail)
        {
            if (!sendDiagnostics.CompressionAttempted)
            {
                return "compressionDecision=not-attempted";
            }

            var diagnostics = sendDiagnostics.Compression;
            if (sendDiagnostics.CompressionAccepted)
            {
                return $"compressionDecision=accepted compressedBytes={diagnostics.CompressedBytes} " +
                       $"ratio={diagnostics.ActualCompressionRatio:F3} thresholdBytes={diagnostics.ThresholdBytes} " +
                       $"minRatio={diagnostics.MinCompressionRatio:F3}";
            }

            string payloadProfile = includeDebugDetail && !string.IsNullOrWhiteSpace(diagnostics.PayloadProfile)
                ? $" payloadProfile=({diagnostics.PayloadProfile})"
                : string.Empty;
            return $"compressionDecision=rejected compressionReason={FormatValue(diagnostics.Reason)} " +
                   $"candidateBytes={diagnostics.CompressedBytes} ratio={diagnostics.ActualCompressionRatio:F3} " +
                   $"thresholdBytes={diagnostics.ThresholdBytes} minRatio={diagnostics.MinCompressionRatio:F3}" +
                   payloadProfile;
        }

        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 > EstimatedReliableDataPlanePayloadMaxBytes);
        }

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

        private static int EstimateReliableFragments(int wireBytes)
        {
            if (wireBytes <= 0)
            {
                return 1;
            }

            return Math.Max(1, (wireBytes + EstimatedReliableChunkMaxBytes - 1) / EstimatedReliableChunkMaxBytes);
        }

        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} " +
                $"reliableSendRate={ReliableSendRate} " +
                $"reliablePacketMaxBytes={ReliablePacketMaxBytes} useRawUdpUnreliableLane={useRawUdpUnreliableLane} " +
                $"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 NormalizeReliableSendRate(int value)
        {
            return Math.Min(MaxReliableSendRate, Math.Max(MinReliableSendRate, 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 uint Fnv1a32(byte[]? data, int count)
        {
            const uint offsetBasis = 2166136261;
            const uint prime = 16777619;
            uint hash = offsetBasis;
            if (data != null)
            {
                for (int i = 0; i < count; i++)
                {
                    hash ^= data[i];
                    hash *= prime;
                }
            }

            return hash;
        }

        private static string ToHex(byte[]? data, int count)
        {
            if (data == null || count == 0)
            {
                return "(empty)";
            }

            var builder = new StringBuilder(count * 2);
            for (int i = 0; i < count; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            return builder.ToString();
        }

        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;
        }
    }
}
