#include "adapters/windows/storage/RuntimeStorageLayout.h"

#include <mutex>
#include <system_error>

#include "adapters/windows/ModulePathCache.h"
#include "foundation/io/FileSystemUtils.h"

namespace ta::adapters::windows::storage
{
    namespace
    {
        std::mutex g_mutex;
        std::optional<RuntimeStorageLayout> g_layout;

    }

    bool initialize() noexcept
    {
        try
        {
            const auto module_directory = module_path_cache::directory();
            if (!module_directory)
                return false;

            RuntimeStorageLayout next{};
            next.root = *module_directory;
            next.logs = next.root / L"logs";
            next.locales = next.root / L"locales";

            if (!ta::foundation::io::ensure_directory(next.logs) ||
                !ta::foundation::io::ensure_directory(next.locales))
            {
                return false;
            }


            std::scoped_lock lock(g_mutex);
            g_layout = std::move(next);
            return true;
        }
        catch (...)
        {
            return false;
        }
    }

    void reset() noexcept
    {
        std::scoped_lock lock(g_mutex);
        g_layout.reset();
    }

    std::optional<RuntimeStorageLayout> snapshot() noexcept
    {
        std::scoped_lock lock(g_mutex);
        return g_layout;
    }
}
