"""Timeout termination condition."""

import time
from typing import Optional, Sequence

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

from .base import BaseTermination


class TimeoutTermination(BaseTermination):
    """
    Terminates when elapsed time exceeds limit.

    Tracks wall-clock time from the first check() call and stops
    when the timeout is exceeded.

    Example:
        # Stop after 5 minutes (300 seconds)
        termination = TimeoutTermination(timeout_seconds=300)

        # Combine with other conditions
        termination = (
            TimeoutTermination(60) | TextMentionTermination("DONE")
        )
    """

    def __init__(self, timeout_seconds: float):
        super().__init__()
        if timeout_seconds <= 0:
            raise ValueError("timeout_seconds must be > 0")
        self.timeout_seconds = timeout_seconds
        self.start_time: Optional[float] = None

    def check(self, new_messages: Sequence[Message]) -> Optional[StopMessage]:
        """Check if timeout has been exceeded."""
        # Start timer on first check
        if self.start_time is None:
            self.start_time = time.time()
            return None

        elapsed = time.time() - self.start_time

        if elapsed >= self.timeout_seconds:
            return self._set_termination(
                f"Timeout exceeded ({elapsed:.1f}s/{self.timeout_seconds}s)",
                {
                    "elapsed_seconds": round(elapsed, 2),
                    "timeout_seconds": self.timeout_seconds,
                },
            )

        return None

    def reset(self) -> None:
        """Reset timer."""
        super().reset()
        self.start_time = None
