#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Diagnostics;
using Google.Protobuf;
using IGP.Protocol.Arena.Game;
using IGP.Multiplayer.Models;
using Newtonsoft.Json.Linq;
using IGPLog = IGP.UnitySDK.IGPLog;

namespace IGP.Multiplayer.Protocol
{
    internal sealed class IGPDataPlanePeerTable
    {
        internal Func<double> Clock = () => Now;
        internal void CancelTarget(uint slot)
        {
            foreach (var key in partials.Where(p => p.Value.Header.SenderSlot == slot).Select(p => p.Key).ToArray()) Retire(key);
        }

        internal uint PlayerSlot { get; private set; }
        internal uint HostSlot { get; private set; }
        internal string MatchId { get; private set; } = "";
        internal string AdmissionId { get; private set; } = "";
        internal string UdpPermit { get; private set; } = "";
        internal string ReconnectToken { get; private set; } = "";
        internal IGPMatchEntryKind EntryKind { get; private set; }
        internal IReadOnlyDictionary<uint, Peer> PeerStates { get; private set; } = new Dictionary<uint, Peer>();
        internal IReadOnlyDictionary<string, uint> SlotByPlayerId { get; private set; } = new Dictionary<string, uint>();
        internal IReadOnlyDictionary<uint, string> PlayerIdBySlot { get; private set; } = new Dictionary<uint, string>();
        internal int BodyMaxBytes { get; private set; }
        internal int RecordMaxBytes { get; private set; }
        internal int FragmentMax { get; private set; }
        internal int PendingMax { get; private set; }
        internal int BufferMax { get; private set; }
        internal double TimeoutSeconds { get; private set; }
        private readonly Dictionary<string, Partial> partials = new Dictionary<string, Partial>();
        private readonly Dictionary<string, Caller> callers = new Dictionary<string, Caller>();
        private readonly Dictionary<string, double> retired = new Dictionary<string, double>();
        private long buffered;
        private bool closed;
        internal bool IsActive => !closed;
        internal static double Now => (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
        internal sealed class Caller { internal uint Slot; internal string Admission = ""; internal double Deadline; }
        private sealed class Partial
        {
            internal GameHeader Header = null!;
            internal byte[]?[] Pieces = null!;
            internal int Received, Bytes;
            internal long Budget;
            internal double Deadline;
        }

        internal static IGPDataPlanePeerTable FromHandshakeAck(JObject ack, string playerId)
        {
            if (ack.Value<string>("protocol") != IGPGameProtocol.Protocol) throw new InvalidOperationException("Unsupported Game protocol");
            var p = new IGPDataPlanePeerTable
            {
                EntryKind = ack.Value<string>("entryKind") == "initial" ? IGPMatchEntryKind.Initial :
                    ack.Value<string>("entryKind") == "reentry" ? IGPMatchEntryKind.Reentry : IGPMatchEntryKind.Unknown,
                PlayerSlot = ack.Value<uint?>("playerSlot") ?? 0,
                MatchId = ack.Value<string>("matchId") ?? "",
                AdmissionId = ack.Value<string>("admissionId") ?? "",
                ReconnectToken = ack.Value<string>("reconnectToken") ?? "",
                UdpPermit = ack.Value<string>("udpPermit") ?? ""
            };
            if (p.PlayerSlot == 0 || p.MatchId == "" || p.AdmissionId == "" || p.UdpPermit == "") throw new InvalidOperationException("Missing Game identity");
            var limits = ack["limits"] as JObject ?? throw new InvalidOperationException("Missing Game limits");
            int recordMax = limits.Value<int?>("maxRecordBytes") ?? 0;
            if (recordMax <= 0 || recordMax > 16384) throw new InvalidOperationException("Invalid maxRecordBytes");
            p.RecordMaxBytes = recordMax;
            // SDK-local resource policies; Arena negotiates only maxRecordBytes.
            p.BodyMaxBytes = 1024 * 1024;
            p.FragmentMax = 1024;
            p.PendingMax = 8;
            p.BufferMax = 4 * 1024 * 1024;
            p.TimeoutSeconds = IGPReliableTransportOptions.ReassemblyTimeoutSeconds;
            IGPLog.Info("game-session", "handshake", $"event=record-limit-received recordMaxBytes={p.RecordMaxBytes}");
            var snapshot = new PeersSnapshotBody { MatchId = p.MatchId, HostSlot = ack.Value<uint?>("hostSlot") ?? 0 };
            foreach (var item in ack["playerSlots"] as JArray ?? throw new InvalidOperationException("Missing Game peers")) snapshot.Peers.Add(new Peer { PlayerId = item.Value<string>("playerId") ?? "", Slot = item.Value<uint?>("slot") ?? 0, State = (PeerState)(item.Value<int?>("state") ?? 1), DisconnectDeadlineUnixMillis = item.Value<long?>("disconnectDeadlineUnixMillis") ?? 0 });
            p.Install(snapshot);
            if (!p.PlayerIdBySlot.TryGetValue(p.PlayerSlot, out string? actual) || actual != playerId) throw new InvalidOperationException("Game handshake identity mismatch");
            return p;
        }

        internal void Install(PeersSnapshotBody snapshot)
        {
            if (snapshot.MatchId != MatchId || snapshot.HostSlot == 0 || snapshot.Peers.Count > 64) throw new InvalidOperationException("Invalid peer snapshot");
            var slots = new Dictionary<string, uint>(StringComparer.Ordinal);
            var ids = new Dictionary<uint, string>();
            foreach (var peer in snapshot.Peers)
            {
                if (peer.PlayerId == "" || peer.Slot == 0 || slots.ContainsKey(peer.PlayerId) || ids.ContainsKey(peer.Slot)) throw new InvalidOperationException("Duplicate or invalid Game peer");
                slots.Add(peer.PlayerId, peer.Slot); ids.Add(peer.Slot, peer.PlayerId);
            }
            if (!ids.ContainsKey(PlayerSlot)) throw new InvalidOperationException("Local admission removed");
            if (PlayerIdBySlot.TryGetValue(PlayerSlot, out var localIdentity) && ids[PlayerSlot] != localIdentity)
                throw new InvalidOperationException("Local admission identity changed");
            foreach (var key in partials.Where(x => !ids.ContainsKey(x.Value.Header.SenderSlot) && x.Value.Header.SenderSlot != 0).Select(x => x.Key).ToArray()) Retire(key);
            HostSlot = snapshot.HostSlot; SlotByPlayerId = slots; PlayerIdBySlot = ids;
            PeerStates = snapshot.Peers.ToDictionary(x => x.Slot, x => x.Clone());
        }

        internal void RememberCaller(string player, string name, string request, uint slot, string admission)
        {
            Sweep();
            if (player == "" || admission == "") throw new InvalidOperationException("Missing RPC caller identity");
            string key = player + "\0" + name + "\0" + request;
            if (!callers.ContainsKey(key) && callers.Count >= 1024) throw new InvalidOperationException("RPC reply budget exceeded");
            // An old asynchronous reply with the same public name/request/player key
            // must never be rebound to a later admission.
            if (callers.TryGetValue(key, out var previous) && (previous.Slot != slot || previous.Admission != admission)) throw new InvalidOperationException("Ambiguous RPC reply identity");
            callers[key] = new Caller { Slot = slot, Admission = admission, Deadline = Now + 30 };
        }
        internal Caller GetCaller(string player, string name, string request)
        {
            Sweep();
            if (!callers.TryGetValue(player + "\0" + name + "\0" + request, out var caller)) throw new InvalidOperationException("RPC caller is no longer valid");
            if (!PlayerIdBySlot.TryGetValue(caller.Slot, out var current) || current != player) throw new InvalidOperationException("RPC caller has left");
            return caller;
        }

        internal bool CanEncodeP2PPayload(string target, int bytes, uint messageType, int maxRecord)
        {
            if (closed || bytes <= 0 || !SlotByPlayerId.TryGetValue(target, out uint slot)) return false;
            // P2PBody's two protobuf fields, without allocating or copying its data bytes.
            int bodyBytes = checked((messageType == 0 ? 0 : 1 + CodedOutputStream.ComputeUInt32Size(messageType)) +
                1 + CodedOutputStream.ComputeLengthSize(bytes) + bytes);
            if (bodyBytes > BodyMaxBytes) return false;
            var header = new GameHeader { Type = MessageType.P2P, SenderSlot = PlayerSlot, Route = Route.Targets };
            header.TargetSlots.Add(slot);
            int limit = Math.Min(maxRecord, RecordMaxBytes);
            if (4 + header.CalculateSize() + bodyBytes <= limit)
                return 8L + header.CalculateSize() + bodyBytes <= IGPReliableTransportOptions.BusinessPendingByteLimit;
            header.Fragment = new Fragment { Id = ByteString.CopyFrom(new byte[16]),
                Count = (uint)FragmentMax, Index = (uint)FragmentMax - 1, TotalBytes = (uint)bodyBytes };
            int capacity = FragmentPayloadCapacity(header, limit);
            if (capacity <= 0) return false;
            int count = (bodyBytes + capacity - 1) / capacity;
            if (count > FragmentMax) return false;
            header.Fragment.Count = (uint)count;
            long encodedBytes = bodyBytes;
            for (int i = 0; i < count; i++)
            {
                header.Fragment.Index = (uint)i;
                encodedBytes += 8 + header.CalculateSize(); // Game header length + transport framing.
            }
            return encodedBytes <= IGPReliableTransportOptions.BusinessPendingByteLimit;
        }

        private static int FragmentPayloadCapacity(GameHeader header, int limit) => limit - 4 - header.CalculateSize();

        internal IEnumerable<byte[]> Encode(Message message, int maxRecord)
        {
            if (closed) throw new InvalidOperationException("Game admission closed");
            var (header, body) = IGPGameProtocol.Encode(message, this);
            if (body.Length > BodyMaxBytes)
            {
                IGPLog.Error("game-session", "encode", $"event=rejected reason=logical-message-too-large bodyBytes={body.Length} logicalMaxBytes={BodyMaxBytes}");
                throw new InvalidOperationException("Game body too large");
            }
            int limit = Math.Min(maxRecord, RecordMaxBytes);
            if (4 + header.CalculateSize() + body.Length <= limit) { yield return IGPGameProtocol.Pack(header, body); yield break; }
            if (header.Type != MessageType.P2P && header.Type != MessageType.Custom)
                throw new InvalidOperationException("Arena operation must fit one Game record");
            if (header.Route == Route.Others)
            {
                header.Route = Route.Targets;
                header.TargetSlots.Add(PlayerIdBySlot.Keys.Where(x => x != PlayerSlot));
            }
            if (header.Route == Route.Host) { header.Route = Route.Targets; header.TargetSlots.Add(HostSlot); }
            var id = new byte[16]; using (var random = RandomNumberGenerator.Create()) random.GetBytes(id);
            header.Fragment = new Fragment { Id = ByteString.CopyFrom(id), Count = (uint)FragmentMax, Index = (uint)FragmentMax - 1, TotalBytes = (uint)body.Length };
            int bytesPerPiece = FragmentPayloadCapacity(header, limit);
            if (bytesPerPiece <= 0) throw new InvalidOperationException("Record cannot fit fragment header");
            int count = (body.Length + bytesPerPiece - 1) / bytesPerPiece;
            if (count > FragmentMax)
            {
                IGPLog.Error("game-session", "encode", $"event=rejected reason=fragment-count-exceeded fragmentCount={count} fragmentMax={FragmentMax} recordMaxBytes={limit}");
                throw new InvalidOperationException("Too many Game fragments");
            }
            IGPLog.Warning("game-session", "fragment", $"event=created fragmentCount={count} logicalBytes={body.Length} recordMaxBytes={limit} messageType={header.Type}");
            header.Fragment.Count = (uint)count;
            for (int i = 0; i < count; i++)
            {
                header.Fragment.Index = (uint)i;
                int offset = i * bytesPerPiece;
                int countBytes = Math.Min(bytesPerPiece, body.Length - offset);
                yield return IGPGameProtocol.Pack(header, body, offset, countBytes);
            }
        }

        internal Message? Decode(byte[] record, string roomId, IGPRealtimeTransport transport)
        {
            if (closed) return null;
            Sweep();
            if (record.Length > RecordMaxBytes) throw new InvalidOperationException("Game record exceeds maxRecordBytes");
            var (header, body) = IGPGameProtocol.Unpack(record);
            if (header.SenderSlot != 0 && !PlayerIdBySlot.ContainsKey(header.SenderSlot)) return null;
            if (transport == IGPRealtimeTransport.Udp && (header.Fragment != null || header.Type != MessageType.P2P && header.Type != MessageType.Custom)) return null;
            if (body.Length > BodyMaxBytes) throw new InvalidOperationException("Game body too large");
            if (header.Type == MessageType.MessageAborted)
            {
                if (header.SenderSlot != 0 || header.Fragment != null) throw new InvalidOperationException("Invalid abort notification");
                var abort = (MessageAbortedBody)IGPGameProtocol.ParseBody(header.Type, body, BodyMaxBytes);
                if (abort.MessageId.Length != 16) throw new InvalidOperationException("Invalid abort identity");
                Retire(Key(abort.SenderSlot, abort.MessageId));
            }
            if (header.Fragment != null)
            {
                var f = header.Fragment;
                if (f.Count > FragmentMax || f.TotalBytes > BodyMaxBytes || body.Length == 0 || body.Length > f.TotalBytes) throw new InvalidOperationException("Fragment limit exceeded");
                string key = Key(header.SenderSlot, f.Id);
                if (retired.ContainsKey(key)) return null;
                var canonical = header.Clone(); canonical.Fragment.Index = 0;
                if (!partials.TryGetValue(key, out var state))
                {
                    long budget = 2L * f.TotalBytes + 64L * f.Count + canonical.CalculateSize();
                    if (partials.Count >= PendingMax || budget + buffered > BufferMax) throw new InvalidOperationException("Reassembly budget exceeded");
                    state = new Partial { Header = canonical, Pieces = new byte[]?[checked((int)f.Count)], Budget = budget, Deadline = Clock() + TimeoutSeconds };
                    partials.Add(key, state); buffered += budget;
                }
                if (!state.Header.Equals(canonical)) { Close(); throw new InvalidOperationException("Fragment metadata conflict"); }
                int index = checked((int)f.Index);
                if (state.Pieces[index] != null)
                {
                    if (!state.Pieces[index]!.AsSpan().SequenceEqual(body.Span)) { Close(); throw new InvalidOperationException("Fragment data conflict"); }
                    return null;
                }
                state.Pieces[index] = body.ToArray(); state.Bytes += body.Length; state.Received++;
                if (state.Bytes > f.TotalBytes) throw new InvalidOperationException("Fragment total exceeded");
                if (state.Received != f.Count) return null;
                if (state.Bytes != f.TotalBytes) throw new InvalidOperationException("Fragment total mismatch");
                var assembled = new byte[state.Bytes]; int offset = 0;
                foreach (var piece in state.Pieces) { Buffer.BlockCopy(piece!, 0, assembled, offset, piece!.Length); offset += piece.Length; }
                body = assembled;
                header = canonical; header.Fragment = null;
                Retire(key);
            }
            if (header.Type == MessageType.PeersSnapshot)
            {
                if (header.SenderSlot != 0) throw new InvalidOperationException("Forged peer snapshot");
                Install((PeersSnapshotBody)IGPGameProtocol.ParseBody(header.Type, body, BodyMaxBytes));
            }
            return IGPGameProtocol.Decode(header, body, roomId, transport, this);
        }
        private static string Key(uint sender, ByteString id) => sender + ":" + Convert.ToBase64String(id.ToByteArray());
        private void Retire(string key)
        {
            if (partials.TryGetValue(key, out var state)) { buffered -= state.Budget; partials.Remove(key); }
            if (!retired.ContainsKey(key) && retired.Count >= 4096) throw new InvalidOperationException("Fragment replay budget exceeded");
            retired[key] = Clock() + TimeoutSeconds;
        }
        internal void Sweep()
        {
            if (closed) throw new InvalidOperationException("Game admission closed");
            double now = Clock();
            foreach (var key in callers.Where(x => x.Value.Deadline <= now).Select(x => x.Key).ToArray()) callers.Remove(key);
            foreach (var key in retired.Where(x => x.Value <= now).Select(x => x.Key).ToArray()) retired.Remove(key);
            if (partials.Values.Any(x => x.Deadline <= now)) { Close(); throw new InvalidOperationException("Incomplete Game message expired"); }
        }
        internal void Close() { closed = true; partials.Clear(); callers.Clear(); retired.Clear(); buffered = 0; UdpPermit = ""; ReconnectToken = ""; }
    }
}
