#include "shared_spi_bus.h"
#include "pico/mutex.h"
#include "pico/multicore.h"
#include <stdbool.h>

static mutex_t g_spi_bus_mutex;
static bool g_spi_bus_initialized = false;
static uint32_t g_core_depth[2] = {0, 0};

void shared_spi_bus_init(void) {
    if (g_spi_bus_initialized) {
        return;
    }

    mutex_init(&g_spi_bus_mutex);
    g_spi_bus_initialized = true;
}

void shared_spi_bus_lock(void) {
    if (!g_spi_bus_initialized) {
        shared_spi_bus_init();
    }

    int core = get_core_num();
    if (core < 0 || core > 1) {
        core = 0;
    }

    // Re-entrant lock on same core (needed for nested SD helpers).
    if (g_core_depth[core] > 0) {
        g_core_depth[core]++;
        return;
    }

    mutex_enter_blocking(&g_spi_bus_mutex);
    g_core_depth[core] = 1;
}

void shared_spi_bus_unlock(void) {
    if (!g_spi_bus_initialized) {
        return;
    }

    int core = get_core_num();
    if (core < 0 || core > 1) {
        core = 0;
    }

    if (g_core_depth[core] == 0) {
        return;
    }

    g_core_depth[core]--;
    if (g_core_depth[core] == 0) {
        mutex_exit(&g_spi_bus_mutex);
    }
}

void shared_spi_bus_force_recover(void) {
    // Used after Core1 reset to avoid stale mutex/depth state.
    mutex_init(&g_spi_bus_mutex);
    g_core_depth[0] = 0;
    g_core_depth[1] = 0;
    g_spi_bus_initialized = true;
}
