"""M-24 Fake Dispatch 클라이언트.

외부 팀 위임 시스템 없이 위임 동작을 시뮬레이션한다.
실패 모드 설정으로 에러 처리 테스트도 가능하다.

Usage:
    fd = FakeDispatch()
    result = fd.dispatch("dev-team", "build feature X")
    assert result["status"] == "ok"
    assert result["team"] == "dev-team"
"""

from __future__ import annotations

import uuid
from typing import Any


class DispatchError(Exception):
    """FakeDispatch 실패 모드 예외."""


class FakeDispatch:
    """팀 위임을 시뮬레이션하는 Fake Dispatch 클라이언트."""

    def __init__(self) -> None:
        """초기화."""
        self.dispatch_count: int = 0
        self.last_team: str | None = None
        self.last_task: str | None = None
        self.dispatched: list[dict[str, Any]] = []
        self._should_fail: bool = False

    def dispatch(self, team: str, task: str, **kwargs: Any) -> dict[str, Any]:
        """팀에 작업을 위임하는 동작을 시뮬레이션한다.

        Args:
            team: 위임 대상 팀 이름.
            task: 작업 설명.
            **kwargs: 추가 파라미터 (기록에 포함됨).

        Returns:
            {"status": "ok", "task_id": str, "team": str} 형태의 결과.

        Raises:
            DispatchError: 실패 모드가 활성화된 경우.
        """
        if self._should_fail:
            raise DispatchError(f"Dispatch failed for team={team!r}, task={task!r}")

        task_id = str(uuid.uuid4())
        record: dict[str, Any] = {
            "status": "ok",
            "task_id": task_id,
            "team": team,
            "task": task,
            **kwargs,
        }
        self.dispatch_count += 1
        self.last_team = team
        self.last_task = task
        self.dispatched.append(record)
        return record

    def set_failure(self, should_fail: bool) -> None:
        """실패 모드를 설정한다.

        Args:
            should_fail: True이면 dispatch() 호출 시 예외 발생.
        """
        self._should_fail = should_fail

    def reset(self) -> None:
        """모든 상태를 초기화하고 실패 모드를 해제한다."""
        self.dispatch_count = 0
        self.last_team = None
        self.last_task = None
        self.dispatched = []
        self._should_fail = False
