"""
neurocli share — shareable session broadcasting
"""
import json
import uuid
import threading
import time
from datetime import datetime

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False


class SessionBroadcaster:
    """Broadcasts session events to a share server for remote viewing."""

    def __init__(self, share_server: str, session_id: int, project: str):
        self.server = share_server.rstrip("/")
        self.session_id = session_id
        self.project = project
        self.share_id = str(uuid.uuid4())[:8]
        self.active = False
        self._queue = []
        self._lock = threading.Lock()

    def start(self) -> str:
        """Register session and return share URL."""
        if not HAS_REQUESTS:
            return None
        try:
            resp = requests.post(
                f"{self.server}/sessions",
                json={
                    "share_id": self.share_id,
                    "project": self.project,
                    "created_at": datetime.now().isoformat(),
                },
                timeout=5,
            )
            if resp.status_code == 200:
                self.active = True
                self._start_flush_thread()
                return f"{self.server}/view/{self.share_id}"
        except Exception:
            pass
        return None

    def emit(self, event_type: str, data: dict):
        """Queue an event to broadcast."""
        if not self.active:
            return
        with self._lock:
            self._queue.append({
                "type": event_type,
                "data": data,
                "ts": datetime.now().isoformat(),
            })

    def _start_flush_thread(self):
        def flush():
            while self.active:
                time.sleep(0.5)
                with self._lock:
                    if not self._queue:
                        continue
                    batch = list(self._queue)
                    self._queue.clear()
                try:
                    requests.post(
                        f"{self.server}/sessions/{self.share_id}/events",
                        json={"events": batch},
                        timeout=3,
                    )
                except Exception:
                    pass

        t = threading.Thread(target=flush, daemon=True)
        t.start()

    def stop(self):
        self.active = False


def create_broadcaster(cfg: dict, session_id: int, project: str) -> SessionBroadcaster:
    server = cfg.get("share_server", "")
    if not server:
        return None
    return SessionBroadcaster(server, session_id, project)
