"""Tests for colony event system."""

from fliiq.runtime.colony.events import ColonyEvent, EventLog, EventPriority


def test_priority_ordering():
    """Events should be popped in priority order (lowest number first)."""
    log = EventLog()
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="scan"))
    log.push(ColonyEvent(priority=EventPriority.QA_REGRESSION, event_type="regression"))
    log.push(ColonyEvent(priority=EventPriority.GOVERNANCE_REVIEW, event_type="review"))

    first = log.pop()
    assert first.event_type == "regression"
    assert first.priority == EventPriority.QA_REGRESSION

    second = log.pop()
    assert second.event_type == "review"

    third = log.pop()
    assert third.event_type == "scan"


def test_empty_pop():
    log = EventLog()
    assert log.pop() is None


def test_pending_count():
    log = EventLog()
    assert log.pending_count == 0
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="a"))
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="b"))
    assert log.pending_count == 2
    log.pop()
    assert log.pending_count == 1


def test_history():
    log = EventLog()
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="scan"))
    assert len(log.history) == 0  # Not popped yet
    log.pop()
    assert len(log.history) == 1
    assert log.history[0].event_type == "scan"


def test_peek():
    log = EventLog()
    assert log.peek() is None
    log.push(ColonyEvent(priority=EventPriority.QA_REGRESSION, event_type="urgent"))
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="routine"))
    peeked = log.peek()
    assert peeked.event_type == "urgent"
    assert log.pending_count == 2  # Peek doesn't remove


def test_drain():
    log = EventLog()
    log.push(ColonyEvent(priority=EventPriority.ROUTINE_SCAN, event_type="a"))
    log.push(ColonyEvent(priority=EventPriority.QA_REGRESSION, event_type="b"))
    log.push(ColonyEvent(priority=EventPriority.GOVERNANCE_REVIEW, event_type="c"))

    drained = log.drain()
    assert len(drained) == 3
    assert drained[0].priority == EventPriority.QA_REGRESSION  # Highest priority first
    assert log.pending_count == 0
