#nullable enable
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using IGP.UnitySDK.Abstractions;
using IGP.UnitySDK.Models;

namespace IGP.UnitySDK
{
    public partial class IGPRuntimeManager
    {
        private int pendingHostGracefulShutdownRequests;
        private int pendingHostServiceMessageStreamResets;
        public int AttachedAppId => hostSessionClient?.CurrentSession?.AppId ?? 0;

        public bool SupportsCapability(int capabilityFieldNumber)
        {
            return capabilityFieldNumber <= 0 ||
                (currentHostCapabilities?.SupportsCapability(capabilityFieldNumber) ?? false);
        }

        public async Task<IGPDesktopSessionCommandResult> SendAsync(
            int commandType,
            int capabilityFieldNumber = 0,
            string? contentJson = null,
            byte[]? contentBytes = null,
            CancellationToken cancellationToken = default)
        {
            var client = await EnsureHostSessionAsync(ResolveHostAppId(null));
            return await client.SendAsync(
                commandType,
                capabilityFieldNumber,
                contentJson,
                contentBytes,
                cancellationToken);
        }

        internal Task SendHostServiceMessageAsync(
            IGPHostServiceMessage message,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            EnsureCapabilityRequestAvailable();
            var client = hostSessionClient;
            if (client == null)
            {
                IGPLog.Warning("host-session", "service-message",
                    $"event=send-failed direction=sdk-to-host subcommand={message.Subcommand} " +
                    $"messageId={IGPLog.FormatValue(message.MessageId)} result=not-attached");
                throw new IGPSDKException("Host Session is not attached", IGPErrorCodes.ERR_HOST_SESSION_REQUIRED);
            }

            return client.SendServiceMessageAsync(message, cancellationToken);
        }

        internal async Task<bool> TryAttachHostSessionAsync(int? appIdOverride = null)
        {
            if (!initializeRequested)
            {
                MarkHostSessionUnavailable(
                    IGPErrorCodes.ERR_HOST_SESSION_REQUIRED,
                    "IGP SDK is not initialized");
                return false;
            }

            try
            {
                await AttachHostSessionAsync(appIdOverride);
                hostSessionLastErrorCode = string.Empty;
                hostSessionLastErrorMessage = string.Empty;
                return true;
            }
            catch (Exception ex)
            {
                CaptureHostAttachFailure(ex);
                LogSdkWarning(
                    HostSessionPlatformRuntime.TransportName,
                    "attach",
                    $"event=failed error={FormatNetworkLogValue(hostSessionLastErrorMessage)}");
                return false;
            }
        }

