#ifndef LORA_H
#define LORA_H

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

#include "main.h"
#include "sx126x.h"

typedef enum
{
    LORA_EVENT_NONE = 0,
    LORA_EVENT_TX_DONE,
    LORA_EVENT_TIMEOUT,
    LORA_EVENT_RX_DONE,
    LORA_EVENT_CRC_ERROR,
    LORA_EVENT_IRQ_ERROR
} lora_event_t;

/**
 * Initialize the Wio-SX1262 for:
 *
 * 915 MHz
 * LoRa modulation
 * SF7
 * 125 kHz bandwidth
 * Coding rate 4/5
 * +14 dBm TX power
 */
sx126x_status_t LoRa_Init(SPI_HandleTypeDef *spi);

/**
 * Start transmitting one LoRa packet.
 *
 * This function starts TX but does not wait for completion.
 * Call LoRa_Process() repeatedly until LoRa_IsTxInProgress()
 * becomes false.
 */
sx126x_status_t LoRa_Send(
    const uint8_t *payload,
    uint8_t payload_length);

/**
 * Called from the STM32 GPIO EXTI callback when DIO1 rises.
 *
 * This only records the interrupt. It performs no SPI operations.
 */
void LoRa_OnDio1Interrupt(void);

/**
 * Process a pending SX1262 DIO1 interrupt.
 *
 * Call from the main loop, not from the hardware ISR.
 */
lora_event_t LoRa_Process(void);

/**
 * True while the radio is waiting for TX_DONE or TIMEOUT.
 */
bool LoRa_IsTxInProgress(void);

/**
 * Cancel the local TX-wait state and return the radio to standby.
 *
 * Useful when the MCU-side timeout expires.
 */
sx126x_status_t LoRa_AbortTx(void);

/**
 * Put the SX1262 into continuous LoRa receive mode.
 */
sx126x_status_t LoRa_StartReceive(void);

/**
 * Read the packet that caused LORA_EVENT_RX_DONE.
 *
 * payload_capacity is the size of the caller's buffer.
 * payload_length receives the actual number of bytes copied.
 * packet_status may be NULL if RSSI/SNR are not required.
 */
sx126x_status_t LoRa_ReadReceivedPacket(
    uint8_t *payload,
    uint8_t payload_capacity,
    uint8_t *payload_length,
    sx126x_pkt_status_lora_t *packet_status);

#endif