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

namespace IGP.UnitySDK.GameKit
{
    [RequireComponent(typeof(IGPRuntimeManager))]
    public sealed class IGPGameKitRuntime : MonoBehaviour, IIGPRuntimeExtension
    {
        private readonly Dictionary<VoiceActivityKey, string> activeVoiceActivityIds =
            new Dictionary<VoiceActivityKey, string>();
        private IGPRuntimeManager? coreRuntime;
        private IIGPHostServiceMessageSource? hostServiceMessageSource;

        public bool IsInitialized { get; private set; }

        public event Action<IGPVoiceSpeakingEvent>? VoiceSpeakingStarted;
        public event Action<IGPVoiceSpeakingEvent>? VoiceSpeakingStopped;
        public event Action<IGPCommunicationMessageEvent>? CommunicationMessageReceived;

        int IIGPRuntimeExtension.InitializationOrder => 200;

        /// <summary>
        /// Explicitly sends a match result through DesktopSessionServiceMessage.
        /// Requires initialized GameKit and an attached Host Session. Completion means
        /// transport send completed, not Host acceptance or persistence. No automatic
        /// reply, pending request, retry, or protocol timeout is created.
        /// </summary>
        public async Task ReportMatchResultAsync(
            IGPMatchResultReport report,
            CancellationToken cancellationToken = default)
        {
            var messageId = Guid.NewGuid().ToString("N");
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (!IsInitialized || coreRuntime == null)
                    throw new InvalidOperationException("GameKit runtime is not initialized.");

                var json = IGPMatchResultReportSerializer.Serialize(report);
                await coreRuntime.SendHostServiceMessageAsync(new IGPHostServiceMessage(
                    messageId, IGPHostServiceMessageSubcommand.GameKitMatchResultReport, json), cancellationToken);
            }
            catch (Exception exception)
            {
                IGPLog.Warning("game-kit", "match-result-report",
                    $"event=send-failed direction=sdk-to-host subcommand=GameKitMatchResultReport " +
                    $"messageId={messageId} result=failed errorType={exception.GetType().Name}");
                throw;
            }
        }

        private void Awake()
        {
            coreRuntime = GetComponent<IGPRuntimeManager>();
        }

        Task<bool> IIGPRuntimeExtension.InitializeAsync(
            IIGPRuntimeContext context,
            CancellationToken cancellationToken)
        {
            UnsubscribeFromHostServiceMessages();
            if (coreRuntime == null || !ReferenceEquals(coreRuntime, context))
            {
                IGPLog.Warning(
                    "game-kit",
                    "service-message",
                    "event=initialize result=runtime-context-invalid");
                return Task.FromResult(false);
            }

            hostServiceMessageSource = context as IIGPHostServiceMessageSource;
            if (hostServiceMessageSource == null)
            {
                IGPLog.Warning(
                    "game-kit",
                    "service-message",
                    "event=initialize result=source-unavailable");
                return Task.FromResult(false);
            }

            hostServiceMessageSource.ServiceMessageReceived += HandleHostServiceMessage;
            hostServiceMessageSource.ServiceMessageStreamReset += HandleServiceMessageStreamReset;
            IsInitialized = true;
            IGPLog.Info(
                "game-kit",
                "service-message",
                "event=initialize result=subscribed");
            return Task.FromResult(true);
        }

        Task IIGPRuntimeExtension.ShutdownAsync(CancellationToken cancellationToken)
        {
            ShutdownServiceMessages("runtime-shutdown");
            return Task.CompletedTask;
        }

        private void OnDestroy()
        {
            ShutdownServiceMessages("component-destroyed");
        }

        private void ShutdownServiceMessages(string reason)
        {
            UnsubscribeFromHostServiceMessages();
            activeVoiceActivityIds.Clear();
            IsInitialized = false;
            IGPLog.Info(
                "game-kit",
                "service-message",
                $"event=shutdown result=complete reason={IGPLog.FormatValue(reason)}");
        }

        private void UnsubscribeFromHostServiceMessages()
        {
            if (hostServiceMessageSource == null)
            {
                return;
            }

            hostServiceMessageSource.ServiceMessageReceived -= HandleHostServiceMessage;
            hostServiceMessageSource.ServiceMessageStreamReset -= HandleServiceMessageStreamReset;
            hostServiceMessageSource = null;
        }

