#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using IGP.UnitySDK.Abstractions;
using Newtonsoft.Json.Linq;

namespace IGP.UnitySDK.GameKit
{
    public enum IGPFriendPresenceStatus
    {
        Idle = 0,
        Loading = 1,
        Ready = 2,
        Error = 3
    }

    public sealed class IGPFriendPresenceSnapshot
    {
        internal IGPFriendPresenceSnapshot(IGPFriendPresenceStatus status, string[] online, string[] desktop)
        {
            Status = status;
            OnlineUserIds = Array.AsReadOnly((string[])online.Clone());
            DesktopOnlineUserIds = Array.AsReadOnly((string[])desktop.Clone());
        }
        public IGPFriendPresenceStatus Status { get; }
        public IReadOnlyList<string> OnlineUserIds { get; }
        public IReadOnlyList<string> DesktopOnlineUserIds { get; }
    }

    public sealed class IGPFriendStatusChanged
    {
        internal IGPFriendStatusChanged(string userId, bool wasOnline, bool isOnline, bool wasDesktopOnline, bool isDesktopOnline)
        {
            UserId = userId;
            WasOnline = wasOnline;
            IsOnline = isOnline;
            WasDesktopOnline = wasDesktopOnline;
            IsDesktopOnline = isDesktopOnline;
        }
        public string UserId { get; }
        public bool WasOnline { get; }
        public bool IsOnline { get; }
        public bool WasDesktopOnline { get; }
        public bool IsDesktopOnline { get; }
    }

    /// <summary>
    /// Explicit, session-scoped friends presence listener. Construct and call on
    /// Unity's main thread after the runtime has attached. No polling or automatic
    /// re-subscription. Stop before discarding a live monitor.
    /// </summary>
    public sealed class IGPFriendMonitor
    {
        private static readonly Dictionary<object, IGPFriendMonitor> Owners = new Dictionary<object, IGPFriendMonitor>();
        private readonly object runtimeKey;
        private readonly IIGPHostServiceMessageSource source;
        private readonly Func<Func<bool, Task<IGPDesktopSessionCommandResult>>> createSender;
        private readonly Func<CancellationToken> getLifetime;
        private readonly SynchronizationContext? context = SynchronizationContext.Current;
        private readonly int threadId = Thread.CurrentThread.ManagedThreadId;
        private readonly SemaphoreSlim operations = new SemaphoreSlim(1, 1);
        private readonly Queue<PresenceMessage> pending = new Queue<PresenceMessage>();
        private Func<bool, Task<IGPDesktopSessionCommandResult>>? sender;
        private CancellationTokenRegistration lifetimeRegistration;
        private string? subscriptionId;
        private long revision = -1;
        private int generation;
        private bool listening;

        public IGPFriendMonitor(IGPRuntimeManager runtimeManager)
            : this(runtimeManager ?? throw new ArgumentNullException(nameof(runtimeManager)),
                runtimeManager, runtimeManager.CreateFriendsPresenceSubscriptionSender, () => runtimeManager.LifetimeToken) { }

        internal IGPFriendMonitor(object runtimeKey, IIGPHostServiceMessageSource source,
            Func<Func<bool, Task<IGPDesktopSessionCommandResult>>> createSender, Func<CancellationToken> getLifetime)
        {
            this.runtimeKey = runtimeKey;
            this.source = source;
            this.createSender = createSender;
            this.getLifetime = getLifetime;
        }

        public IGPFriendPresenceSnapshot? CurrentSnapshot { get; private set; }
        public event Action<IGPFriendStatusChanged>? FriendStatusChanged;

