namespace RioJoy.Core.Protocol;

/// <summary>
/// Streaming receive-side framing state machine, fed raw bytes from the serial
/// port. Faithful port of the framing loop in <c>ReadCommBlock</c>
/// (riovjoy2.cpp#L860); see docs/PROTOCOL.md §2.
///
/// <para>Rules:</para>
/// <list type="bullet">
///   <item>Outside a packet, a byte in the command range starts a packet whose
///   total length is <c>1 + payloadLen + 1</c> (command + payload + checksum).</item>
///   <item>Outside a packet, any other byte is reported as a
///   <see cref="RioRxEventKind.ControlByte"/> (ACK/NAK/RESTART/IDLE or garbage).</item>
///   <item>Mid-packet, a byte with the high bit set aborts the packet and
///   resynchronizes (<see cref="RioRxEventKind.FramingError"/>); that byte is
///   discarded, matching the legacy <c>continue</c>.</item>
///   <item>When the final (checksum) byte arrives, a
///   <see cref="RioRxEventKind.Packet"/> is emitted with
///   <see cref="RioRxEvent.ChecksumValid"/> set from a real checksum compare.</item>
/// </list>
///
/// Each input byte produces at most one event, so the per-byte
/// <see cref="Feed(byte, out RioRxEvent)"/> returns a single optional event.
/// This type is not thread-safe; drive it from one reader.
/// </summary>
public sealed class PacketParser
{
    // Max framed packet = command(1) + AnalogReply payload(10) + checksum(1) = 12.
    private const int MaxPacketBytes = 16;

    private readonly byte[] _buffer = new byte[MaxPacketBytes];

    // Bytes still expected to complete the current packet (0 = not in a packet).
    private int _remaining;

    // Count of bytes stored in _buffer for the current packet (incl. command).
    private int _count;

    /// <summary>True while a packet is partially received.</summary>
    public bool InPacket => _remaining != 0;

    /// <summary>Discard any in-progress packet and reset to the idle state.</summary>
    public void Reset()
    {
        _remaining = 0;
        _count = 0;
    }

    /// <summary>
    /// Feed one received byte. Returns <see langword="true"/> and sets
    /// <paramref name="ev"/> when this byte produced an event; otherwise returns
    /// <see langword="false"/> (the byte was consumed into an in-progress packet).
    /// </summary>
    public bool Feed(byte ch, out RioRxEvent ev)
    {
        if (_remaining != 0)
        {
            // Mid-packet. A high-bit byte is a framing error → abort and resync.
            if ((ch & 0x80) != 0)
            {
                Reset();
                ev = RioRxEvent.ForFramingError(ch);
                return true;
            }

            _buffer[_count++] = ch;
            _remaining--;

            if (_remaining == 0)
            {
                ev = CompletePacket();
                return true;
            }

            ev = default;
            return false;
        }

        // Not in a packet.
        if (RioCommandTable.IsCommand(ch))
        {
            _count = 0;
            _buffer[_count++] = ch;
            _remaining = RioCommandTable.PayloadLength(ch) + 1; // + checksum byte
            ev = default;
            return false;
        }

        // A byte outside framing: control character (ACK/NAK/RESTART/IDLE) or garbage.
        ev = RioRxEvent.ForControl(ch);
        return true;
    }

    /// <summary>
    /// Feed the first <paramref name="count"/> received bytes of
    /// <paramref name="data"/>, invoking <paramref name="onEvent"/> for each
    /// event produced, in order.
    /// </summary>
    public void Feed(byte[] data, int count, Action<RioRxEvent> onEvent)
    {
        if (data is null) throw new ArgumentNullException(nameof(data));
        if (onEvent is null) throw new ArgumentNullException(nameof(onEvent));
        for (int i = 0; i < count; i++)
        {
            if (Feed(data[i], out RioRxEvent ev))
                onEvent(ev);
        }
    }

    private RioRxEvent CompletePacket()
    {
        // _buffer = [command][payload…][checksum]; _count includes all of them.
        int bodyLen = _count - 1;             // command + payload (exclude checksum)
        byte receivedChecksum = _buffer[bodyLen];
        byte computed = RioChecksum.Compute(_buffer, 0, bodyLen);
        bool checksumValid = computed == receivedChecksum;

        var command = (RioCommand)_buffer[0];
        var payload = new byte[bodyLen - 1];  // copy out; buffer is reused
        Array.Copy(_buffer, 1, payload, 0, payload.Length);
        var packet = new RioPacket(command, payload);

        Reset();
        return RioRxEvent.ForPacket(packet, checksumValid);
    }
}
