from __future__ import annotations

import json
import queue
import threading
from typing import Any, Dict, List


class EventBroadcaster:
    """Very small SSE-style broadcaster using per-connection queues."""

    def __init__(self) -> None:
        self._subscribers: List[queue.Queue[str]] = []
        self._lock = threading.Lock()

    def subscribe(self) -> queue.Queue[str]:
        q: queue.Queue[str] = queue.Queue()
        with self._lock:
            self._subscribers.append(q)
        return q

    def unsubscribe(self, q: queue.Queue[str]) -> None:
        with self._lock:
            if q in self._subscribers:
                self._subscribers.remove(q)

    def publish(self, payload: Dict[str, Any]) -> None:
        data = json.dumps(payload)
        with self._lock:
            subscribers = list(self._subscribers)
        for q in subscribers:
            try:
                q.put_nowait(data)
            except queue.Full:
                # Connection likely stalled; drop message.
                continue
