#pragma once

#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <atomic>
#include <stdexcept>
#include <type_traits>

class ThreadPool {
public:
    explicit ThreadPool(size_t numThreads = std::thread::hardware_concurrency())
        : stopFlag(false)
    {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                for (;;) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queueMutex);
                        condition.wait(lock, [this] {
                            return stopFlag.load() || !tasks.empty();
                        });
                        if (stopFlag.load() && tasks.empty())
                            return;
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    ~ThreadPool() { shutdown(); }

    // Non-copyable, non-movable
    ThreadPool(const ThreadPool&)            = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;

    template <class F, class... Args>
    auto enqueue(F&& f, Args&&... args)
        // FIX: use decay_t so invoke_result matches what is actually stored —
        //      std::bind produced a wrapper whose result type differed from F's
        -> std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
    {
        using return_type =
            std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;

        // FIX: replace std::bind with tuple + std::apply — bind wrappers are
        //      not transparently invocable and break invoke_result deduction
        auto taskPtr = std::make_shared<std::packaged_task<return_type()>>(
            [func = std::forward<F>(f),
             args = std::make_tuple(std::forward<Args>(args)...)]() mutable
                -> return_type {
                return std::apply(func, args);
            }
        );

        std::future<return_type> result = taskPtr->get_future();
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            if (stopFlag.load())
                throw std::runtime_error("enqueue on stopped ThreadPool");
            tasks.emplace([taskPtr]() { (*taskPtr)(); });
        }
        condition.notify_one();
        return result;
    }

    // FIX: added size() — Engine.cpp called getNumThreads() which didn't exist
    size_t size() const { return workers.size(); }

    void shutdown() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stopFlag.store(true);
        }
        condition.notify_all();
        for (std::thread& worker : workers)
            if (worker.joinable())
                worker.join();
        workers.clear(); // safe to call shutdown() more than once
    }

private:
    std::vector<std::thread>           workers;
    std::queue<std::function<void()>>  tasks;
    std::mutex                         queueMutex;
    std::condition_variable            condition;
    std::atomic<bool>                  stopFlag;
};
