using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MessagePack;

namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;

/// <summary>
///     Reads length-prefixed, kind-tagged frames from a stream. Single-consumer — do not call
///     <see cref="ReadFrameAsync"/> from multiple threads against the same instance. Mirror of
///     Driver.Galaxy.Shared.FrameReader; sidecar carries its own copy so the deletion of
///     Galaxy.Shared in PR 7.2 doesn't reach the sidecar.
/// </summary>
public sealed class FrameReader : IDisposable
{
    private readonly Stream _stream;
    private readonly bool _leaveOpen;

    /// <summary>Initializes a new instance of the <see cref="FrameReader"/> class.</summary>
    /// <param name="stream">The stream to read frames from.</param>
    /// <param name="leaveOpen">Whether to leave the stream open when disposing.</param>
    public FrameReader(Stream stream, bool leaveOpen = false)
    {
        _stream = stream ?? throw new ArgumentNullException(nameof(stream));
        _leaveOpen = leaveOpen;
    }

    /// <summary>Reads the next frame asynchronously from the stream.</summary>
    /// <param name="ct">Cancellation token for the operation.</param>
    /// <returns>A tuple of message kind and body, or null if EOF is encountered cleanly.</returns>
    public async Task<(MessageKind Kind, byte[] Body)?> ReadFrameAsync(CancellationToken ct)
    {
        var lengthPrefix = new byte[Framing.LengthPrefixSize];
        if (!await ReadExactAsync(lengthPrefix, ct).ConfigureAwait(false))
            return null; // clean EOF on frame boundary

        var length = (lengthPrefix[0] << 24) | (lengthPrefix[1] << 16) | (lengthPrefix[2] << 8) | lengthPrefix[3];
        if (length < 0 || length > Framing.MaxFrameBodyBytes)
            throw new InvalidDataException($"Sidecar IPC frame length {length} out of range.");

        var kindByte = _stream.ReadByte();
        if (kindByte < 0) throw new EndOfStreamException("EOF after length prefix, before kind byte.");

        var body = new byte[length];
        if (!await ReadExactAsync(body, ct).ConfigureAwait(false))
            throw new EndOfStreamException("EOF mid-frame.");

        return ((MessageKind)(byte)kindByte, body);
    }

    /// <summary>Deserializes the message body to the specified type.</summary>
    /// <typeparam name="T">The type to deserialize to.</typeparam>
    /// <param name="body">The serialized message body.</param>
    public static T Deserialize<T>(byte[] body) => MessagePackSerializer.Deserialize<T>(body);

    private async Task<bool> ReadExactAsync(byte[] buffer, CancellationToken ct)
    {
        var offset = 0;
        while (offset < buffer.Length)
        {
            var read = await _stream.ReadAsync(buffer, offset, buffer.Length - offset, ct).ConfigureAwait(false);
            if (read == 0)
            {
                if (offset == 0) return false;
                throw new EndOfStreamException($"Stream ended after reading {offset} of {buffer.Length} bytes.");
            }
            offset += read;
        }
        return true;
    }

    /// <summary>Disposes the frame reader and optionally closes the underlying stream.</summary>
    public void Dispose()
    {
        if (!_leaveOpen) _stream.Dispose();
    }
}
