// =============================================================================
//  safety/safety_monitor.h -- safety monitor task
// =============================================================================
//
//  50 Hz task on Core 1 that:
//      - Polls every DI through hal::di_poll().
//      - Reacts to PIN_DI1_DISENGAGE_BUTTON rising edge: forces STANDBY,
//        kills actuator power.
//      - Reacts to limit switches: cuts actuator power if both assert.
//      - Reacts to PIN_DI4_EXTERNAL_ALARM (VMS critical): forces STANDBY.
//      - Subscribes itself to the TWDT and feeds it every loop iteration.
//
//  Sprint 6: full alarm catalogue -- off-course, rudder not responding,
//  heading lost, actuator overcurrent, voltage low, limit switch reached,
//  watchdog tripped, VMS critical.
//
//  Alarm bits are written by the 50 Hz safety task and read on demand by the
//  Modbus slave (FC 0x02 discrete inputs). All reads/writes are protected by
//  a portMUX critical section.
// =============================================================================

#pragma once

#include <cstdint>

namespace arautopilot::safety {

/// Spawn the safety monitor task. Must be called AFTER di_init(),
/// rudder_sensor_start_task(), and pid_outer_task_start().
void safety_monitor_start_task();

/// Live alarm bits -- true when the corresponding condition is active.
/// Updated at 50 Hz by the safety task. Read by the Modbus slave handler.
struct AlarmBits {
    bool off_course         = false;
    bool off_course_severe  = false;
    bool rudder_not_resp    = false;
    bool heading_lost       = false;
    bool actuator_overcurr  = false;
    bool voltage_low        = false;
    bool limit_reached      = false;
    bool watchdog_tripped   = false;
    bool vms_critical       = false;

    bool any() const {
        return off_course | off_course_severe | rudder_not_resp
             | heading_lost | actuator_overcurr | voltage_low
             | limit_reached | watchdog_tripped | vms_critical;
    }
};

/// Return a thread-safe snapshot of the current alarm bits.
AlarmBits safety_alarm_bits();

/// Force-set the watchdog-tripped bit. Called once at boot if
/// esp_reset_reason() == ESP_RST_TASK_WDT.
void safety_set_watchdog_tripped();

}  // namespace arautopilot::safety
