"""Handoff termination condition."""

from typing import Optional, Sequence

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

from .base import BaseTermination


class HandoffTermination(BaseTermination):
    """
    Terminates when an agent handoff is detected.

    Looks for handoff patterns in message content, such as:
    - "HANDOFF_TO: agent_name"
    - "TRANSFER_TO: agent_name"
    - Custom handoff keywords

    Example:
        # Default handoff detection
        termination = HandoffTermination()

        # Custom handoff keyword
        termination = HandoffTermination(handoff_keyword="ESCALATE_TO")
    """

    def __init__(self, handoff_keyword: str = "HANDOFF_TO"):
        super().__init__()
        if not handoff_keyword:
            raise ValueError("handoff_keyword cannot be empty")
        self.handoff_keyword = handoff_keyword

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Check if handoff pattern is detected."""
        for message in new_messages:
            if not hasattr(message, "content"):
                continue

            content = message.content
            if self.handoff_keyword in content:
                # Extract target agent if possible
                try:
                    # Look for pattern like "HANDOFF_TO: agent_name"
                    parts = content.split(self.handoff_keyword)
                    if len(parts) > 1:
                        target_part = parts[1].strip()
                        if target_part.startswith(":"):
                            target_part = target_part[1:].strip()
                        target = target_part.split()[0].strip().rstrip(".,!?:")
                    else:
                        target = "unknown"
                except Exception:
                    target = "unknown"

                return self._set_termination(
                    f"Handoff detected: {self.handoff_keyword}",
                    {
                        "handoff_keyword": self.handoff_keyword,
                        "target_agent": target,
                        "message_snippet": content[:100],
                    },
                )

        return None
