import asyncio

from typing import Callable, List


class SimpleTaskManager:
    def __init__(self, max_concurrent: int = 10):
        self.semaphore = asyncio.Semaphore(max_concurrent)
        self.results = []

    async def execute_task(self, task_id: int, coro_func: Callable, *args, **kwargs):
        """执行单个任务"""
        async with self.semaphore:
            try:
                result = await coro_func(*args, **kwargs)
                self.results.append((task_id, result))
                print(f"✅ 任务 {task_id} 完成")
                distribution_after_hook(*result)
                return result
            except Exception as e:
                error_msg = f"任务 {task_id} 失败: {e}"
                self.results.append((task_id, error_msg))
                print(f"❌ {error_msg}")
                return None

    async def process_all(self, tasks: List[tuple]):
        """
        处理所有任务
        tasks: 列表，每个元素是 (coro_func, args, kwargs) 元组
        """
        print(f"🚀 开始处理 {len(tasks)} 个任务，最大并发数: {self.semaphore._value}")

        # 创建所有任务
        task_coroutines = []
        for i, (coro_func, args, kwargs) in enumerate(tasks):
            task_coroutines.append(self.execute_task(i, coro_func, *args, **kwargs))

        # 并发执行所有任务
        await asyncio.gather(*task_coroutines)

        print(f"🎉 所有任务完成！成功: {len([r for r in self.results if '失败' not in str(r[1])])}")
        return self.results
