#ifndef OTA_ADAPTER_H
#define OTA_ADAPTER_H

#include <cstdint>
#include <cstddef>
#include "config.h"

// OTA Model Update Adapter
//
// Double-buffered PSRAM model slots allow hot-swapping TFLite models
// without interrupting inference. The T2 gateway sends delta-encoded
// model chunks via LoRa (MSG_TYPE_OTA_CHUNK). Once all chunks are
// received and verified, the new model is swapped in atomically.

// OTA chunk sub-header (appended after the standard 33-byte detection header):
// [33]     chunk_index (1 byte)
// [34]     total_chunks (1 byte)
// [35-36]  chunk_crc16 (2 bytes)
// [37-38]  model_version (2 bytes)
// [39...]  payload (up to 220 bytes to stay under 260-byte LoRa payload)

#define OTA_CHUNK_HEADER_SIZE  7   // bytes after main packet header
#define OTA_MAX_CHUNK_PAYLOAD  220
#define OTA_MAX_CHUNKS         255

// Initialize OTA adapter (allocate double-buffer in PSRAM)
bool ota_init();

// Handle an incoming OTA chunk packet. Call from main loop when
// msg_type == MSG_TYPE_OTA_CHUNK.
// Returns true if this chunk was accepted.
bool ota_handle_chunk(const uint8_t* data, size_t len);

// Check if a complete model has been received and is ready to swap.
bool ota_model_ready();

// Perform the model hot-swap. Calls classifier_swap_model() internally.
// Returns true on success.
bool ota_apply_model();

// Get the version of the currently staged model (0 if none)
uint16_t ota_staged_version();

// Get the version of the currently active model
uint16_t ota_active_version();

// Reset OTA state (discard any partially-received model)
void ota_reset();

// Free OTA resources
void ota_deinit();

#endif // OTA_ADAPTER_H