        private async Task AttachHostSessionAsync(int? appIdOverride = null)
        {
            var appId = ResolveHostAppId(appIdOverride);
            if (!appId.HasValue)
            {
                throw new IGPSDKException(
                    "IGP appId is required before Host Session capabilities can be used",
                    IGPErrorCodes.ERR_APP_ID_REQUIRED);
            }

            var platformRuntime = HostSessionPlatformRuntime;
            var request = platformRuntime.CreateAttachRequest(appId.Value);

            if (hostSessionClient != null &&
                hostSessionClient.IsAttached &&
                hostSessionClient.CurrentSession != null &&
                hostSessionClient.CurrentSession.AppId == request.AppId)
            {
                return;
            }

            await DetachHostSessionAsync();

            var transport = platformRuntime.CreateTransport();
            var client = new IGPHostSessionClient(transport);
            client.Detached += HandleHostSessionDetached;
            client.ErrorOccurred += HandleHostSessionError;
            client.AntiAddictionChanged += HandleHostAntiAddictionChanged;
            client.NotificationReceived += HandleHostNotificationReceived;
            client.OfflineMapLaunchRequested += HandleHostOfflineMapLaunchRequested;
            client.GracefulShutdownRequested += HandleHostGracefulShutdownRequested;
            client.ServiceMessageReceived += HandleHostServiceMessageReceived;

            try
            {
                var response = await client.ConnectAsync(request, RuntimeCancellationToken);
                runtimeInfo.CommitSaveRootPath(response.IgpSaveRoot);
                hostSessionClient = client;
                currentHostUserContext = new IGPDesktopUserContext
                {
                    userId = response.UserId,
                    accountId = response.AccountId,
                    loginState = response.LoginState,
                };
                currentHostCapabilities = response.Capabilities ?? new IGPDesktopCapabilitySet();
                currentHostUserProfile = response.UserProfile;
                HandleHostIdentityAttached(response.UserId, response.LoginState);
                currentAntiAddictionStatus = response.AntiAddictionStatus;
                hostSessionLastErrorCode = string.Empty;
                hostSessionLastErrorMessage = string.Empty;
                hostSessionLastErrorCategory = string.Empty;
                hostSessionLastChannelState = response.ChannelState ?? string.Empty;
                hostSessionLastAttachState = response.AttachState ?? string.Empty;
                hostSessionLastAttachSource = response.AttachSource ?? string.Empty;
                PublishHostConnectionChanged(true, platformRuntime.AttachedReason);
                platformRuntime.OnAttachSucceeded();
            }
            catch
            {
                client.Detached -= HandleHostSessionDetached;
                client.ErrorOccurred -= HandleHostSessionError;
                client.AntiAddictionChanged -= HandleHostAntiAddictionChanged;
                client.NotificationReceived -= HandleHostNotificationReceived;
                client.OfflineMapLaunchRequested -= HandleHostOfflineMapLaunchRequested;
                client.GracefulShutdownRequested -= HandleHostGracefulShutdownRequested;
                client.ServiceMessageReceived -= HandleHostServiceMessageReceived;
                client.Dispose();
                throw;
            }
        }

        private async Task DetachHostSessionAsync()
        {
            if (hostSessionClient == null)
            {
                ClearHostedRoomHint();
                currentHostUserContext = null;
                currentHostCapabilities = null;
                currentHostUserProfile = null;
                currentAntiAddictionStatus = null;
                return;
            }

            var client = hostSessionClient;
            var wasAttached = client.IsAttached;
            hostSessionClient = null;
            ClearHostedRoomHint();
            currentHostUserContext = null;
            currentHostCapabilities = null;
            currentHostUserProfile = null;
            currentAntiAddictionStatus = null;

            client.Detached -= HandleHostSessionDetached;
            client.ErrorOccurred -= HandleHostSessionError;
            client.AntiAddictionChanged -= HandleHostAntiAddictionChanged;
            client.NotificationReceived -= HandleHostNotificationReceived;
            client.OfflineMapLaunchRequested -= HandleHostOfflineMapLaunchRequested;
            client.GracefulShutdownRequested -= HandleHostGracefulShutdownRequested;
            client.ServiceMessageReceived -= HandleHostServiceMessageReceived;
            ClearPendingHostServiceMessages();
            QueueHostServiceMessageStreamReset();
            await client.DisconnectAsync();
            if (wasAttached)
            {
                PublishHostConnectionChanged(
                    false,
                    HostSessionPlatformRuntime.DetachedReason);
            }
        }

        private async Task<IGPHostSessionClient> EnsureHostSessionAsync(int? appIdOverride = null)
        {
            EnsureSDKInitialized();

            if (hostSessionClient != null &&
                hostSessionClient.IsAttached &&
                hostSessionClient.CurrentSession != null &&
                (!appIdOverride.HasValue || hostSessionClient.CurrentSession.AppId == appIdOverride.Value))
            {
                return hostSessionClient;
            }

            if (await TryAttachHostSessionAsync(appIdOverride))
            {
                return hostSessionClient!;
            }

            if (await HostSessionPlatformRuntime.RecoverUnavailableSessionAsync(appIdOverride))
            {
                return hostSessionClient!;
            }

            throw CreateHostUnavailableException();
        }

