import pytest
from agentbyte.termination.max_message import MaxMessageTermination
from agentbyte.termination.text_mention import TextMentionTermination
from agentbyte.termination.composite import CompositeTermination
from agentbyte.messages import UserMessage


class TestCompositeTermination:
    def test_any_mode(self):
        t1 = MaxMessageTermination(10)
        t2 = TextMentionTermination("STOP")
        comp = CompositeTermination([t1, t2], mode="any")

        msg = UserMessage(content="STOP", source="user")
        stop = comp.check([msg])

        assert stop is not None
        assert comp.is_met()
        assert stop.metadata["mode"] == "any"
        assert stop.metadata["triggered_by"] == "TextMentionTermination"

    def test_all_mode(self):
        t1 = MaxMessageTermination(2)
        t2 = TextMentionTermination("STOP")
        comp = CompositeTermination([t1, t2], mode="all")

        msg_stop = UserMessage(content="STOP", source="user")
        msg_other = UserMessage(content="Hello", source="user")

        # First message: T2 is met, but T1 is not (only 1 message)
        assert comp.check([msg_stop]) is None
        assert not comp.is_met()

        # Second message: T1 is now met (2 messages total)
        stop = comp.check([msg_other])
        assert stop is not None
        assert comp.is_met()
        assert stop.metadata["mode"] == "all"

    def test_reset(self):
        t1 = MaxMessageTermination(1)
        t2 = TextMentionTermination("STOP")
        comp = t1 | t2

        comp.check([UserMessage(content="hi", source="user")])
        assert t1.is_met()
        assert comp.is_met()

        comp.reset()
        assert not comp.is_met()
        assert not t1.is_met()

    def test_invalid_config(self):
        with pytest.raises(ValueError):
            CompositeTermination([])
        with pytest.raises(ValueError):
            CompositeTermination([MaxMessageTermination(1)])
