"""
Event manager for BLE daemon.
"""

import asyncio
from collections import defaultdict
from typing import Any, Callable, Optional

from airctl.common.logging import get_logger
from airctl.common.utils import get_timestamp
from airctl.models.events import EventType

logger = get_logger(__name__)


class EventManager:
    """
    Manages event emission and subscription.
    
    Events are broadcast to all subscribed clients.
    """

    def __init__(self) -> None:
        self._subscribers: list[asyncio.Queue] = []
        self._event_history: list[dict[str, Any]] = []
        self._max_history = 100

    def subscribe(self) -> asyncio.Queue:
        """
        Subscribe to events.

        Returns:
            Queue that will receive events
        """
        queue: asyncio.Queue = asyncio.Queue()
        self._subscribers.append(queue)
        logger.debug(f"New event subscriber (total: {len(self._subscribers)})")
        return queue

    def unsubscribe(self, queue: asyncio.Queue) -> None:
        """
        Unsubscribe from events.

        Args:
            queue: Queue to unsubscribe
        """
        if queue in self._subscribers:
            self._subscribers.remove(queue)
            logger.debug(f"Removed event subscriber (total: {len(self._subscribers)})")

    def emit(self, event: dict[str, Any]) -> None:
        """
        Emit an event to all subscribers.

        Args:
            event: Event data
        """
        self._event_history.append(event)
        if len(self._event_history) > self._max_history:
            self._event_history = self._event_history[-self._max_history:]

        for queue in list(self._subscribers):
            try:
                queue.put_nowait(event)
            except asyncio.QueueFull:
                logger.warning("Event queue full, dropping event")

        logger.debug(f"Emitted event: {event.get('type')}")

    def get_history(
        self,
        event_type: Optional[str] = None,
        address: Optional[str] = None,
        limit: int = 10,
    ) -> list[dict[str, Any]]:
        """
        Get event history.

        Args:
            event_type: Filter by event type
            address: Filter by device address
            limit: Maximum number of events to return

        Returns:
            List of events
        """
        events = self._event_history

        if event_type:
            events = [e for e in events if e.get("type") == event_type]

        if address:
            events = [e for e in events if e.get("device_address") == address]

        return events[-limit:]

    def clear_history(self) -> None:
        """Clear event history."""
        self._event_history.clear()

    @property
    def subscriber_count(self) -> int:
        """Get number of subscribers."""
        return len(self._subscribers)
