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

namespace IGP.Multiplayer
{
    public partial class IGPMultiplayerRuntime
    {
        private readonly Dictionary<object, MirrorShutdownRegistration> mirrorShutdownRegistrations =
            new Dictionary<object, MirrorShutdownRegistration>();
        private bool quitRequested;
        private bool quitAllowed;
        private Task? quitWaitTask;
        private Action quitApplication = () => Application.Quit();

        internal string MirrorMatchId => currentMatchId;

        internal void RegisterMirrorShutdown(object owner, Func<bool> active, Action stop)
        {
            mirrorShutdownRegistrations[owner] = new MirrorShutdownRegistration(active, stop);
        }

        internal void UnregisterMirrorShutdown(object owner) => mirrorShutdownRegistrations.Remove(owner);

        internal void RequestMirrorLeave(string matchId, string origin)
        {
            if (isDestroyed || string.IsNullOrEmpty(matchId) || matchId != currentMatchId) return;
            LogSdkInfo("multiplayer-runtime", "mirror-leave",
                $"event=requested origin={FormatNetworkLogValue(origin)} matchId={FormatNetworkLogValue(matchId)}");
            _ = ObserveMirrorLeaveAsync(DisconnectAsync(), matchId, origin);
        }

        private async Task ObserveMirrorLeaveAsync(Task leave, string matchId, string origin)
        {
            try
            {
                await leave;
                LogSdkInfo("multiplayer-runtime", "mirror-leave",
                    $"event=complete origin={FormatNetworkLogValue(origin)} matchId={FormatNetworkLogValue(matchId)}");
            }
            catch (Exception exception)
            {
                LogSdkWarning("multiplayer-runtime", "mirror-leave",
                    $"event=failed origin={FormatNetworkLogValue(origin)} matchId={FormatNetworkLogValue(matchId)} errorType={exception.GetType().Name}");
            }
        }

        private bool HandleWantsToQuit()
        {
            if (quitAllowed || isDestroyed) return true;
            if (quitRequested) return false;
            // Snapshot: a stop callback unregisters its Mirror transport.
            var active = new List<MirrorShutdownRegistration>();
            foreach (var registration in mirrorShutdownRegistrations.Values)
                if (registration.Active()) active.Add(registration);
            bool pending = explicitLeaveTask != null && !explicitLeaveTask.IsCompleted;
            if (active.Count == 0 && !pending) return true;
            quitRequested = true;
            foreach (var registration in active)
            {
                try { registration.Stop(); }
                catch (Exception exception)
                {
                    LogSdkWarning("multiplayer-runtime", "quit", $"event=stop-failed errorType={exception.GetType().Name}");
                }
            }
            // Stop failures must not skip the member leave on a normal application exit.
            Task leave = explicitLeaveTask ?? DisconnectAsync();
            if (leave.IsCompleted)
            {
                _ = leave.Exception;
                quitAllowed = true;
                return true;
            }
            LogSdkInfo("multiplayer-runtime", "quit", "event=deferred reason=leave-pending");
            quitWaitTask = ResumeQuitAfterLeaveAsync(leave);
            return false;
        }

        private async Task ResumeQuitAfterLeaveAsync(Task leave)
        {
            try { await leave; }
            catch (Exception) { LogSdkWarning("multiplayer-runtime", "quit", "event=leave-unconfirmed"); }
            if (isDestroyed) return;
            quitAllowed = true;
            LogSdkInfo("multiplayer-runtime", "quit", "event=complete result=allowed");
            quitApplication();
        }

        private async Task<bool> WaitForLeaveAcknowledgementAsync(Task acknowledgement,
            System.Diagnostics.Stopwatch stopwatch)
        {
            while (!acknowledgement.IsCompleted && stopwatch.ElapsedMilliseconds < 3000)
            {
                if (isDestroyed) return false;
                // Unity Update may have been disabled by the application's stop sequence.
                // Continuations retain Unity's main-thread context; never tick on a worker.
                if (!isActiveAndEnabled)
                {
                    while (roomActions.TryDequeue(out var action)) action();
                    leavingTransport?.Tick();
                }
                await Task.WhenAny(acknowledgement, Task.Delay(10));
            }
            return acknowledgement.IsCompleted;
        }

        private async Task<bool> BeginBootstrapAfterLeaveAsync(IGPMultiplayerBootstrap bootstrap,
            bool allowProviderRefresh, CancellationToken cancellationToken, Task leave)
        {
            // Cancellation belongs to this caller, not the shared leave.
            var ready = AwaitLeaveForBootstrapAsync(leave);
            await AwaitCallerAsync(ready, cancellationToken);
            cancellationToken.ThrowIfCancellationRequested();
            if (isDestroyed || shutdownTask != null || quitRequested) return false;
            return await BeginBootstrapAsync(bootstrap, allowProviderRefresh, cancellationToken);
        }

        private static async Task<bool> AwaitLeaveForBootstrapAsync(Task leave)
        {
            try { await leave; }
            catch (Exception) { /* Old membership may be unconfirmed; never reuse that Match. */ }
            return true;
        }

        private sealed class MirrorShutdownRegistration
        {
            internal readonly Func<bool> Active;
            internal readonly Action Stop;
            internal MirrorShutdownRegistration(Func<bool> active, Action stop) { Active = active; Stop = stop; }
        }
    }
}
