#include "PathUtils.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#include <limits.h>
#endif

#include <algorithm>

namespace UsdLayerManager {

std::string ExeDir()
{
#ifdef _WIN32
    wchar_t wpath[MAX_PATH] = {};
    DWORD len = ::GetModuleFileNameW(nullptr, wpath, MAX_PATH);
    if (len == 0 || len >= MAX_PATH)
        return "./";

    // Convert UTF-16 → UTF-8
    int needed = ::WideCharToMultiByte(CP_UTF8, 0, wpath, static_cast<int>(len),
                                       nullptr, 0, nullptr, nullptr);
    std::string path(static_cast<size_t>(needed), '\0');
    ::WideCharToMultiByte(CP_UTF8, 0, wpath, static_cast<int>(len),
                          path.data(), needed, nullptr, nullptr);
#else
    char buf[PATH_MAX] = {};
    ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
    if (len <= 0)
        return "./";
    std::string path(buf, static_cast<size_t>(len));
#endif

    // Normalise to forward slashes and strip the filename
    std::replace(path.begin(), path.end(), '\\', '/');
    auto slash = path.rfind('/');
    if (slash != std::string::npos)
        path = path.substr(0, slash + 1); // keep trailing '/'
    else
        path = "./";

    return path;
}

std::string ResourcePath(const std::string& relativePath)
{
    return ExeDir() + relativePath;
}

} // namespace UsdLayerManager
