# toolkit/thread_pool.py
import threading
from concurrent.futures import ThreadPoolExecutor, Future
from vs_log_macros import VSC_INFO, VSC_ERROR

class ThreadPool:
    """
    @brief 线程池单例类
    模拟C++的ThreadPool，使用Python的ThreadPoolExecutor。
    """
    _instance = None
    _lock = threading.Lock()

    def __new__(cls, max_workers: int = 10):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._executor = ThreadPoolExecutor(max_workers=max_workers)
                VSC_INFO("thread_pool", "ThreadPool initialized with %d workers", max_workers)
            return cls._instance

    @staticmethod
    def getInstance(max_workers: int = 10):
        """获取线程池单例实例。"""
        return ThreadPool(max_workers)

    def enqueue(self, func, *args, **kwargs) -> Future:
        """
        @brief 提交任务到线程池。
        @param func 要执行的函数
        @param args 函数的位置参数
        @param kwargs 函数的关键字参数
        @return Future 对象，表示异步操作的结果
        """
        try:
            future = self._executor.submit(func, *args, **kwargs)
            return future
        except Exception as e:
            VSC_ERROR("thread_pool", "Failed to enqueue task: %s", str(e))
            raise

    def shutdown(self, wait: bool = True):
        """
        @brief 关闭线程池。
        @param wait 如果为True，则等待所有待处理的future完成。
        """
        if self._executor:
            VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)
            self._executor.shutdown(wait=wait)
            self._executor = None