/**
 * @file hal_file.c
 * @brief HAL 文件读写实现（JieLi 平台）
 */

#include "hal_file.h"
#include <stdio.h>
#include <string.h>

hal_file_t hal_file_open(const char *path, const char *mode)
{
    if (!path || !mode) {
        return NULL;
    }
    FILE *fp = fopen(path, mode);
    return (hal_file_t)fp;
}

int hal_file_read(hal_file_t file, void *buf, size_t len)
{
    if (!file || !buf || len == 0) {
        return -1;
    }
    size_t n = fread(buf, 1, len, (FILE *)file);
    return (int)n;
}

int hal_file_write(hal_file_t file, const void *buf, size_t len)
{
    if (!file || !buf || len == 0) {
        return -1;
    }
    size_t n = fwrite(buf, 1, len, (FILE *)file);
    return (int)n;
}

int hal_file_close(hal_file_t file)
{
    if (!file) {
        return -1;
    }
    return fclose((FILE *)file);
}

int hal_file_size(hal_file_t file)
{
    if (!file) {
        return -1;
    }
    FILE *fp = (FILE *)file;
    long cur = ftell(fp);
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, cur, SEEK_SET);
    return (int)size;
}

bool hal_file_exists(const char *path)
{
    if (!path) {
        return false;
    }
    FILE *fp = fopen(path, "r");
    if (fp) {
        fclose(fp);
        return true;
    }
    return false;
}
