#include "paths.h"
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>

#define ASSETS_PATH_MAX (PATH_MAX + 64)

static char g_assetsDir[ASSETS_PATH_MAX];

static bool is_dir(const char *path) {
    struct stat st;
    return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
}

void paths_init(void) {
    char exePath[PATH_MAX];
    ssize_t n = readlink("/proc/self/exe", exePath, sizeof(exePath) - 1);
    if (n > 0) {
        exePath[n] = '\0';
        char *slash = strrchr(exePath, '/');
        if (slash) {
            *slash = '\0'; /* exePath is now the executable's own directory, e.g. .../bin */
            char candidate[ASSETS_PATH_MAX];
            snprintf(candidate, sizeof candidate, "%s/../share/hush/assets", exePath);
            if (is_dir(candidate)) {
                snprintf(g_assetsDir, sizeof g_assetsDir, "%s", candidate);
                return;
            }
        }
    }
    /* No install found next to the executable (or /proc/self/exe isn't available on this
       platform) -- fall back to the source tree, so `./build/hush` keeps working unmodified. */
    snprintf(g_assetsDir, sizeof g_assetsDir, "%s", ASSETS_DIR);
}

const char *paths_assets_dir(void) {
    return g_assetsDir;
}
