#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using IGP.UnitySDK;
using IGP.UnitySDK.Abstractions;
using NUnit.Framework;
using UnityEngine;
using Object = UnityEngine.Object;

namespace IGP.UnitySDK.GameKit.Tests
{
    [TestFixture]
    public sealed class IGPGameKitCommunicationTests
    {
        private const IGPHostServiceMessageSubcommand SpeakingStarted =
            IGPHostServiceMessageSubcommand.GameKitCommunicationVoiceSpeakingStarted;
        private const IGPHostServiceMessageSubcommand SpeakingStopped =
            IGPHostServiceMessageSubcommand.GameKitCommunicationVoiceSpeakingStopped;
        private const IGPHostServiceMessageSubcommand CommunicationMessage =
            IGPHostServiceMessageSubcommand.GameKitCommunicationMessage;

        private GameObject? gameObject;
        private IGPRuntimeManager? coreRuntime;
        private IGPGameKitRuntime? gameKitRuntime;

        [SetUp]
        public void SetUp()
        {
            gameObject = new GameObject("IGPGameKitCommunicationTests");
            coreRuntime = gameObject.AddComponent<IGPRuntimeManager>();
            gameKitRuntime = gameObject.AddComponent<IGPGameKitRuntime>();
        }

        [TearDown]
        public void TearDown()
        {
            IGPLog.Configure(IGPLogLevel.Off);
            if (gameObject != null)
            {
                Object.DestroyImmediate(gameObject);
            }
            gameObject = null;
            coreRuntime = null;
            gameKitRuntime = null;
        }

        [Test]
        public void PublicApi_MatchesApprovedGameKitSurface()
        {
            Assert.IsTrue(typeof(IGPGameKitRuntime).IsPublic);
            Assert.IsTrue(typeof(IGPGameKitRuntime).IsSealed);
            Assert.AreEqual(typeof(bool), typeof(IGPGameKitRuntime).GetProperty("IsInitialized")!.PropertyType);
            Assert.IsNull(typeof(IGPGameKitRuntime).GetProperty("IsInitialized")!.GetSetMethod(false));
            Assert.AreEqual(
                typeof(Action<IGPVoiceSpeakingEvent>),
                typeof(IGPGameKitRuntime).GetEvent("VoiceSpeakingStarted")!.EventHandlerType);
            Assert.AreEqual(
                typeof(Action<IGPVoiceSpeakingEvent>),
                typeof(IGPGameKitRuntime).GetEvent("VoiceSpeakingStopped")!.EventHandlerType);
            Assert.AreEqual(
                typeof(Action<IGPCommunicationMessageEvent>),
                typeof(IGPGameKitRuntime).GetEvent("CommunicationMessageReceived")!.EventHandlerType);
            Assert.IsNull(typeof(IGPGameKitRuntime).GetMethod("InitializeAsync", BindingFlags.Instance | BindingFlags.Public));
            Assert.IsNull(typeof(IGPGameKitRuntime).GetMethod("ShutdownAsync", BindingFlags.Instance | BindingFlags.Public));

            AssertInternalConstructors(typeof(IGPVoiceSpeakingEvent));
            AssertInternalConstructors(typeof(IGPCommunicationMessageEvent));
            AssertInternalConstructors(typeof(IGPCommunicationSegment));
            AssertInternalConstructors(typeof(IGPCommunicationTextSegment));
            AssertInternalConstructors(typeof(IGPCommunicationEmotionSegment));

            Assert.IsTrue(typeof(IGPVoiceSpeakingEvent).IsSealed);
            Assert.IsTrue(typeof(IGPCommunicationMessageEvent).IsSealed);
            Assert.IsTrue(typeof(IGPCommunicationSegment).IsAbstract);
            Assert.IsTrue(typeof(IGPCommunicationTextSegment).IsSealed);
            Assert.IsTrue(typeof(IGPCommunicationEmotionSegment).IsSealed);
            AssertReadOnlyProperties(
                typeof(IGPVoiceSpeakingEvent),
                "OccurredAtUnixMs", "PlayerId", "RoomId", "VoiceActivityId");
            AssertReadOnlyProperties(
                typeof(IGPCommunicationMessageEvent),
                "MessageId", "RoomId", "Segments", "SenderPlayerId", "SentAtUnixMs");
            AssertReadOnlyProperties(typeof(IGPCommunicationSegment));
            AssertReadOnlyProperties(typeof(IGPCommunicationTextSegment), "Text");
            AssertReadOnlyProperties(typeof(IGPCommunicationEmotionSegment), "EmotionId");
        }

