#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"

char* util_read_file(const char *path) {
    FILE *fp = fopen(path, "rb");
    if (!fp) return NULL;
    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char *buf = malloc((size_t)len + 1);
    if (!buf) { fclose(fp); return NULL; }
    size_t n = fread(buf, 1, (size_t)len, fp);
    buf[n] = '\0';
    fclose(fp);
    return buf;
}

char* util_dirname(const char *path) {
    static char buf[512];
    strcpy(buf, path);
    char *p = strrchr(buf, '/');
    if (p) *p = '\0';
    else strcpy(buf, ".");
    return buf;
}

char* util_basename(const char *path) {
    static char buf[256];
    strcpy(buf, path);
    char *p = strrchr(buf, '/');
    return p ? p + 1 : buf;
}

char* util_strip_ext(const char *path) {
    static char buf[256];
    strcpy(buf, path);
    char *p = strrchr(buf, '.');
    if (p) *p = '\0';
    return buf;
}

int util_file_exists(const char *path) {
    return access(path, F_OK) == 0;
}

void util_trim_newline(char *str) {
    size_t len = strlen(str);
    if (len > 0 && str[len-1] == '\n') str[len-1] = '\0';
}
