"""Team 多 Agent 协作 - Phase 10.1"""

from dataclasses import dataclass, field
from typing import Any
from enum import Enum


class TaskStatus(Enum):
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class TeamTask:
    """团队任务"""

    id: str
    description: str
    assignee: str | None = None
    status: TaskStatus = TaskStatus.PENDING
    result: Any = None
    error: str | None = None


class TeamLeader:
    """团队领导者

    协调多个 Agent 成员执行任务。
    """

    def __init__(self, team_id: str, members: list[str]):
        """
        Args:
            team_id: 团队 ID
            members: 成员 ID 列表
        """
        self.team_id = team_id
        self.members = members
        self._tasks: dict[str, TeamTask] = {}

    def create_task(self, description: str) -> str:
        """创建任务

        Args:
            description: 任务描述

        Returns:
            任务 ID
        """
        import uuid

        task_id = str(uuid.uuid4())[:8]
        self._tasks[task_id] = TeamTask(
            id=task_id,
            description=description,
        )
        return task_id

    def assign_task(self, task_id: str, member: str) -> bool:
        """分配任务

        Args:
            task_id: 任务 ID
            member: 成员 ID

        Returns:
            是否成功
        """
        if task_id not in self._tasks:
            return False

        if member not in self.members:
            return False

        self._tasks[task_id].assignee = member
        self._tasks[task_id].status = TaskStatus.IN_PROGRESS
        return True

    def broadcast_task(self, description: str) -> list[str]:
        """广播任务给所有成员

        Args:
            description: 任务描述

        Returns:
            创建的任务 ID 列表
        """
        task_ids = []
        for member in self.members:
            task_id = self.create_task(description)
            self.assign_task(task_id, member)
            task_ids.append(task_id)
        return task_ids

    def collect_results(self) -> dict[str, Any]:
        """收集所有任务结果

        Returns:
            任务 ID -> 结果的映射
        """
        return {
            task_id: task.result
            for task_id, task in self._tasks.items()
            if task.status == TaskStatus.COMPLETED
        }

    def get_team_status(self) -> dict[str, Any]:
        """获取团队状态

        Returns:
            团队状态摘要
        """
        return {
            "team_id": self.team_id,
            "members": self.members,
            "task_count": len(self._tasks),
            "completed": sum(1 for t in self._tasks.values() if t.status == TaskStatus.COMPLETED),
            "failed": sum(1 for t in self._tasks.values() if t.status == TaskStatus.FAILED),
        }