        private int? ResolveHostAppId(int? appIdOverride = null)
        {
            if (appIdOverride.HasValue && appIdOverride.Value > 0)
            {
                return appIdOverride.Value;
            }

            return IGPHostSessionEnvironment.TryResolveAppId(
                config?.appId ?? 0,
                pendingLaunchOptions?.appId,
                out var resolvedAppId)
                ? resolvedAppId
                : null;
        }

        private string ResolveSdkVersion()
        {
            return IGPSdkVersion.PackageVersion;
        }

        private void CaptureHostAttachFailure(Exception error)
        {
            if (error is IGPSDKException sdkException)
            {
                MarkHostSessionUnavailable(
                    string.IsNullOrWhiteSpace(sdkException.ErrorCode)
                        ? IGPErrorCodes.ERR_HOST_SESSION_REQUIRED
                        : sdkException.ErrorCode!,
                    sdkException.Message,
                    sdkException.Category,
                    sdkException.DesktopChannelState,
                    sdkException.DesktopAttachState);
                return;
            }

            MarkHostSessionUnavailable(
                IGPErrorCodes.ERR_HOST_SESSION_REQUIRED,
                error.Message,
                IGPErrorCodes.CATEGORY_CHANNEL,
                channelState: null,
                attachState: null);
        }

        private void MarkHostSessionUnavailable(string errorCode, string message)
        {
            MarkHostSessionUnavailable(
                errorCode,
                message,
                IGPErrorCodes.ResolveCategory(errorCode),
                channelState: null,
                attachState: null);
        }

        private void MarkHostSessionUnavailable(
            string errorCode,
            string message,
            string? category,
            string? channelState,
            string? attachState)
        {
            currentHostUserContext = null;
            currentHostCapabilities = null;
            currentHostUserProfile = null;
            currentAntiAddictionStatus = null;
            hostSessionLastErrorCode = errorCode ?? string.Empty;
            hostSessionLastErrorMessage = message ?? string.Empty;
            hostSessionLastErrorCategory = string.IsNullOrWhiteSpace(category)
                ? IGPErrorCodes.ResolveCategory(errorCode)
                : category!;

            if (!string.IsNullOrEmpty(channelState))
            {
                hostSessionLastChannelState = channelState!;
            }

            if (!string.IsNullOrEmpty(attachState))
            {
                hostSessionLastAttachState = attachState!;
            }

            hostSessionPlatformRuntime?.ScheduleAttachRecoveryIfNeeded();
        }

        private IGPSDKException CreateHostUnavailableException()
        {
            var errorCode = string.IsNullOrWhiteSpace(hostSessionLastErrorCode)
                ? IGPErrorCodes.ERR_HOST_SESSION_REQUIRED
                : hostSessionLastErrorCode;
            var message = string.IsNullOrWhiteSpace(hostSessionLastErrorMessage)
                ? "Host Session is not attached"
                : hostSessionLastErrorMessage;
            return new IGPSDKException(message, errorCode);
        }

        private void EnsureHostCapability(bool supported, string message)
        {
            if (!supported)
            {
                throw new IGPSDKException(
                    message,
                    IGPErrorCodes.ERR_HOST_SESSION_CAPABILITY_MISSING);
            }
        }

        private void HandleHostSessionDetached(string reason)
        {
            ClearPendingHostServiceMessages();
            QueueHostServiceMessageStreamReset();
            ClearHostedRoomHint();
            currentAntiAddictionStatus = null;
            MarkHostSessionUnavailable(
                IGPErrorCodes.ERR_HOST_SESSION_REQUIRED,
                string.IsNullOrWhiteSpace(reason) ? "Host Session detached" : reason,
                IGPErrorCodes.CATEGORY_CHANNEL,
                channelState: "disconnected",
                attachState: "idle");

            HostSessionPlatformRuntime.ScheduleAttachRecoveryIfNeeded();
            HostSessionPlatformRuntime.ScheduleAuthorizationRecoveryIfNeeded();
            PublishHostConnectionChanged(false, reason);

            if (!isDestroyed)
            {
                LogSdkWarning(
                    HostSessionPlatformRuntime.TransportName,
                    "detach",
                    $"event=detached error={FormatNetworkLogValue(hostSessionLastErrorMessage)}");
            }
        }

