#ifndef AIW_STREAM_H
#define AIW_STREAM_H

#include "ai_wire.h"

#include <stdbool.h>
#include <stdint.h>

#define AIW_STREAM_DEFAULT_TIMEOUT_MS 20u

typedef struct {
    uint8_t bytes[AIW_MAX_PACKET_BYTES];
    uint16_t used;
    uint16_t expected_length;
    uint32_t last_byte_ms;
    uint32_t interbyte_timeout_ms;
    uint32_t accepted_frames;
    uint32_t rejected_headers;
    uint32_t rejected_frames;
    uint32_t timed_out_frames;
    uint32_t discarded_bytes;
    uint32_t transport_resets;
} aiw_stream;

/* timeout_ms must be nonzero and below 2^31 for wrap-safe elapsed-time checks. */
bool aiw_stream_init(aiw_stream *stream, uint32_t timeout_ms);

/* Drop a partial frame after UART overrun/error; diagnostic counters are preserved. */
void aiw_stream_abort(aiw_stream *stream);

/* Feed one received byte. Returns true for one CRC-valid supported AIW v2 message. */
bool aiw_stream_push_message(aiw_stream *stream, uint8_t byte, uint32_t now_ms,
                             aiw_message *message);

/* Compatibility wrapper: consumes all supported messages and returns true only for AI_RESULT. */
bool aiw_stream_push(aiw_stream *stream, uint8_t byte, uint32_t now_ms,
                     aiw_result *result);

#endif
