/*==============================================================================
 * dr_util.c - BLE response formatting helpers
 *
 * Convenience wrappers used by command handlers to assemble and transmit
 * short BLE responses. Each helper prepends a 4-char TAG and writes the
 * supplied uint16 values in Big-Endian order.
 *============================================================================*/

#include "dr_util.h"
#include "parser.h"

extern void single_format_data(uint8_t *buffer, const char *tag, uint16_t value);
extern void format_data(uint8_t *buffer, const char *tag, uint16_t *data, uint8_t length);
extern uint8_t ble_bin_buffer[];
extern void dr_binary_tx_safe(uint8_t const *ble_bin_buff, uint16_t length);

void dr_ble_return_1(const char *tag, uint16_t value)
{
    single_format_data(ble_bin_buffer, tag, value);
    dr_binary_tx_safe(ble_bin_buffer, 3);  /* Use safe TX with retry */
}

void dr_ble_return_2(const char *tag, uint16_t v1, uint16_t v2)
{
    ble_bin_buffer[0] = tag[0];
    ble_bin_buffer[1] = tag[1];
    ble_bin_buffer[2] = tag[2];
    ble_bin_buffer[3] = tag[3];

    ble_bin_buffer[4] = (uint8_t)(v1 >> 8);
    ble_bin_buffer[5] = (uint8_t)(v1 & 0xFF);
    ble_bin_buffer[6] = (uint8_t)(v2 >> 8);
    ble_bin_buffer[7] = (uint8_t)(v2 & 0xFF);

    dr_binary_tx_safe(ble_bin_buffer, 4);  /* Use safe TX with retry */
}

void dr_ble_return_3(const char *tag, uint16_t v1, uint16_t v2, uint16_t v3)
{
    ble_bin_buffer[0] = tag[0];
    ble_bin_buffer[1] = tag[1];
    ble_bin_buffer[2] = tag[2];
    ble_bin_buffer[3] = tag[3];

    ble_bin_buffer[4] = (uint8_t)(v1 >> 8);
    ble_bin_buffer[5] = (uint8_t)(v1 & 0xFF);
    ble_bin_buffer[6] = (uint8_t)(v2 >> 8);
    ble_bin_buffer[7] = (uint8_t)(v2 & 0xFF);
    ble_bin_buffer[8] = (uint8_t)(v3 >> 8);
    ble_bin_buffer[9] = (uint8_t)(v3 & 0xFF);

    dr_binary_tx_safe(ble_bin_buffer, 5);  /* Use safe TX with retry */
}

void dr_ble_debug(uint16_t point_id, uint16_t value)
{
    /* Use dedicated buffer to avoid conflicts with ble_bin_buffer */
    static uint8_t dbg_buffer[8] = {0};

    dbg_buffer[0] = 'd';
    dbg_buffer[1] = 'b';
    dbg_buffer[2] = 'g';
    dbg_buffer[3] = ':';

    dbg_buffer[4] = (uint8_t)(point_id >> 8);
    dbg_buffer[5] = (uint8_t)(point_id & 0xFF);
    dbg_buffer[6] = (uint8_t)(value >> 8);
    dbg_buffer[7] = (uint8_t)(value & 0xFF);

    dr_binary_tx_safe(dbg_buffer, 4);
}

void dr_ble_return_piezo_1(const char *tag, uint16_t value)
{
    /* Use dedicated buffer for piezo responses to avoid conflicts with ble_bin_buffer */
    static uint8_t piezo_buffer[8] = {0};

    piezo_buffer[0] = tag[0];
    piezo_buffer[1] = tag[1];
    piezo_buffer[2] = tag[2];
    piezo_buffer[3] = tag[3];

    piezo_buffer[4] = (uint8_t)(value >> 8);
    piezo_buffer[5] = (uint8_t)(value & 0xFF);

    dr_binary_tx_safe(piezo_buffer, 3);  /* 6 bytes = 3 words */
}
