#pragma once
#ifndef DYNLIBUTILS_H
#define DYNLIBUTILS_H

// ============================================================================
// DynLibUtils — Shared dynamic library loading utilities
//
// Common infrastructure used by EPLoader, NvDynLoader, CvLoader, OvLoader, etc.
// Consolidates duplicate utility functions that were previously in each loader.
// ============================================================================

#ifdef _WIN32
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <windows.h>
   using LibHandle = HMODULE;
#  define LIB_INVALID nullptr
#else
#  include <dlfcn.h>
   using LibHandle = void*;
#  define LIB_INVALID nullptr
#endif

#include <string>
#include <vector>
#include <iostream>

namespace ANSCENTER {
namespace DynLib {

    // ── Platform defaults ────────────────────────────────────────────────────
#ifdef _WIN32
    static constexpr const char* DEFAULT_SHARED_DIR =
        "C:\\ProgramData\\ANSCENTER\\Shared";
#else
    static constexpr const char* DEFAULT_SHARED_DIR =
        "/opt/anscenter/shared";
#endif

    // ── File / path helpers ──────────────────────────────────────────────────

    /// Returns true if @p path is a regular file.
    [[nodiscard]] bool FileExists(const std::string& path);

    /// Joins base + component with the platform separator.
    [[nodiscard]] std::string JoinPath(const std::string& base,
                                       const std::string& component);

    // ── DLL search-path injection ────────────────────────────────────────────

    /// Adds @p dir to the DLL search path.
    ///  - Windows: AddDllDirectory() + prepend to %PATH%
    ///  - Linux:   prepend to $LD_LIBRARY_PATH
    void InjectDllSearchPath(const std::string& dir);

    // ── Library loading ──────────────────────────────────────────────────────

    /// Iterates @p candidates, returns the first successfully loaded library.
    /// @param loadedPath  On success, receives the path/name that was loaded.
    /// @param verbose     Print discovery results to stdout.
    /// @param globalLoad  Linux only: use RTLD_GLOBAL (ignored on Windows).
    [[nodiscard]] LibHandle FindAndLoad(const std::vector<std::string>& candidates,
                                        std::string& loadedPath,
                                        bool verbose = true,
                                        bool globalLoad = false);

    /// Load a single library by path.
    /// @param globalLoad  Linux only: use RTLD_GLOBAL.
    [[nodiscard]] LibHandle LoadLib(const std::string& path, bool globalLoad = false);

    /// Free a loaded library handle.
    void FreeLib(LibHandle h);

    /// Get a symbol address from a loaded library.
    [[nodiscard]] void* GetSymbol(LibHandle h, const char* sym);

    // ── Type-safe symbol binding ─────────────────────────────────────────────

    /// Bind a function pointer from a loaded library handle.
    /// @returns true if the symbol was found and bound.
    template<typename Fn>
    [[nodiscard]] bool Bind(LibHandle h, const char* sym, Fn*& pfn)
    {
        pfn = reinterpret_cast<Fn*>(GetSymbol(h, sym));
        return pfn != nullptr;
    }

} // namespace DynLib
} // namespace ANSCENTER

#endif // DYNLIBUTILS_H
