#include "spi_bus_manager.h"
#include "esp_log.h"
#include "esp_err.h"

#define TAG "spi_bus_mgr"

#define SHARED_SPI_HOST SPI2_HOST

// Pinos padrão (podem ser futuramente configuráveis)
#define PIN_NUM_MOSI 23
#define PIN_NUM_MISO 19
#define PIN_NUM_CLK  18

static bool initialized = false;

esp_err_t spi_bus_manager_init(void) {
    if (initialized) {
        ESP_LOGW(TAG, "SPI bus already initialized on host %d", SHARED_SPI_HOST);
        return ESP_OK;
    }

    spi_bus_config_t buscfg = {
        .mosi_io_num = PIN_NUM_MOSI,
        .miso_io_num = PIN_NUM_MISO,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 64,  // Ajustável conforme necessidade
    };

    esp_err_t ret = spi_bus_initialize(SHARED_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize SPI bus: %s", esp_err_to_name(ret));
        return ret;
    }

    initialized = true;
    ESP_LOGI(TAG, "SPI bus initialized on host %d", SHARED_SPI_HOST);
    return ESP_OK;
}

spi_host_device_t spi_bus_manager_get_host(void) {
    return SHARED_SPI_HOST;
}

bool spi_bus_manager_is_initialized(void) {
    return initialized;
}