        public async Task StartAsync()
        {
            CheckThread();
            await operations.WaitAsync();
            var attempt = generation;
            var rollback = false;
            try
            {
                if (listening) return;
                lock (Owners)
                {
                    if (Owners.TryGetValue(runtimeKey, out var owner) && !ReferenceEquals(owner, this))
                        throw Failure("FRIENDS_MONITOR_ALREADY_ACTIVE");
                    Owners[runtimeKey] = this;
                }
                Log("subscribe", "start");
                sender = createSender();
                getLifetime().ThrowIfCancellationRequested();
                listening = true;
                source.ServiceMessageReceived += Receive;
                source.ServiceMessageStreamReset += Reset;
                lifetimeRegistration = getLifetime().Register(() => OnLifetimeEnded(attempt));
                rollback = true;
                var result = await sender(true);
                if (!listening || attempt != generation) throw Failure("FRIENDS_SESSION_ENDED");
                if (!result.Success) { rollback = false; throw Failure(SafeCode(result.Code)); }
                var json = JObject.Parse(result.ContentJson ?? string.Empty);
                subscriptionId = ReadId(json["subscriptionId"]);
                if (subscriptionId == null) throw Failure("FRIENDS_INVALID_RESPONSE");
                while (pending.Count > 0 && listening && generation == attempt) Apply(pending.Dequeue());
                Log("subscribe", "complete");
            }
            catch (Exception exception)
            {
                // An enable may have reached the Host even if its result was
                // malformed. Keep ownership until rollback finishes. A reset
                // means that session ended; never send cleanup to a new one.
                var cleanup = rollback && attempt == generation ? sender : null;
                Clear(false);
                if (cleanup != null)
                {
                    try { await cleanup(false); }
                    catch { Log("unsubscribe", "failed", true); }
                }
                ReleaseOwnership();
                Log("subscribe", "failed", true);
                if (exception is IGPFriendsException) throw;
                throw Failure("FRIENDS_SUBSCRIPTION_FAILED");
            }
            finally { operations.Release(); }
        }

        public async Task StopAsync()
        {
            CheckThread();
            await operations.WaitAsync();
            try
            {
                var previousSender = sender;
                Clear(false);
                if (previousSender == null) return;
                Log("unsubscribe", "start");
                var result = await previousSender(false);
                if (!result.Success) throw Failure(SafeCode(result.Code));
                Log("unsubscribe", "complete");
            }
            catch (Exception exception)
            {
                Log("unsubscribe", "failed", true);
                if (exception is IGPFriendsException) throw;
                throw Failure("FRIENDS_UNSUBSCRIBE_FAILED");
            }
            finally { ReleaseOwnership(); operations.Release(); }
        }

        private void CheckThread()
        {
            if (Thread.CurrentThread.ManagedThreadId != threadId)
                throw Failure("FRIENDS_MAIN_THREAD_REQUIRED");
        }

        private void OnLifetimeEnded(int endedGeneration)
        {
            if (context != null && Thread.CurrentThread.ManagedThreadId != threadId)
                context.Post(_ => { if (generation == endedGeneration) Reset(); }, null);
            else if (generation == endedGeneration) Reset();
        }

        private void Reset()
        {
            Clear(true);
            Log("stream-reset", "complete");
        }

        private void Clear(bool release)
        {
            generation++;
            listening = false;
            source.ServiceMessageReceived -= Receive;
            source.ServiceMessageStreamReset -= Reset;
            lifetimeRegistration.Dispose();
            lifetimeRegistration = default;
            sender = null;
            subscriptionId = null;
            revision = -1;
            CurrentSnapshot = null;
            pending.Clear();
            if (release) ReleaseOwnership();
        }

        private void ReleaseOwnership()
        {
            lock (Owners)
                if (Owners.TryGetValue(runtimeKey, out var owner) && ReferenceEquals(owner, this)) Owners.Remove(runtimeKey);
        }

        private void Receive(IGPHostServiceMessage message)
        {
            if (!listening || message.Subcommand != IGPHostServiceMessageSubcommand.GameKitFriendsPresence) return;
            var parsed = Parse(message.ContentJson);
            if (parsed == null) { Log("snapshot", "invalid-payload", true); return; }
            if (subscriptionId == null) pending.Enqueue(parsed);
            else Apply(parsed);
        }

