from __future__ import annotations

from dataclasses import dataclass
from typing import Literal

TrackPriority = Literal["P0", "P1", "P2", "P3"]

_PRIORITY_ORDER = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}


@dataclass
class TrackEntry:
    track_id: str
    label: str
    priority: TrackPriority = "P1"


class TrackRegistry:
    """多任务轨登记 — Chat P0 · assist P1 · background P2 · dream P3。"""

    def __init__(self) -> None:
        self._tracks: dict[str, TrackEntry] = {}

    def register(self, track_id: str, label: str, *, priority: TrackPriority = "P1") -> TrackEntry:
        entry = TrackEntry(track_id=track_id, label=label, priority=priority)
        self._tracks[track_id] = entry
        return entry

    def unregister(self, track_id: str) -> None:
        self._tracks.pop(track_id, None)

    def list_active(self) -> list[TrackEntry]:
        return sorted(
            self._tracks.values(),
            key=lambda e: (_PRIORITY_ORDER.get(e.priority, 9), e.track_id),
        )

    def health_summary(self) -> dict[str, int]:
        return {"active": len(self._tracks)}
