#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IGP.Multiplayer.Models;
using IGP.UnitySDK;
using IGP.UnitySDK.Models;

namespace IGP.Multiplayer
{
    public partial class IGPMultiplayerRuntime
    {
        private string currentMatchId = string.Empty;
        private string startedMatchId = string.Empty;
        private bool matchFinished;
        private readonly HashSet<string> retiredMatches = new HashSet<string>(StringComparer.Ordinal);
        private CancellationTokenSource? matchOperationCancellation;
        private Task<bool>? matchOperation;
        private string operationMatchId = string.Empty;
        private CancellationToken activeConnectionToken;
        private int bootstrapRequestGeneration;
        private IGPMultiplayerBootstrap? pendingMatchBootstrap;

        public async Task<bool> TryCreateRuntimeAsync(CancellationToken cancellationToken = default)
        {
            EnsureExtensionInitialized();
            cancellationToken.ThrowIfCancellationRequested();
            if (leavingMatch && explicitLeaveTask != null)
                await AwaitCallerAsync(AwaitLeaveForBootstrapAsync(explicitLeaveTask), cancellationToken);
            if (shutdownTask != null || quitRequested || isDestroyed) return false;
            int request = ++bootstrapRequestGeneration;
            int generation = realtimeRoomGeneration;
            LogSdkInfo("host-bootstrap", "event=start");
            try
            {
                var context = runtimeContext ?? throw new IGPSDKException("Core runtime context is unavailable");
                using var linked = CancellationTokenSource.CreateLinkedTokenSource(RuntimeCancellationToken, cancellationToken);
                var bootstrap = await context.RequestMultiplayerBootstrapAsync(linked.Token);
                linked.Token.ThrowIfCancellationRequested();
                if (request != bootstrapRequestGeneration || generation != realtimeRoomGeneration)
                {
                    LogSdkInfo("host-bootstrap", "event=complete result=stale");
                    return false;
                }
                bool result = bootstrap != null && await BeginBootstrapAsync(bootstrap, true, cancellationToken);
                LogSdkInfo("host-bootstrap", $"event=complete result={(result ? "ready" : "unavailable")}");
                return result;
            }
            catch (OperationCanceledException)
            {
                LogSdkInfo("host-bootstrap", "event=complete result=canceled");
                throw;
            }
            catch (Exception exception)
            {
                ReportRuntimeCreationFailure(exception, "core-host-provider", "core-host");
                return false;
            }
        }

        public Task<bool> TryCreateRuntimeAsync(IGPMultiplayerBootstrap bootstrap,
            CancellationToken cancellationToken = default) => BeginBootstrapAsync(bootstrap, false, cancellationToken);

        private Task<bool> BeginBootstrapAsync(IGPMultiplayerBootstrap bootstrap, bool allowProviderRefresh, CancellationToken cancellationToken)
        {
            if (bootstrap == null) throw new ArgumentNullException(nameof(bootstrap));
            EnsureExtensionInitialized();
            cancellationToken.ThrowIfCancellationRequested();
            if (shutdownTask != null || quitRequested) return Task.FromResult(false);
            if (leavingMatch && explicitLeaveTask != null)
                return BeginBootstrapAfterLeaveAsync(bootstrap, allowProviderRefresh, cancellationToken, explicitLeaveTask);
            try { IGPMultiplayerBootstrapValidator.Validate(bootstrap); }
            catch (Exception exception)
            {
                ReportRuntimeCreationFailure(exception, "caller-bootstrap", "explicit");
                return Task.FromResult(false);
            }
            string match = bootstrap.DataPlane.MatchId;
            if (currentMatchId == match && (!string.Equals(currentRoomId, bootstrap.Room.Id, StringComparison.Ordinal) ||
                !string.Equals(playerId, bootstrap.CurrentPlayer.Id, StringComparison.Ordinal)))
            {
                ReportRuntimeCreationFailure(new IGPSDKException("Match context identity differs", "MULTIPLAYER_CONTEXT_INVALID"), "runtime-create", "bootstrap");
                return Task.FromResult(false);
            }
            if (retiredMatches.Contains(match) || (matchFinished && currentMatchId == match))
                return Task.FromResult(false);
            if (matchOperation != null && !matchOperation.IsCompleted && operationMatchId == match)
                return AwaitCallerAsync(matchOperation, cancellationToken);
            if (currentMatchId == match && currentRoomId == bootstrap.Room.Id &&
                playerId == bootstrap.CurrentPlayer.Id && IsRealtimeReady) return Task.FromResult(true);
            // Retain the Game authority when a same-Match handoff arrives during an outage.
            if (currentMatchId == match && startedMatchId == match)
                return ReconnectDataPlaneAsync(cancellationToken);
            return AwaitCallerAsync(StartMatchOperation(bootstrap, false, allowProviderRefresh: allowProviderRefresh), cancellationToken);
        }

