#include <windows.h>

#include <atomic>

#include "bootstrap/RuntimeHost.h"
#include "application/lifecycle/RuntimeState.h"
#include "adapters/windows/ModulePathCache.h"

namespace
{
    std::atomic<ta::bootstrap::RuntimeHost*> g_runtime_host{ nullptr };

    DWORD WINAPI runtime_thread(LPVOID parameter)
    {
        static ta::bootstrap::RuntimeHost host(static_cast<HMODULE>(parameter));
        g_runtime_host.store(&host, std::memory_order_release);
        const bool started = host.start();
        if (!started)
            g_runtime_host.store(nullptr, std::memory_order_release);
        return started ? 0UL : 1UL;
    }
}

extern "C" __declspec(dllexport) BOOL WINAPI TarkovAddonsRefactoredRequestShutdown()
{
    ta::bootstrap::RuntimeHost* host = g_runtime_host.load(std::memory_order_acquire);
    if (!host)
        return FALSE;

    host->stop();
    g_runtime_host.store(nullptr, std::memory_order_release);
    return ta::application::runtime::state().phase() == ta::application::runtime::RuntimePhase::Stopped ? TRUE : FALSE;
}

BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        DisableThreadLibraryCalls(module);

        // The launcher removes this module from the loader list after LoadLibrary
        // returns. Capture the path synchronously while the loader entry is valid.
        static_cast<void>(ta::adapters::windows::module_path_cache::capture(module));

        if (HANDLE thread = CreateThread(nullptr, 0, runtime_thread, module, 0, nullptr))
            CloseHandle(thread);
    }

    // Shutdown remains explicit. DllMain must not detach hooks or wait for
    // callbacks while the loader lock is held.
    return TRUE;
}
