"""Console v2 selection store — tracks which beat/take the user is viewing.

GET  /api/selection/current → {project_id, beat_id, take_id} or empty dict
POST /api/selection/current → body {project_id, beat_id, take_id}; emits BUS event
"""
import threading
from typing import Optional
from fastapi import APIRouter
from pydantic import BaseModel
from recoil.api.eventbus import BUS

router = APIRouter()
_LOCK = threading.Lock()
_SELECTION: dict[str, str] = {}


class SelectionPayload(BaseModel):
    project_id: Optional[str] = None
    beat_id: Optional[str] = None
    take_id: Optional[str] = None


@router.get("/selection/current")
def get_selection() -> dict:
    with _LOCK:
        return dict(_SELECTION)


@router.post("/selection/current")
def set_selection(body: SelectionPayload) -> dict:
    new_selection: dict[str, str] = {k: v for k, v in body.model_dump().items() if v is not None}
    with _LOCK:
        if dict(_SELECTION) == new_selection:
            return {"ok": True}
        _SELECTION.clear()
        _SELECTION.update(new_selection)
        snapshot = dict(_SELECTION)
    BUS.emit_sync("info", "selection/changed", "selection updated", payload=snapshot)
    return {"ok": True}