        private void HandleHostNotificationReceived(IGPDesktopSessionCommandResult notification)
        {
            HandleMobileHostIdentityNotification(notification);
            HandleRoomAccessNotification(notification);
            if (!isDestroyed)
            {
                hostNotificationReceived?.Invoke(notification);
            }
        }

        private void HandleHostOfflineMapLaunchRequested(
            IGPDesktopOfflineMapLaunchRequestedEvent offlineMapLaunchRequested)
        {
            if (isDestroyed || offlineMapLaunchRequested == null)
            {
                return;
            }

            var attachedAppId = hostSessionClient?.CurrentSession?.AppId;
            if (offlineMapLaunchRequested.appId > 0 &&
                attachedAppId.HasValue &&
                attachedAppId.Value > 0 &&
                offlineMapLaunchRequested.appId != attachedAppId.Value)
            {
                return;
            }

            OfflineMapLaunchRequested?.Invoke(offlineMapLaunchRequested);
        }

        private void HandleHostGracefulShutdownRequested()
        {
            if (isDestroyed)
            {
                return;
            }

            Interlocked.Increment(ref pendingHostGracefulShutdownRequests);
        }

        private void HandleHostServiceMessageReceived(IGPHostServiceMessage message)
        {
            if (isDestroyed || message == null)
            {
                return;
            }

            pendingHostServiceMessages.Enqueue(message);
            IGPLog.Info(
                "host-session",
                "service-message",
                $"event=queued direction=host-to-sdk subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                $"messageId={IGPLog.FormatValue(message.MessageId)} " +
                $"hasReplyTo={!string.IsNullOrWhiteSpace(message.ReplyToMessageId)} " +
                $"jsonBytes={Encoding.UTF8.GetByteCount(message.ContentJson)}");
        }