        private void HandleHostServiceMessage(IGPHostServiceMessage message)
        {
            switch (message.Subcommand)
            {
                case IGPHostServiceMessageSubcommand.GameKitCommunicationVoiceSpeakingStarted:
                case IGPHostServiceMessageSubcommand.GameKitCommunicationVoiceSpeakingStopped:
                    HandleVoiceActivityMessage(message);
                    return;
                case IGPHostServiceMessageSubcommand.GameKitCommunicationMessage:
                    HandleCommunicationMessage(message);
                    return;
                default:
                    LogIgnored(message, "unknown-subcommand");
                    return;
            }
        }

        private void HandleVoiceActivityMessage(IGPHostServiceMessage message)
        {
            VoiceActivityPayload? payload;
            try
            {
                payload = JsonConvert.DeserializeObject<VoiceActivityPayload>(message.ContentJson);
            }
            catch (JsonException)
            {
                LogIgnored(message, "invalid-json");
                return;
            }
            catch (ArgumentException)
            {
                LogIgnored(message, "invalid-json");
                return;
            }

            if (!IsValidVoiceActivityPayload(payload))
            {
                LogIgnored(message, "invalid-payload");
                return;
            }

            var voicePayload = payload!;
            var key = new VoiceActivityKey(voicePayload.RoomId, voicePayload.PlayerId);
            var voiceEvent = new IGPVoiceSpeakingEvent(
                voicePayload.RoomId,
                voicePayload.PlayerId,
                voicePayload.VoiceActivityId,
                voicePayload.OccurredAtUnixMs);

            if (message.Subcommand ==
                IGPHostServiceMessageSubcommand.GameKitCommunicationVoiceSpeakingStarted)
            {
                if (activeVoiceActivityIds.TryGetValue(key, out var currentActivityId) &&
                    string.Equals(currentActivityId, voicePayload.VoiceActivityId, StringComparison.Ordinal))
                {
                    LogProcessed(message, "duplicate-ignored");
                    return;
                }

                activeVoiceActivityIds[key] = voicePayload.VoiceActivityId;
                VoiceSpeakingStarted?.Invoke(voiceEvent);
                LogProcessed(message, "event-emitted");
                return;
            }

            if (!activeVoiceActivityIds.TryGetValue(key, out var activeActivityId) ||
                !string.Equals(activeActivityId, voicePayload.VoiceActivityId, StringComparison.Ordinal))
            {
                LogProcessed(message, "stale-ignored");
                return;
            }

            activeVoiceActivityIds.Remove(key);
            VoiceSpeakingStopped?.Invoke(voiceEvent);
            LogProcessed(message, "event-emitted");
        }

        private void HandleCommunicationMessage(IGPHostServiceMessage message)
        {
            CommunicationMessagePayload? payload;
            try
            {
                payload = JsonConvert.DeserializeObject<CommunicationMessagePayload>(message.ContentJson);
            }
            catch (JsonException)
            {
                LogIgnored(message, "invalid-json");
                return;
            }
            catch (ArgumentException)
            {
                LogIgnored(message, "invalid-json");
                return;
            }

            if (!TryBuildCommunicationEvent(message, payload, out var communicationEvent))
            {
                LogIgnored(message, "invalid-payload");
                return;
            }

            CommunicationMessageReceived?.Invoke(communicationEvent!);
            IGPLog.Info(
                "game-kit",
                "service-message",
                $"event=processed subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                $"messageId={IGPLog.FormatValue(message.MessageId)} result=event-emitted " +
                $"segmentCount={communicationEvent!.Segments.Count}");
        }

        private static bool TryBuildCommunicationEvent(
            IGPHostServiceMessage message,
            CommunicationMessagePayload? payload,
            out IGPCommunicationMessageEvent? communicationEvent)
        {
            communicationEvent = null;
            if (payload == null ||
                payload.SchemaVersion != 1 ||
                string.IsNullOrWhiteSpace(message.MessageId) ||
                string.IsNullOrWhiteSpace(payload.RoomId) ||
                string.IsNullOrWhiteSpace(payload.SenderPlayerId) ||
                payload.SentAtUnixMs <= 0 ||
                payload.Segments == null ||
                payload.Segments.Count == 0)
            {
                return false;
            }

            var segments = new List<IGPCommunicationSegment>(payload.Segments.Count);
            foreach (var segment in payload.Segments)
            {
                if (segment == null)
                {
                    return false;
                }

                if (string.Equals(segment.Type, "text", StringComparison.Ordinal))
                {
                    if (segment.Text == null || segment.Text.Length == 0)
                    {
                        return false;
                    }
                    segments.Add(new IGPCommunicationTextSegment(segment.Text));
                    continue;
                }

                if (string.Equals(segment.Type, "emotion", StringComparison.Ordinal))
                {
                    if (string.IsNullOrWhiteSpace(segment.EmotionId))
                    {
                        return false;
                    }
                    segments.Add(new IGPCommunicationEmotionSegment(segment.EmotionId));
                    continue;
                }

                return false;
            }

            communicationEvent = new IGPCommunicationMessageEvent(
                message.MessageId,
                payload.RoomId,
                payload.SenderPlayerId,
                payload.SentAtUnixMs,
                segments);
            return true;
        }