        public Task<bool> ReconnectDataPlaneAsync(CancellationToken cancellationToken = default)
        {
            EnsureExtensionInitialized();
            cancellationToken.ThrowIfCancellationRequested();
            if (leavingMatch || shutdownTask != null || quitRequested) return Task.FromResult(false);
            if (matchOperation != null && !matchOperation.IsCompleted)
                return AwaitCallerAsync(matchOperation, cancellationToken);
            if (IsRealtimeReady) return Task.FromResult(true);
            return AwaitCallerAsync(StartMatchOperation(null, true), cancellationToken);
        }

        public Task<bool> ReconnectDataPlaneAsync(IGPMultiplayerBootstrap bootstrap,
            CancellationToken cancellationToken = default) => TryCreateRuntimeAsync(bootstrap, cancellationToken);

        private Task<bool> StartMatchOperation(IGPMultiplayerBootstrap? bootstrap, bool recovery, Task? startSignal = null, bool allowProviderRefresh = false)
        {
            matchOperationCancellation?.Cancel();
            var cancellation = CancellationTokenSource.CreateLinkedTokenSource(RuntimeCancellationToken);
            matchOperationCancellation = cancellation;
            operationMatchId = bootstrap?.DataPlane.MatchId ?? currentMatchId;
            var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            matchOperation = completion.Task;
            _ = RunMatchOperationAsync(bootstrap, recovery, cancellation, completion, startSignal, allowProviderRefresh);
            return completion.Task;
        }

