"""External termination condition."""

from typing import Optional, Sequence

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

from .base import BaseTermination


class ExternalTermination(BaseTermination):
    """
    Terminates via external programmatic control.

    Allows external code to trigger termination by calling trigger().
    Useful for custom stopping logic that depends on external state.

    Example:
        termination = ExternalTermination()

        # In orchestration
        orchestrator = RoundRobinOrchestrator(
            agents=[agent1, agent2],
            termination=termination
        )

        # External control (e.g., from UI, monitoring system)
        if some_external_condition():
            termination.trigger("Custom stop reason")
    """

    def __init__(self):
        super().__init__()
        self._triggered = False
        self._trigger_reason = ""

    def trigger(self, reason: str = "External termination triggered"):
        """Trigger termination externally."""
        self._triggered = True
        self._trigger_reason = reason

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Check if termination has been triggered externally."""
        if self._triggered:
            return self._set_termination(
                self._trigger_reason,
                {
                    "externally_triggered": True,
                },
            )

        return None

    def reset(self) -> None:
        """Reset external trigger."""
        super().reset()
        self._triggered = False
        self._trigger_reason = ""
