// =============================================================================
//  heartbeat.cpp -- LED + uptime heartbeat task
// =============================================================================
//
//  Blinks PIN_DO5_ENGAGED_LAMP at 1 Hz to give a visible "the firmware is
//  alive" signal at the bench. In Sprint 1 we co-opt this LED because there
//  is no pilot to engage yet; from Sprint 6 onwards the engaged lamp will be
//  driven by the actual pilot state and the heartbeat will move to an
//  internal counter only.
//
//  Also logs uptime + free heap once per second so a terminal observer can
//  see the system is healthy.
// =============================================================================

#include <Arduino.h>

#include "../hal/pinout.h"
#include "ar_log.h"
#include "task_config.h"

namespace {
constexpr const char* TAG = "AR/SYS";
}  // namespace

static void HeartbeatTask(void* /*pv*/) {
    pinMode(PIN_DO5_ENGAGED_LAMP, OUTPUT);
    bool led_on = false;
    uint32_t tick = 0;

    AR_LOGI(TAG, "heartbeat task started on core %d, pin %d", xPortGetCoreID(),
            PIN_DO5_ENGAGED_LAMP);

    TickType_t last_wake = xTaskGetTickCount();
    for (;;) {
        led_on = !led_on;
        digitalWrite(PIN_DO5_ENGAGED_LAMP, led_on ? HIGH : LOW);

        AR_LOGD(TAG, "tick=%u uptime=%lus free_heap=%u min_free=%u", tick,
                millis() / 1000U, ESP.getFreeHeap(), ESP.getMinFreeHeap());

        ++tick;
        vTaskDelayUntil(&last_wake, pdMS_TO_TICKS(AR_PERIOD_MS_HEARTBEAT));
    }
}

void ar_start_heartbeat_task() {
    xTaskCreatePinnedToCore(HeartbeatTask, "heartbeat", AR_TASK_STACK_HEARTBEAT,
                            nullptr, AR_TASK_PRIO_HEARTBEAT, nullptr,
                            AR_TASK_CORE_COMMS);
}
