"""Source-based termination condition."""

from typing import Optional, Sequence

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

from .base import BaseTermination


class SourceTermination(BaseTermination):
    """
    Terminates when a message from a specific named source is received.

    Matches the ``source`` field on every message.  More precise than
    ``TextMentionTermination`` for reviewer-gated and handoff workflows
    because it scopes the check to a single agent rather than scanning
    all message content.

    Args:
        source: The exact source name to watch (e.g. ``"reviewer"``).

    Example:
        # Stop as soon as the reviewer speaks
        termination = SourceTermination(source="reviewer")

        # Stop only when reviewer approves — agent-scoped AND content-scoped
        termination = (
            SourceTermination(source="reviewer")
            & TextMentionTermination("APPROVED")
        )
    """

    def __init__(self, source: str) -> None:
        super().__init__()
        if not source:
            raise ValueError("source cannot be empty")
        self.source = source

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Terminate when any new message matches the target source."""
        for message in new_messages:
            if not hasattr(message, "source"):
                continue
            if message.source == self.source:
                snippet = str(message.content)[:100] if hasattr(message, "content") else ""
                return self._set_termination(
                    f"Message received from source '{self.source}'",
                    {
                        "source": self.source,
                        "message_snippet": snippet,
                    },
                )
        return None