        private async Task RunMatchOperationAsync(IGPMultiplayerBootstrap? bootstrap, bool recovery,
            CancellationTokenSource cancellation, TaskCompletionSource<bool> completion, Task? startSignal, bool allowProviderRefresh)
        {
            bool entered = false;
            var token = cancellation.Token;
            try
            {
                // Install the shared task before callbacks or synchronous failures can re-enter.
                if (startSignal != null) await startSignal;
                await runtimeCreationGate.WaitAsync(token);
                entered = true;
                token.ThrowIfCancellationRequested();
                activeConnectionToken = token;
                runtimeCreationInProgress = true;
                LogSdkInfo(recovery ? "match-reconnect" : "runtime-create", "event=start");
                if (recovery)
                {
                    if (matchFinished || reconnectDescriptor == null || string.IsNullOrEmpty(reconnectToken))
                        throw new IGPSDKException("Current Match has no recovery credential", "MULTIPLAYER_RECONNECT_FAILED");
                    var descriptor = reconnectDescriptor;
                    descriptor.Token = reconnectToken;
                    descriptor.ExpiresAtUnixSeconds = long.MaxValue / 1000;
                    pendingConnectionRecoveryNotification = true;
                    EnsureRuntimeResources();
                    await ConnectDataPlaneAsync(descriptor, false, token);
                    token.ThrowIfCancellationRequested();
                    PublishConnectionRecoveredIfPending("match-reconnect");
                }
                else
                {
                    var source = bootstrap!;
                    if (currentMatchId != source.DataPlane.MatchId)
                    {
                        if (!string.IsNullOrEmpty(currentMatchId)) retiredMatches.Add(currentMatchId);
                        ResetHostedDataPlaneState("match-replaced");
                        Network?.ResetSessionState();
                        knownMatchPlayers.Clear();
                    }
                    if (CurrentRoomSnapshot != null && CurrentRoomSnapshot.Id != source.Room.Id) ClearBootstrapContext();
                    currentMatchId = source.DataPlane.MatchId;
                    matchFinished = false;
                    pendingConnectionRecoveryNotification = false;
                    reconnectDescriptor = null;
                    reconnectToken = string.Empty;
                    explicitLeaveTask = null;
                    currentRoomId = source.Room.Id;
                    playerId = source.CurrentPlayer.Id;
                    playerName = source.CurrentPlayer.Name;
                    realtimeRoomGeneration++;
                    pendingMatchBootstrap = source;
                    if (CurrentRoomSnapshot == null)
                        CommitRoomSnapshot(source.Room, source.CurrentPlayer, "room-entered", false);
                    token.ThrowIfCancellationRequested();
                    EnsureRuntimeResources();
                    await ConnectDataPlaneAsync(IGPResolvedGameDataPlaneDescriptor.FromCore(source.DataPlane), allowProviderRefresh, token);
                    token.ThrowIfCancellationRequested();
                }
                LogSdkInfo(recovery ? "match-reconnect" : "runtime-create", "event=complete result=ready");
                completion.TrySetResult(IsRealtimeReady);
            }
            catch (OperationCanceledException)
            {
                if (entered && !leavingMatch) ResetHostedDataPlaneState("operation-canceled");
                LogSdkInfo(recovery ? "match-reconnect" : "runtime-create", "event=complete result=canceled");
                completion.TrySetCanceled();
            }
            catch (Exception exception)
            {
                if (entered && !leavingMatch)
                {
                    ResetHostedDataPlaneState("operation-failed");
                    UpdateRealtimeConnectionState(IGPRealtimeConnectionState.Failed, "operation-failed");
                    if (!recovery && string.IsNullOrEmpty(startedMatchId))
                    {
                        string failedMatch = currentMatchId;
                        DisposeRuntimeResources("initial-connect-failed");
                        ClearBootstrapContext();
                        retiredMatches.Remove(failedMatch);
                    }
                }
                if (token.IsCancellationRequested) completion.TrySetCanceled();
                else
                {
                    ReportRuntimeCreationFailure(recovery
                        ? new IGPSDKException("Match connection recovery failed", "MULTIPLAYER_RECONNECT_FAILED")
                        : exception, recovery ? "match-reconnect" : "runtime-create", recovery ? "retained-member" : "bootstrap");
                    completion.TrySetResult(false);
                }
            }
            finally
            {
                if (entered)
                {
                    if (KcpClient != null) KcpClient.DowngradeErrorsToWarnings = false;
                    runtimeCreationInProgress = false;
                    runtimeCreationGate.Release();
                }
                if (ReferenceEquals(matchOperationCancellation, cancellation)) matchOperationCancellation = null;
                cancellation.Dispose();
            }
        }

        private static async Task<bool> AwaitCallerAsync(Task<bool> operation, CancellationToken cancellationToken)
        {
            if (!cancellationToken.CanBeCanceled) return await operation;
            var canceled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            using (cancellationToken.Register(() => canceled.TrySetCanceled()))
            {
                var completed = await Task.WhenAny(operation, canceled.Task);
                cancellationToken.ThrowIfCancellationRequested();
                return await completed;
            }
        }

        private void ReportRuntimeCreationFailure(Exception exception, string source, string bootstrapSource)
        {
            string code = exception is IGPSDKException sdk && !string.IsNullOrWhiteSpace(sdk.ErrorCode)
                ? sdk.ErrorCode! : "HOSTED_DATA_PLANE_ATTACH_FAILED";
            // Never copy provider/transport exception text or inner exceptions into public events.
            LogSdkWarning("runtime-create", $"event=complete result=failed source={source} code={FormatNetworkLogValue(code)}");
            PublishMultiplayerError(code, "Multiplayer connection operation failed", source, null, true);
        }
    }
}
