/**
 * @file hal_semaphore.c
 * @brief HAL 信号量实现（JieLi 平台）
 */

#include "hal_semaphore.h"
#include "os/os_api.h"
#include <stdlib.h>

hal_sem_t hal_sem_create(uint32_t initial_count)
{
    OS_SEM *sem = (OS_SEM *)zalloc(sizeof(OS_SEM));
    if (!sem) {
        return NULL;
    }
    os_sem_create(sem, initial_count);
    return (hal_sem_t)sem;
}

int hal_sem_wait(hal_sem_t sem, uint32_t timeout_ms)
{
    if (!sem) {
        return -1;
    }
    int timeout_ticks = 0;
    if (timeout_ms == HAL_SEM_WAIT_FOREVER) {
        timeout_ticks = 0; /* JieLi: 0 means wait forever */
    } else {
        timeout_ticks = timeout_ms / 10; /* JieLi tick = 10ms */
        if (timeout_ticks == 0 && timeout_ms > 0) {
            timeout_ticks = 1;
        }
    }
    int ret = os_sem_pend((OS_SEM *)sem, timeout_ticks);
    return (ret == OS_NO_ERR) ? 0 : -1;
}

int hal_sem_post(hal_sem_t sem)
{
    if (!sem) {
        return -1;
    }
    os_sem_post((OS_SEM *)sem);
    return 0;
}

void hal_sem_destroy(hal_sem_t sem)
{
    if (!sem) {
        return;
    }
    os_sem_del((OS_SEM *)sem, 0);
    free(sem);
}
