// =============================================================================
//  hal/nvs_config.h -- NVS-backed calibration store (Sprint 7)
// =============================================================================
//
//  Persists commissioning data to the ESP32 NVS (Non-Volatile Storage) under
//  the namespace "ar_cal".
//
//  Keys written:
//    "adc_port"   -- int16_t  raw ADC at full-port rudder limit
//    "adc_stbd"   -- int16_t  raw ADC at full-stbd rudder limit
//    "rud_port"   -- float    physical angle at port limit (deg, default -35)
//    "rud_stbd"   -- float    physical angle at stbd limit (deg, default +35)
//    "ou_kp"      -- float    outer-loop recommended Kp from commissioning
//    "ou_ki"      -- float    outer-loop recommended Ki
//    "ou_kd"      -- float    outer-loop recommended Kd
//    "commissioned"-- uint8_t 1 if the unit has been commissioned
//
//  All reads/writes are synchronous and should only be called at startup or
//  from a low-priority task (not the 50 Hz safety task).
// =============================================================================

#pragma once

#include <cstdint>

namespace arautopilot::hal {

struct CalibrationData {
    int16_t adc_port         = 0;       ///< raw ADC at port limit
    int16_t adc_stbd         = 4095;    ///< raw ADC at stbd limit
    float   rudder_port_deg  = -35.0f;  ///< physical port angle
    float   rudder_stbd_deg  =  35.0f;  ///< physical stbd angle
    float   outer_kp         = 1.0f;    ///< recommended outer Kp
    float   outer_ki         = 0.0f;    ///< recommended outer Ki
    float   outer_kd         = 0.0f;    ///< recommended outer Kd
    bool    commissioned     = false;   ///< true once commissioning ran
};

/// Initialise the NVS namespace.  Must be called from setup() before any
/// other nvs_config function.  Returns false if NVS flash is unrecoverable
/// (factory reset required).
bool nvs_config_init();

/// Read calibration data from NVS.  Returns default values if the key is
/// absent (first boot or factory-reset).
CalibrationData nvs_config_load();

/// Write calibration data to NVS.
bool nvs_config_save(const CalibrationData& cal);

/// Erase the entire "ar_cal" namespace (factory reset).
bool nvs_config_erase();

}  // namespace arautopilot::hal
