#nullable enable
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using Google.Protobuf;
using IGP.Protocol.Arena.Game;
using IGP.Multiplayer.Models;
using IGP.Multiplayer.Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IGP.Multiplayer.Protocol
{
    // Only the header is parsed until a complete body is available.
    internal static class IGPGameProtocol
    {
        internal const string Protocol = "arena-protobuf";
        internal const int HeaderMaxBytes = 4096;
        internal static readonly JsonParser BodyParser = new JsonParser(new JsonParser.Settings(8).WithIgnoreUnknownFields(true));
        private static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true);
        private static readonly string[] Names = { "", "p2p_data", "custom", "state_set", "state_get", "state_reset", "scene_gate_set", "scene_gate_get", "rpc_register", "rpc_unregister", "rpc_call", "rpc_response", "ping", "pong", "game_finish", "error", "arena.peers.snapshot", "arena.message.aborted", "player_leave" };
        private static readonly string[] Schemas = { "", "P2PBody", "CustomBody", "StateSetBody", "StateGetBody", "StateResetBody", "SceneGateSetBody", "SceneGateGetBody", "RPCRegisterBody", "RPCUnregisterBody", "RPCCallBody", "RPCResponseBody", "PingBody", "PongBody", "GameFinishBody", "ErrorBody", "PeersSnapshotBody", "MessageAbortedBody", "PlayerLeaveBody" };

        internal static JToken ReadJson(byte[] bytes)
        {
            string json = Utf8.GetString(bytes);
            IGPJsonSyntax.Validate(json);
            using var reader = new JsonTextReader(new StringReader(json)) { MaxDepth = 8, DateParseHandling = DateParseHandling.None };
            var token = JToken.Load(reader, new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error, CommentHandling = CommentHandling.Load });
            if (reader.Read() || InvalidJson(token)) throw new InvalidOperationException("Invalid JSON value");
            return token;
        }

        private static bool InvalidJson(JToken token) => token.Type == JTokenType.Comment || token.Type == JTokenType.Undefined || token.Type == JTokenType.Constructor || token.Type == JTokenType.Float && (double.IsNaN(token.Value<double>()) || double.IsInfinity(token.Value<double>())) || token.Children().Any(InvalidJson);

        internal static byte[] Pack(GameHeader header, byte[] body) => Pack(header, body, 0, body.Length);

        internal static byte[] Pack(GameHeader header, byte[] body, int offset, int count)
        {
            Validate(header);
            int headerBytes = header.CalculateSize();
            if (headerBytes > HeaderMaxBytes) throw new InvalidOperationException("Game header too large");
            var record = new byte[checked(4 + headerBytes + count)];
            BinaryPrimitives.WriteUInt32BigEndian(record.AsSpan(0, 4), (uint)headerBytes);
            header.WriteTo(record.AsSpan(4, headerBytes));
            Buffer.BlockCopy(body, offset, record, 4 + headerBytes, count);
            return record;
        }

        internal static (GameHeader Header, ReadOnlyMemory<byte> Body) Unpack(byte[] record)
        {
            if (record.Length < 4) throw new InvalidOperationException("Truncated Game record");
            uint size = BinaryPrimitives.ReadUInt32BigEndian(record.AsSpan(0, 4));
            if (size == 0 || size > HeaderMaxBytes || size > record.Length - 4) throw new InvalidOperationException("Invalid Game header length");
            using var stream = new MemoryStream(record, 4, (int)size, false);
            using var input = CodedInputStream.CreateWithLimits(stream, HeaderMaxBytes, 8);
            var header = GameHeader.Parser.ParseFrom(input);
            Validate(header);
            // Synchronous view; reassembly and public callbacks detach before retention.
            return (header, record.AsMemory(4 + (int)size));
        }

        internal static void Validate(GameHeader h)
        {
            if (!h.HasType || (int)h.Type < 1 || (int)h.Type > 18 || !h.HasSenderSlot || !h.HasRoute || (int)h.Route < 1 || (int)h.Route > 4) throw new InvalidOperationException("Invalid Game header");
            if ((h.Route == Route.Targets) != (h.TargetSlots.Count > 0) || h.TargetSlots.Count > 64 || h.TargetSlots.Any(x => x == 0) || h.TargetSlots.Distinct().Count() != h.TargetSlots.Count) throw new InvalidOperationException("Invalid Game targets");
            if (h.Fragment != null && (h.Fragment.Id.Length != 16 || h.Fragment.Count == 0 || h.Fragment.Index >= h.Fragment.Count || h.Fragment.TotalBytes == 0 || h.Type == MessageType.Ping || h.Type == MessageType.Pong || h.Type == MessageType.P2P && h.Route != Route.Targets)) throw new InvalidOperationException("Invalid Game fragment");
        }

        internal static (GameHeader Header, byte[] Body) Encode(Message message, IGPDataPlanePeerTable peers)
        {
            if (!peers.IsActive) throw new InvalidOperationException("Game admission closed");
            if (message.type == "runtime.finished" || message.type.StartsWith("arena.", StringComparison.Ordinal)) throw new InvalidOperationException("Reserved system message");
            int type = Array.IndexOf(Names, message.type);
            if (type <= 0) type = (int)MessageType.Custom;
            if (type == 13 || type >= 15 && type != (int)MessageType.PlayerLeave) throw new InvalidOperationException("Client cannot send system messages");
            var header = new GameHeader { Type = (MessageType)type, SenderSlot = peers.PlayerSlot, Route = Route.Arena };
            var operation = EncodeTypedOperation(header.Type, message, peers);
            if (operation != null) return (header, operation.ToByteArray());
            JObject value = message.content == null || type == (int)MessageType.Custom || message.content is P2PMessagePayload || message.content is IGPReliableHeartbeatPayload ? new JObject() : JObject.FromObject(message.content);
            IMessage body;
            if (header.Type == MessageType.P2P)
            {
                var payload = message.content as P2PMessagePayload ?? value.ToObject<P2PMessagePayload>()!;
                body = new P2PBody { ApplicationMessageType = payload.messageType, Data = ByteString.CopyFrom(payload.ReadBytes()) };
                RouteMessage(header, peers, message.dataPlaneTargetPlayerIds, string.IsNullOrEmpty(payload.targetId) ? message.targetPlayerId : payload.targetId);
            }
            else if (header.Type == MessageType.Custom)
            {
                body = new CustomBody { Name = message.type, ContentJson = JsonBytes(message.content == null ? JValue.CreateNull() : JToken.FromObject(message.content)) };
                RouteMessage(header, peers, message.dataPlaneTargetPlayerIds, message.targetPlayerId);
            }
            else if (header.Type == MessageType.Ping)
            {
                body = message.content is IGPReliableHeartbeatPayload probe ? new PingBody { Seq = probe.Sequence } : new PingBody { Seq = value.Value<ulong?>("seq") ?? 0, ClientTimestamp = value.Value<long?>("clientTimestamp") ?? 0 };
            }
            else
            {
                if (header.Type == MessageType.StateSet) MoveJson(value, "value", "valueJson");
                if (header.Type == MessageType.RpcCall) { MoveJson(value, "data", "argumentsJson"); if (value.Value<string>("mode") == "host") value["hostSlot"] = peers.HostSlot; }
                if (header.Type == MessageType.RpcResponse)
                {
                    var caller = peers.GetCaller(message.targetPlayerId, value.Value<string>("name") ?? "", value.Value<string>("requestId") ?? "");
                    value["callerSlot"] = caller.Slot;
                    value["callerAdmissionId"] = caller.Admission;
                    // Keep the SDK's data/error result semantics in the schema's JSON value.
                    value["resultJson"] = Convert.ToBase64String(JsonBytes(new JObject { ["data"] = value["data"], ["error"] = value["error"] ?? "" }).ToByteArray());
                    value.Remove("data"); value.Remove("error");
                }
                if (type >= 3 && type <= 7 || (header.Type == MessageType.GameFinish || header.Type == MessageType.PlayerLeave)) value = new JObject { ["request"] = value };
                body = BodyParser.Parse(value.ToString(Formatting.None), Descriptor(header.Type));
            }
            return (header, body.ToByteArray());
        }

        // Normal SDK operations already have typed content. Only the public
        // arbitrary-object entry needs the JSON boundary adapter below.
        private static IMessage? EncodeTypedOperation(MessageType type, Message message, IGPDataPlanePeerTable peers)
        {
            switch (type)
            {
                case MessageType.StateSet when message.content is StateSetContent set:
                    return new StateSetBody { Request = new StateSetRequest { Scope = set.scope ?? "", Key = set.key ?? "", PlayerId = set.playerId ?? "", ValueJson = JsonBytes(Token(set.value)) } };
                case MessageType.StateGet when message.content is StateGetContent get:
                    return new StateGetBody { Request = new StateGetRequest { Scope = get.scope ?? "", Key = get.key ?? "", PlayerId = get.playerId ?? "" } };
                case MessageType.StateReset when message.content is StateResetContent reset:
                    var request = new StateResetRequest { Scope = reset.scope ?? "" };
                    if (reset.keysToExclude != null) request.KeysToExclude.Add(reset.keysToExclude);
                    return new StateResetBody { Request = request };
                case MessageType.SceneGateSet when message.content is SceneGateSetContent scene:
                    return new SceneGateSetBody { Request = new SceneGateValue { Value = scene.value ?? "" } };
                case MessageType.SceneGateGet when message.content == null:
                    return new SceneGateGetBody { Request = new Empty() };
                case MessageType.RpcRegister when message.content is RPCRegisterContent register:
                    return new RPCRegisterBody { Name = register.name ?? "" };
                case MessageType.RpcUnregister when message.content is RPCUnregisterContent unregister:
                    return new RPCUnregisterBody { Name = unregister.name ?? "" };
                case MessageType.RpcCall when message.content is RPCCallContent call:
                    return new RPCCallBody { Name = call.name ?? "", Mode = call.mode ?? "", RequestId = call.requestId ?? "", ArgumentsJson = JsonBytes(Token(call.data)), HostSlot = call.mode == "host" ? peers.HostSlot : 0 };
                case MessageType.RpcResponse when message.content is RPCResponseContent response:
                    var caller = peers.GetCaller(message.targetPlayerId, response.name ?? "", response.requestId ?? "");
                    return new RPCResponseBody { Name = response.name ?? "", RequestId = response.requestId ?? "", CallerSlot = caller.Slot, CallerAdmissionId = caller.Admission, ResultJson = JsonBytes(new JObject { ["data"] = Token(response.data), ["error"] = Token(response.error) }) };
                case MessageType.Ping when message.content is IGPReliableHeartbeatPayload ping:
                    return new PingBody { Seq = ping.Sequence };
                case MessageType.GameFinish when message.content == null:
                    return new GameFinishBody { Request = new Empty() };
                case MessageType.PlayerLeave when message.content == null:
                    return new PlayerLeaveBody { Request = new Empty() };
                default: return null;
            }
        }

        private static JToken Token(object? value) => value == null ? JValue.CreateNull() : JToken.FromObject(value);

        private static void RouteMessage(GameHeader header, IGPDataPlanePeerTable peers, string[]? targets, string target)
        {
            if (targets == null && string.IsNullOrEmpty(target)) { header.Route = Route.Others; return; }
            header.Route = Route.Targets;
            if (targets == null && target == "host") { header.TargetSlots.Add(peers.HostSlot); Validate(header); return; }
            foreach (string id in targets ?? new[] { target })
            {
                if (!peers.SlotByPlayerId.TryGetValue(id, out uint slot)) throw new InvalidOperationException("Unknown target player");
                header.TargetSlots.Add(slot);
            }
            Validate(header);
        }

        private static Google.Protobuf.Reflection.MessageDescriptor Descriptor(MessageType type) => ArenaGameReflection.Descriptor.MessageTypes.Single(x => x.Name == Schemas[(int)type]);
        internal static IMessage ParseBody(MessageType type, ReadOnlyMemory<byte> encoded, int maxBytes)
        {
            if (!MemoryMarshal.TryGetArray(encoded, out var bytes)) throw new InvalidOperationException("Game body must be array-backed");
            using var stream = new MemoryStream(bytes.Array!, bytes.Offset, bytes.Count, false);
            using var input = CodedInputStream.CreateWithLimits(stream, maxBytes, 8);
            return Descriptor(type).Parser.ParseFrom(input);
        }
        private static ByteString JsonBytes(JToken value)
        {
            var bytes = Utf8.GetBytes(value.ToString(Formatting.None));
            ReadJson(bytes);
            return ByteString.CopyFrom(bytes);
        }
        private static void MoveJson(JObject value, string from, string to)
        {
            value[to] = Convert.ToBase64String(JsonBytes(value[from] ?? JValue.CreateNull()).ToByteArray());
            value.Remove(from);
        }

        internal static Message Decode(GameHeader header, ReadOnlyMemory<byte> encoded, string roomId, IGPRealtimeTransport transport, IGPDataPlanePeerTable peers)
        {
            if (header.Type != MessageType.P2P && header.Type != MessageType.Custom && header.Type != MessageType.RpcCall && header.Type != MessageType.RpcResponse && header.SenderSlot != 0) throw new InvalidOperationException("Forged server message");
            var body = ParseBody(header.Type, encoded, peers.BodyMaxBytes);
            string sender = peers.PlayerIdBySlot.TryGetValue(header.SenderSlot, out var id) ? id : "";
            string target = header.TargetSlots.Count == 1 && peers.PlayerIdBySlot.TryGetValue(header.TargetSlots[0], out var recipient) ? recipient : "";
            object? content;
            string type = Names[(int)header.Type];
            if (body is P2PBody p) content = new P2PMessagePayload { senderId = sender, targetId = target, binaryData = p.Data.ToByteArray(), messageType = p.ApplicationMessageType, transportChannel = IGPP2PTransportChannels.Data, reliable = transport != IGPRealtimeTransport.Udp };
            else if (body is CustomBody c) { type = c.Name; content = ReadJson(c.ContentJson.ToByteArray()); if (Array.IndexOf(Names, type) >= 0 || type == "runtime.finished" || type.StartsWith("arena.", StringComparison.Ordinal)) throw new InvalidOperationException("Custom type conflicts with system type"); }
            else if (body is StateSetBody stateSet)
            {
                var result = stateSet.Result ?? throw new InvalidOperationException("Expected operation result");
                content = new StateSetContent { scope = result.Scope, key = result.Key, playerId = result.PlayerId, value = ReadJson(result.ValueJson.ToByteArray()).ToObject<object>(), reliable = true };
            }
            else if (body is StateGetBody stateGet)
            {
                var result = stateGet.Result ?? throw new InvalidOperationException("Expected operation result");
                content = new StateGetResponseContent { scope = result.Scope, key = result.Key, playerId = result.PlayerId, value = ReadJson(result.ValueJson.ToByteArray()).ToObject<object>() };
            }
            else if (body is StateResetBody stateReset)
            {
                var result = stateReset.Result ?? throw new InvalidOperationException("Expected operation result");
                content = new StateResetResponseContent { scope = result.Scope, playerId = result.PlayerId, keysToExclude = result.KeysToExclude.ToArray(), success = true };
            }
            else if (body is SceneGateSetBody sceneSet)
                content = new SceneGateSetContent { value = (sceneSet.Result ?? throw new InvalidOperationException("Expected operation result")).Value };
            else if (body is SceneGateGetBody sceneGet)
                content = new SceneGateGetContent { value = (sceneGet.Result ?? throw new InvalidOperationException("Expected operation result")).Value };
            else if (body is RPCCallBody rpcCall)
            {
                peers.RememberCaller(sender, rpcCall.Name, rpcCall.RequestId, header.SenderSlot, rpcCall.CallerAdmissionId);
                content = new RPCCallContent { name = rpcCall.Name, mode = rpcCall.Mode, requestId = rpcCall.RequestId, data = ReadJson(rpcCall.ArgumentsJson.ToByteArray()).ToObject<object>(), callerPlayerId = sender };
            }
            else if (body is RPCResponseBody rpcResponse)
            {
                var result = ReadJson(rpcResponse.ResultJson.ToByteArray());
                var response = new RPCResponseContent { name = rpcResponse.Name, requestId = rpcResponse.RequestId };
                if (result is JObject obj && obj["data"] != null && obj["error"] != null)
                {
                    response.data = obj["data"]!.ToObject<object>();
                    response.error = obj["error"]!.ToObject<string>()!;
                }
                else response.data = result.ToObject<object>();
                content = response;
            }
            else
            {
                var value = JObject.Parse(new JsonFormatter(new JsonFormatter.Settings(true)).Format(body));
                if (header.Type == MessageType.GameFinish) { value = value["finished"] as JObject ?? throw new InvalidOperationException("Expected finished notification"); type = "runtime.finished"; }
                content = value;
            }
            return new Message { type = type, roomId = roomId, playerId = sender, targetPlayerId = target, reliable = transport != IGPRealtimeTransport.Udp, content = content };
        }
    }
}
