/**
 * @file uart_trans.h
 * @brief Bare-metal UART DMA/IDLE transport and MUX framing helpers.
 */

#ifndef __UART_TRANS_H__
#define __UART_TRANS_H__

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

#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
    UART_CHANNEL_U0 = 0,
    UART_CHANNEL_U1 = 1,
    UART_CHANNEL_MAX
} uart_channel_t;

typedef struct {
    uint8_t src_id;
    uint8_t dst_mask;
    uint16_t payload_len;
    uint8_t payload[256];
} uart_mux_frame_t;

#define UART_RX_DMA_BUFFER_SIZE   256u
#define UART_TX_DMA_BUFFER_SIZE   256u
#define UART_RX_RING_BUFFER_SIZE  512u
#define UART_TX_RING_BUFFER_SIZE  384u
#define UART_DEFAULT_BAUDRATE     115200u

typedef struct {
    uint32_t baudrate;
} uart_config_t;

typedef struct {
    uint32_t rx_bytes;
    uint32_t tx_bytes;
    uint32_t rx_packets;
    uint32_t tx_packets;
    uint32_t idle_events;
    uint32_t rx_half_events;
    uint32_t rx_full_events;
    uint32_t errors;
} uart_stats_t;

int uart_trans_init(void);
int uart_trans_config(uart_channel_t channel, const uart_config_t *config);
int uart_trans_start(uart_channel_t channel);
int uart_trans_stop(uart_channel_t channel);
void uart_trans_poll(void);
uint16_t uart_trans_rx_available(uart_channel_t channel);
uint16_t uart_trans_read(uart_channel_t channel, uint8_t *data, uint16_t max_len);
uint16_t uart_trans_write(uart_channel_t channel, const uint8_t *data, uint16_t len);
uint16_t uart_trans_tx_free(uart_channel_t channel);
void uart_trans_get_stats(uart_channel_t channel, uart_stats_t *stats);
void uart_trans_reset_stats(uart_channel_t channel);
void uart_trans_idle_handler(uart_channel_t channel);
void uart_trans_rx_half_cplt_handler(uart_channel_t channel);
void uart_trans_rx_cplt_handler(uart_channel_t channel);
void uart_trans_tx_cplt_handler(uart_channel_t channel);
bool uart_mux_try_extract_frame(uart_channel_t channel, uart_mux_frame_t *frame);
bool uart_mux_encode_frame(uint8_t src_id,
                           uint8_t dst_mask,
                           const uint8_t *payload,
                           uint16_t payload_len,
                           uint8_t *out,
                           uint16_t *out_len,
                           uint16_t out_capacity);

#ifdef __cplusplus
}
#endif

#endif /* __UART_TRANS_H__ */