        private static bool IsValidVoiceActivityPayload(VoiceActivityPayload? payload)
        {
            return payload != null &&
                payload.SchemaVersion == 1 &&
                !string.IsNullOrWhiteSpace(payload.RoomId) &&
                !string.IsNullOrWhiteSpace(payload.PlayerId) &&
                !string.IsNullOrWhiteSpace(payload.VoiceActivityId) &&
                payload.OccurredAtUnixMs > 0;
        }

        private static void LogProcessed(IGPHostServiceMessage message, string result)
        {
            IGPLog.Info(
                "game-kit",
                "service-message",
                $"event=processed subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                $"messageId={IGPLog.FormatValue(message.MessageId)} result={IGPLog.FormatValue(result)}");
        }

        private static void LogIgnored(IGPHostServiceMessage message, string reason)
        {
            IGPLog.Warning(
                "game-kit",
                "service-message",
                $"event=ignored subcommand={IGPLog.FormatValue(message.Subcommand.ToString())} " +
                $"messageId={IGPLog.FormatValue(message.MessageId)} reason={IGPLog.FormatValue(reason)}");
        }

        private void HandleServiceMessageStreamReset()
        {
            var clearedCount = activeVoiceActivityIds.Count;
            activeVoiceActivityIds.Clear();
            IGPLog.Info(
                "game-kit",
                "service-message",
                $"event=stream-reset result=state-cleared count={clearedCount}");
        }

        private sealed class VoiceActivityPayload
        {
            [JsonProperty("schemaVersion")]
            public int SchemaVersion { get; set; }

            [JsonProperty("roomId")]
            public string RoomId { get; set; } = string.Empty;

            [JsonProperty("playerId")]
            public string PlayerId { get; set; } = string.Empty;

            [JsonProperty("voiceActivityId")]
            public string VoiceActivityId { get; set; } = string.Empty;

            [JsonProperty("occurredAtUnixMs")]
            public long OccurredAtUnixMs { get; set; }
        }

        private sealed class CommunicationMessagePayload
        {
            [JsonProperty("schemaVersion")]
            public int SchemaVersion { get; set; }

            [JsonProperty("roomId")]
            public string RoomId { get; set; } = string.Empty;

            [JsonProperty("senderPlayerId")]
            public string SenderPlayerId { get; set; } = string.Empty;

            [JsonProperty("sentAtUnixMs")]
            public long SentAtUnixMs { get; set; }

            [JsonProperty("segments")]
            public List<CommunicationSegmentPayload>? Segments { get; set; }
        }

        private sealed class CommunicationSegmentPayload
        {
            [JsonProperty("type")]
            public string Type { get; set; } = string.Empty;

            [JsonProperty("text")]
            public string? Text { get; set; }

            [JsonProperty("emotionId")]
            public string? EmotionId { get; set; }
        }

        private readonly struct VoiceActivityKey : IEquatable<VoiceActivityKey>
        {
            private readonly string roomId;
            private readonly string playerId;

            internal VoiceActivityKey(string roomId, string playerId)
            {
                this.roomId = roomId;
                this.playerId = playerId;
            }

            public bool Equals(VoiceActivityKey other)
            {
                return string.Equals(roomId, other.roomId, StringComparison.Ordinal) &&
                    string.Equals(playerId, other.playerId, StringComparison.Ordinal);
            }

            public override bool Equals(object? obj)
            {
                return obj is VoiceActivityKey other && Equals(other);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    return ((roomId != null ? StringComparer.Ordinal.GetHashCode(roomId) : 0) * 397) ^
                        (playerId != null ? StringComparer.Ordinal.GetHashCode(playerId) : 0);
                }
            }
        }
    }
}