        [Test]
        public void CommunicationMessages_DeliverTextEmotionAndMixedSegmentsInOrder()
        {
            var received = new List<IGPCommunicationMessageEvent>();
            gameKitRuntime!.CommunicationMessageReceived += value => received.Add(value);

            Send(CommunicationMessage, CommunicationPayload(
                "[{\"type\":\"text\",\"text\":\"only text\"}]"), "text-message");
            Send(CommunicationMessage, CommunicationPayload(
                "[{\"type\":\"emotion\",\"emotionId\":\"emotion.wave\"}]"), "emotion-message");
            Send(CommunicationMessage, CommunicationPayload(
                "[{\"type\":\"text\",\"text\":\"  hello  \"}," +
                "{\"type\":\"emotion\",\"emotionId\":\"emotion.cato-hello\"}," +
                "{\"type\":\"text\",\"text\":\"ready\"}]"), "mixed-message");

            Assert.AreEqual(3, received.Count);
            Assert.AreEqual("mixed-message", received[2].MessageId);
            Assert.AreEqual("room-123", received[2].RoomId);
            Assert.AreEqual("player-456", received[2].SenderPlayerId);
            Assert.AreEqual(1788775200123L, received[2].SentAtUnixMs);
            Assert.AreEqual(3, received[2].Segments.Count);
            Assert.AreEqual("  hello  ", ((IGPCommunicationTextSegment)received[2].Segments[0]).Text);
            Assert.AreEqual(
                "emotion.cato-hello",
                ((IGPCommunicationEmotionSegment)received[2].Segments[1]).EmotionId);
            Assert.AreEqual("ready", ((IGPCommunicationTextSegment)received[2].Segments[2]).Text);
            Assert.Throws<NotSupportedException>(() =>
                ((IList)received[2].Segments).Add(received[2].Segments[0]));
        }

        [TestCase("not-json")]
        [TestCase("null")]
        [TestCase("{\"schemaVersion\":2,\"roomId\":\"room-123\",\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1,\"segments\":[{\"type\":\"text\",\"text\":\"x\"}]}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-123\",\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1,\"segments\":[]}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-123\",\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1,\"segments\":[{\"type\":\"text\",\"text\":\"\"}]}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-123\",\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1,\"segments\":[{\"type\":\"emotion\",\"emotionId\":\"\"}]}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-123\",\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1,\"segments\":[{\"type\":\"video\"}]}")]
        public void InvalidCommunicationPayload_IsIgnoredAsAWhole(string contentJson)
        {
            var received = 0;
            gameKitRuntime!.CommunicationMessageReceived += _ => received += 1;

            Assert.DoesNotThrow(() => Send(CommunicationMessage, contentJson));

            Assert.AreEqual(0, received);
        }

        [TestCase("not-json")]
        [TestCase("null")]
        [TestCase("{\"schemaVersion\":2,\"roomId\":\"room-a\",\"playerId\":\"player-1\",\"voiceActivityId\":\"activity-1\",\"occurredAtUnixMs\":1}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"\",\"playerId\":\"player-1\",\"voiceActivityId\":\"activity-1\",\"occurredAtUnixMs\":1}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-a\",\"playerId\":\"\",\"voiceActivityId\":\"activity-1\",\"occurredAtUnixMs\":1}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-a\",\"playerId\":\"player-1\",\"voiceActivityId\":\"\",\"occurredAtUnixMs\":1}")]
        [TestCase("{\"schemaVersion\":1,\"roomId\":\"room-a\",\"playerId\":\"player-1\",\"voiceActivityId\":\"activity-1\",\"occurredAtUnixMs\":0}")]
        public void InvalidVoicePayload_IsIgnored(string contentJson)
        {
            var starts = 0;
            gameKitRuntime!.VoiceSpeakingStarted += _ => starts += 1;

            Assert.DoesNotThrow(() => Send(SpeakingStarted, contentJson));

            Assert.AreEqual(0, starts);
            Assert.AreEqual(0, ActiveActivityCount());
        }

        [Test]
        public void UnknownSubcommand_IsIgnored()
        {
            var communicationMessages = 0;
            var voiceStarts = 0;
            gameKitRuntime!.CommunicationMessageReceived += _ => communicationMessages += 1;
            gameKitRuntime.VoiceSpeakingStarted += _ => voiceStarts += 1;

            Assert.DoesNotThrow(() => Send(
                (IGPHostServiceMessageSubcommand)999,
                CommunicationPayload("[{\"type\":\"text\",\"text\":\"ignored\"}]")));

            Assert.AreEqual(0, communicationMessages);
            Assert.AreEqual(0, voiceStarts);
        }