        private void Apply(PresenceMessage message)
        {
            if (message.SubscriptionId != subscriptionId || message.Revision <= revision)
            { Log("snapshot", "ignored"); return; }
            revision = message.Revision;
            var previous = CurrentSnapshot;
            CurrentSnapshot = message.Snapshot;
            if (previous?.Status != IGPFriendPresenceStatus.Ready || message.Snapshot.Status != IGPFriendPresenceStatus.Ready)
            { Log("snapshot", "baseline"); return; }

            var oldOnline = new HashSet<string>(previous.OnlineUserIds, StringComparer.Ordinal);
            var oldDesktop = new HashSet<string>(previous.DesktopOnlineUserIds, StringComparer.Ordinal);
            var online = new HashSet<string>(message.Snapshot.OnlineUserIds, StringComparer.Ordinal);
            var desktop = new HashSet<string>(message.Snapshot.DesktopOnlineUserIds, StringComparer.Ordinal);
            var users = new SortedSet<string>(oldOnline, StringComparer.Ordinal);
            users.UnionWith(oldDesktop); users.UnionWith(online); users.UnionWith(desktop);
            var dispatchGeneration = generation;
            var count = 0;
            foreach (var id in users)
            {
                if (!listening || generation != dispatchGeneration) break;
                if (oldOnline.Contains(id) == online.Contains(id) && oldDesktop.Contains(id) == desktop.Contains(id)) continue;
                var change = new IGPFriendStatusChanged(id, oldOnline.Contains(id), online.Contains(id), oldDesktop.Contains(id), desktop.Contains(id));
                var handlers = FriendStatusChanged;
                if (handlers == null) continue;
                foreach (Action<IGPFriendStatusChanged> handler in handlers.GetInvocationList())
                {
                    if (!listening || generation != dispatchGeneration) break;
                    try { handler(change); count++; }
                    catch { Log("event", "subscriber-failed", true); }
                }
            }
            IGPLog.Info("game-kit-friends", "snapshot", $"phase=complete result=processed deliveredCount={count}");
        }

        private sealed class PresenceMessage
        {
            internal string SubscriptionId = string.Empty;
            internal long Revision;
            internal IGPFriendPresenceSnapshot Snapshot = null!;
        }

        private static PresenceMessage? Parse(string content)
        {
            try
            {
                var json = JObject.Parse(content);
                if (json.Count != 6 || json["schemaVersion"]?.Type != JTokenType.Integer || (long)json["schemaVersion"]! != 1) return null;
                var id = ReadId(json["subscriptionId"]);
                if (id == null || json["revision"]?.Type != JTokenType.Integer) return null;
                var rev = (long)json["revision"]!;
                if (rev < 0 || rev > 9007199254740991L || json["status"]?.Type != JTokenType.String) return null;
                IGPFriendPresenceStatus status;
                switch ((string?)json["status"])
                {
                    case "idle": status = IGPFriendPresenceStatus.Idle; break;
                    case "loading": status = IGPFriendPresenceStatus.Loading; break;
                    case "ready": status = IGPFriendPresenceStatus.Ready; break;
                    case "error": status = IGPFriendPresenceStatus.Error; break;
                    default: return null;
                }
                var online = ReadIds(json["onlineUserIds"]);
                var desktop = ReadIds(json["desktopOnlineUserIds"]);
                if (online == null || desktop == null) return null;
                return new PresenceMessage { SubscriptionId = id, Revision = rev,
                    Snapshot = new IGPFriendPresenceSnapshot(status, online, desktop) };
            }
            catch { return null; }
        }

        private static string? ReadId(JToken? value) =>
            value?.Type == JTokenType.String && !string.IsNullOrWhiteSpace((string?)value) ? (string?)value : null;

        private static string[]? ReadIds(JToken? value)
        {
            if (!(value is JArray array)) return null;
            var ids = new HashSet<string>(StringComparer.Ordinal);
            foreach (var item in array)
            {
                var id = ReadId(item);
                if (id == null || !ids.Add(id)) return null;
            }
            return ids.ToArray();
        }

        private static string SafeCode(string? code) =>
            !string.IsNullOrEmpty(code) && code!.Length <= 80 && code.All(c => c == '_' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
                ? code : "FRIENDS_SUBSCRIPTION_FAILED";
        private static IGPFriendsException Failure(string code) => new IGPFriendsException(code, "Friends presence operation failed");
        private static void Log(string operation, string result, bool warning = false)
        {
            if (warning) IGPLog.Warning("game-kit-friends", operation, $"phase=complete result={result}");
            else IGPLog.Info("game-kit-friends", operation, $"phase=complete result={result}");
        }
    }
}
