// evse_core.c - Main EVSE control logic

#include "evse_fsm.h"
#include "evse_error.h"
#include "evse_limits.h"
#include "evse_config.h"
#include "evse_api.h"
#include "evse_session.h"
#include "evse_pilot.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_log.h"

static const char *TAG = "evse_core";

static SemaphoreHandle_t mutex;
static evse_state_t last_state = EVSE_STATE_A;

static void evse_core_task(void *arg);

// ================================
// Initialization
// ================================

void evse_init(void) {
    ESP_LOGI(TAG, "EVSE Init");

    mutex = xSemaphoreCreateMutex();  // Optional: use static version for deterministic memory

    evse_check_defaults();
    evse_fsm_reset();
    pilot_set_level(true);  // Enable pilot output

    xTaskCreate(evse_core_task, "evse_core_task", 4096, NULL, 5, NULL);
}

// ================================
// Main Processing Logic
// ================================

void evse_process(void) {
    xSemaphoreTake(mutex, portMAX_DELAY);

    pilot_voltage_t pilot_voltage;
    bool is_n12v = false;

    pilot_measure(&pilot_voltage, &is_n12v);
    ESP_LOGD(TAG, "Pilot: %d, -12V: %s", pilot_voltage, is_n12v ? "yes" : "no");

    evse_error_check(pilot_voltage, is_n12v);

    // Só chama FSM, que decide tudo
    evse_fsm_process(
        pilot_voltage,
        evse_state_get_authorized(),
        evse_config_is_available(),
        evse_config_is_enabled()
    );

    evse_limits_check();

    evse_state_t current = evse_get_state();
    if (current != last_state) {
        ESP_LOGI(TAG, "State changed: %s → %s",
                 evse_state_to_str(last_state),
                 evse_state_to_str(current));
        last_state = current;
    }

    evse_mark_error_cleared();

    xSemaphoreGive(mutex);
}

// ================================
// Background Task
// ================================

static void evse_core_task(void *arg) {
    while (true) {
        evse_process();
        vTaskDelay(pdMS_TO_TICKS(100));  // 10 Hz cycle
    }
}