#include "system_init.h"

#include "esp_event.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#include "esp_log.h"

#include "wifidevnum_config.h"
#include "ota_manager.h"

static const char *tag_s = "SYS_INIT";

esp_err_t system_core_init(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    /* 初始化 OTA 管理器（检查上次OTA状态，如有必要则回退） */
    ret = ota_manager_init();
    if (ret != ESP_OK) {
        ESP_LOGW(tag_s, "OTA manager triggered rollback, restarting...");
        /* ota_manager_init 内部会调用 esp_restart() */
        /* 如果能走到这里，说明没有触发回退，继续启动 */
    }

    ESP_ERROR_CHECK(init_spiffs());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    return ESP_OK;
}