        private void DrainHostServiceMessages()
        {
            if (isDestroyed || !sdkInitialized)
            {
                return;
            }

            while (pendingHostServiceMessages.TryDequeue(out var message))
            {
                var handler = hostServiceMessageReceived;
                if (handler == null)
                {
                    IGPLog.Warning(
                        "host-session",
                        "service-message",
                        $"event=ignored reason=no-handler subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                        $"messageId={IGPLog.FormatValue(message.MessageId)}");
                    continue;
                }

                var deliveredCount = 0;
                var failedCount = 0;
                foreach (Action<IGPHostServiceMessage> subscriber in handler.GetInvocationList())
                {
                    try
                    {
                        subscriber.Invoke(message);
                        deliveredCount++;
                    }
                    catch (Exception)
                    {
                        failedCount++;
                    }
                }

                if (failedCount > 0)
                {
                    IGPLog.Warning(
                        "host-session",
                        "service-message",
                        $"event=dispatched direction=host-to-sdk subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                        $"messageId={IGPLog.FormatValue(message.MessageId)} result=handler-failed " +
                        $"deliveredCount={deliveredCount} failedCount={failedCount}");
                    continue;
                }

                IGPLog.Info(
                    "host-session",
                    "service-message",
                    $"event=dispatched direction=host-to-sdk subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                    $"messageId={IGPLog.FormatValue(message.MessageId)} " +
                    $"jsonBytes={Encoding.UTF8.GetByteCount(message.ContentJson)} result=delivered " +
                    $"deliveredCount={deliveredCount}");
            }
        }

        private void QueueHostServiceMessageStreamReset()
        {
            if (!isDestroyed)
            {
                Interlocked.Increment(ref pendingHostServiceMessageStreamResets);
            }
        }

        private void DrainHostServiceMessageStreamResets()
        {
            var pendingResets = Interlocked.Exchange(ref pendingHostServiceMessageStreamResets, 0);
            if (isDestroyed || pendingResets == 0)
            {
                return;
            }

            var handler = hostServiceMessageStreamReset;
            if (handler == null)
            {
                IGPLog.Info(
                    "host-session",
                    "service-message",
                    "event=stream-reset result=no-handler");
                return;
            }

            var deliveredCount = 0;
            var failedCount = 0;
            foreach (Action subscriber in handler.GetInvocationList())
            {
                try
                {
                    subscriber.Invoke();
                    deliveredCount++;
                }
                catch (Exception)
                {
                    failedCount++;
                }
            }

            if (failedCount > 0)
            {
                IGPLog.Warning(
                    "host-session",
                    "service-message",
                    $"event=stream-reset result=handler-failed deliveredCount={deliveredCount} " +
                    $"failedCount={failedCount}");
                return;
            }

            IGPLog.Info(
                "host-session",
                "service-message",
                $"event=stream-reset result=dispatched deliveredCount={deliveredCount}");
        }

        private void ClearPendingHostServiceMessages()
        {
            while (pendingHostServiceMessages.TryDequeue(out _))
            {
            }
        }

        private void DrainHostGracefulShutdownRequests()
        {
            var pendingRequests = Interlocked.Exchange(ref pendingHostGracefulShutdownRequests, 0);
            if (isDestroyed)
            {
                return;
            }

            for (var index = 0; index < pendingRequests; index += 1)
            {
                GracefulShutdownRequested?.Invoke();
            }
        }

        private void HandleHostSessionError(IGPSDKException error)
        {
            var code = string.IsNullOrWhiteSpace(error.ErrorCode)
                ? IGPErrorCodes.ERR_HOST_SESSION_REQUIRED
                : error.ErrorCode!;
            var message = error.Message;
            // 兼容旧事件：只有 code + message 时按码推断分类。
            HandleHostSessionErrorCore(
                string.IsNullOrWhiteSpace(code) ? IGPErrorCodes.ERR_HOST_SESSION_REQUIRED : code,
                message,
                error.Category,
                error.DesktopChannelState,
                error.DesktopAttachState);
        }

        private void HandleHostSessionErrorCore(
            string code,
            string message,
            string? category,
            string? channelState,
            string? attachState)
        {
            MarkHostSessionUnavailable(code, message, category, channelState, attachState);

            // Recovery policy is selected by error category; the platform runtime
            // decides whether attach or authorization recovery is supported.
            var resolvedCategory = string.IsNullOrWhiteSpace(category)
                ? IGPErrorCodes.ResolveCategory(code)
                : category!;

            if (resolvedCategory == IGPErrorCodes.CATEGORY_AUTHORIZATION)
            {
                HostSessionPlatformRuntime.ScheduleAuthorizationRecoveryIfNeeded();
            }
            else if (resolvedCategory == IGPErrorCodes.CATEGORY_CHANNEL ||
                     resolvedCategory == IGPErrorCodes.CATEGORY_RUNTIME)
            {
                HostSessionPlatformRuntime.ScheduleAttachRecoveryIfNeeded();
                HostSessionPlatformRuntime.ScheduleAuthorizationRecoveryIfNeeded();
            }

            if (!isDestroyed)
            {
                LogSdkError(
                    HostSessionPlatformRuntime.TransportName,
                    "error",
                    $"event=received code={FormatNetworkLogValue(hostSessionLastErrorCode)} " +
                    $"category={FormatNetworkLogValue(resolvedCategory)} error={FormatNetworkLogValue(message)}");
                ErrorOccurred?.Invoke(new IGPSDKException(
                    $"Host Session error: {message}",
                    code,
                    resolvedCategory,
                    channelState,
                    attachState));
            }
        }

        private void PublishHostConnectionChanged(bool isConnected, string reason)
        {
            if (hostConnectionEventState == isConnected)
            {
                return;
            }

            hostConnectionEventState = isConnected;
            if (!isDestroyed)
            {
                ConnectionChanged?.Invoke(new IGPConnectionChangedEvent(
                    isConnected,
                    HostSessionPlatformRuntime.ConnectionSource,
                    reason));
            }
        }
    }
}
