"""Cancellation termination condition."""

from typing import Optional, Sequence

from agentbyte.cancellation_token import CancellationToken
from agentbyte.messages import Message
from agentbyte.types import StopMessage

from .base import BaseTermination


class CancellationTermination(BaseTermination):
    """
    Terminates when a CancellationToken is triggered.

    Allows external cancellation of orchestration through a shared
    cancellation token.

    Example:
        from agentbyte import CancellationToken

        token = CancellationToken()
        termination = CancellationTermination(token)

        # In another thread/task:
        token.cancel()  # Will trigger termination
    """

    def __init__(self, cancellation_token: CancellationToken):
        super().__init__()
        if cancellation_token is None:
            raise ValueError("cancellation_token cannot be None")
        self.cancellation_token = cancellation_token

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Check if cancellation has been requested."""
        if self.cancellation_token.is_cancelled():
            return self._set_termination(
                "Cancellation requested",
                {
                    "cancellation_token": str(self.cancellation_token),
                },
            )

        return None
