"""Mailbox — async message queue for agent communication."""
from __future__ import annotations

import asyncio
from typing import Any


class Mailbox:
    """An async FIFO queue for delivering messages to an agent."""

    def __init__(self) -> None:
        self._queue: asyncio.Queue[Any] = asyncio.Queue()

    async def put(self, message: Any) -> None:
        """Enqueue a message."""
        await self._queue.put(message)

    async def get(self) -> Any:
        """Dequeue a message (blocks until one is available)."""
        return await self._queue.get()

    def get_nowait(self) -> Any | None:
        """Dequeue a message without blocking. Returns None if empty."""
        try:
            return self._queue.get_nowait()
        except asyncio.QueueEmpty:
            return None

    def empty(self) -> bool:
        """Check if the mailbox is empty."""
        return self._queue.empty()

    def drain(self) -> list[Any]:
        """Remove and return all queued messages."""
        items: list[Any] = []
        while not self._queue.empty():
            try:
                items.append(self._queue.get_nowait())
            except asyncio.QueueEmpty:
                break
        return items
