"""Text mention termination condition."""

from typing import Optional, Sequence

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

from .base import BaseTermination


class TextMentionTermination(BaseTermination):
    """
    Terminates when specific text appears in message content.

    Searches for exact substring match (case-sensitive by default).
    Useful for agent-controlled termination (e.g., "TERMINATE", "APPROVED").

    Example:
        # Case-sensitive (default)
        termination = TextMentionTermination("TERMINATE")

        # Case-insensitive
        termination = TextMentionTermination("done", case_sensitive=False)

        # Combine with other conditions
        termination = (
            MaxMessageTermination(10) | TextMentionTermination("DONE")
        )
    """

    def __init__(self, text: str, case_sensitive: bool = True):
        super().__init__()
        if not text:
            raise ValueError("text cannot be empty")
        self.text = text
        self.case_sensitive = case_sensitive
        self._search_text = text if case_sensitive else text.lower()

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Check if trigger text appears in any new message."""
        for message in new_messages:
            if not hasattr(message, "content"):
                continue

            content = message.content
            if not self.case_sensitive:
                content = content.lower()

            if self._search_text in content:
                return self._set_termination(
                    f"Text mention found: '{self.text}'",
                    {
                        "trigger_text": self.text,
                        "found_in_message": message.content[:100],  # First 100 chars
                        "case_sensitive": self.case_sensitive,
                    },
                )

        return None
