"""Colony event system — typed events with priority ordering."""

from __future__ import annotations

import heapq
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import IntEnum


class EventPriority(IntEnum):
    """Lower number = higher priority."""

    QA_REGRESSION = 0
    GOVERNANCE_REVIEW = 1
    POST_MERGE_QA = 2
    INTEL_BRIEF_READY = 3
    PROPOSAL_REVISION = 4
    ROUTINE_SCAN = 5


@dataclass(order=True)
class ColonyEvent:
    priority: EventPriority = field(compare=True)
    timestamp: datetime = field(compare=False, default_factory=lambda: datetime.now(timezone.utc))
    event_type: str = field(compare=False, default="")
    target_agent: str = field(compare=False, default="")
    payload: dict = field(compare=False, default_factory=dict)


class EventLog:
    """Priority queue for pending events + append-only history."""

    def __init__(self) -> None:
        self._queue: list[ColonyEvent] = []
        self._history: list[ColonyEvent] = []

    def push(self, event: ColonyEvent) -> None:
        heapq.heappush(self._queue, event)

    def pop(self) -> ColonyEvent | None:
        if not self._queue:
            return None
        event = heapq.heappop(self._queue)
        self._history.append(event)
        return event

    def peek(self) -> ColonyEvent | None:
        return self._queue[0] if self._queue else None

    @property
    def pending_count(self) -> int:
        return len(self._queue)

    @property
    def history(self) -> list[ColonyEvent]:
        return list(self._history)

    def drain(self) -> list[ColonyEvent]:
        """Pop all events (for shutdown). Returns them in priority order."""
        events = []
        while self._queue:
            events.append(heapq.heappop(self._queue))
        return events