        [Test]
        public void VoiceMessages_DeduplicateAndMatchByRoomPlayerAndActivity()
        {
            var started = new List<IGPVoiceSpeakingEvent>();
            var stopped = new List<IGPVoiceSpeakingEvent>();
            gameKitRuntime!.VoiceSpeakingStarted += value => started.Add(value);
            gameKitRuntime.VoiceSpeakingStopped += value => stopped.Add(value);

            Send(SpeakingStarted, VoicePayload("room-a", "player-1", "activity-1"));
            Send(SpeakingStarted, VoicePayload("room-a", "player-1", "activity-1"));
            Send(SpeakingStarted, VoicePayload("room-b", "player-1", "activity-2"));
            Send(SpeakingStopped, VoicePayload("room-a", "player-1", "stale"));
            Send(SpeakingStopped, VoicePayload("room-a", "player-1", "activity-1"));
            Send(SpeakingStopped, VoicePayload("room-b", "player-1", "activity-2"));

            Assert.AreEqual(2, started.Count);
            Assert.AreEqual(2, stopped.Count);
            Assert.AreEqual("room-a", started[0].RoomId);
            Assert.AreEqual("player-1", started[0].PlayerId);
            Assert.AreEqual("activity-1", started[0].VoiceActivityId);
            Assert.AreEqual(1788775200123L, started[0].OccurredAtUnixMs);
        }

        [Test]
        public void StreamResetAndShutdown_ClearVoiceStateWithoutSyntheticStop()
        {
            var stops = 0;
            gameKitRuntime!.VoiceSpeakingStopped += _ => stops += 1;
            ((IIGPRuntimeExtension)gameKitRuntime).InitializeAsync(coreRuntime!, CancellationToken.None)
                .GetAwaiter().GetResult();
            Assert.IsTrue(gameKitRuntime.IsInitialized);

            Send(SpeakingStarted, VoicePayload("room-a", "player-1", "activity-1"));
            typeof(IGPRuntimeManager).GetMethod(
                "QueueHostServiceMessageStreamReset",
                BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(coreRuntime, null);
            typeof(IGPRuntimeManager).GetMethod(
                "Update",
                BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(coreRuntime, null);
            Assert.AreEqual(0, ActiveActivityCount());
            Assert.AreEqual(0, stops);

            Send(SpeakingStarted, VoicePayload("room-a", "player-1", "activity-2"));
            ((IIGPRuntimeExtension)gameKitRuntime).ShutdownAsync(CancellationToken.None)
                .GetAwaiter().GetResult();
            Assert.AreEqual(0, ActiveActivityCount());
            Assert.AreEqual(0, stops);
            Assert.IsFalse(gameKitRuntime.IsInitialized);
        }

        private static void AssertInternalConstructors(Type type)
        {
            Assert.AreEqual(0, type.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length);
            var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.AreEqual(1, constructors.Length);
            Assert.IsTrue(constructors[0].IsAssembly);
        }

        private static void AssertReadOnlyProperties(Type type, params string[] expectedNames)
        {
            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var names = Array.ConvertAll(properties, property => property.Name);
            Array.Sort(names, StringComparer.Ordinal);
            Array.Sort(expectedNames, StringComparer.Ordinal);
            CollectionAssert.AreEqual(expectedNames, names);
            Assert.IsTrue(Array.TrueForAll(
                properties,
                property => property.CanRead && property.GetSetMethod(true) == null));
        }

        private void Send(
            IGPHostServiceMessageSubcommand subcommand,
            string contentJson,
            string messageId = "message-1")
        {
            InvokePrivate(
                "HandleHostServiceMessage",
                new IGPHostServiceMessage(messageId, subcommand, contentJson));
        }

        private static string CommunicationPayload(string segments)
        {
            return "{\"schemaVersion\":1,\"roomId\":\"room-123\"," +
                "\"senderPlayerId\":\"player-456\",\"sentAtUnixMs\":1788775200123," +
                $"\"segments\":{segments}}}";
        }

        private static string VoicePayload(string roomId, string playerId, string activityId)
        {
            return $"{{\"schemaVersion\":1,\"roomId\":\"{roomId}\",\"playerId\":\"{playerId}\"," +
                $"\"voiceActivityId\":\"{activityId}\",\"occurredAtUnixMs\":1788775200123}}";
        }

        private int ActiveActivityCount()
        {
            return ((IDictionary)typeof(IGPGameKitRuntime)
                .GetField("activeVoiceActivityIds", BindingFlags.Instance | BindingFlags.NonPublic)!
                .GetValue(gameKitRuntime)!).Count;
        }

        private void InvokePrivate(string methodName, params object[] arguments)
        {
            typeof(IGPGameKitRuntime)
                .GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic)!
                .Invoke(gameKitRuntime, arguments);
        }
    }
}
