"""AI Team OS — Unified event bus."""

from __future__ import annotations

import logging

from aiteam.api.ws.manager import ws_manager
from aiteam.api.ws.protocol import WSEvent
from aiteam.storage.repository import StorageRepository
from aiteam.types import Event

logger = logging.getLogger(__name__)


class EventBus:
    """Unified event emitter — persists to DB and broadcasts via WS simultaneously."""

    def __init__(self, repo: StorageRepository) -> None:
        self._repo = repo

    async def emit(self, event_type: str, source: str, data: dict) -> Event:
        """Emit an event: 1) write to database 2) broadcast via WS.

        Args:
            event_type: Event type (e.g. "team.created").
            source: Event source (e.g. "team:<id>").
            data: Event payload data.

        Returns:
            The persisted Event object.
        """
        # Persist
        event = await self._repo.create_event(event_type, source, data)

        # WS broadcast
        try:
            ws_event = WSEvent(
                channel=event_type,
                event_type=event_type,
                data=data,
                timestamp=event.timestamp,
            )
            await ws_manager.broadcast_event(ws_event)
        except Exception:
            logger.warning("WS broadcast failed for %s", event_type, exc_info=True)

        return event
