"""SessionManager — multi-session management for headless Textual apps."""

from __future__ import annotations

import uuid

from textual_mcp.session import AppSession


class SessionManager:
    """Manages multiple concurrent AppSession instances."""

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

    def create_session(self, session_id: str | None = None) -> AppSession:
        """Create a new AppSession.

        Args:
            session_id: Optional custom ID. Auto-generated if omitted.

        Raises:
            ValueError: If a session with the given ID already exists.
        """
        if session_id is None:
            session_id = str(uuid.uuid4())[:8]
        if session_id in self._sessions:
            raise ValueError(f"Session '{session_id}' already exists")
        session = AppSession(session_id)
        self._sessions[session_id] = session
        return session

    def get_session(self, session_id: str) -> AppSession:
        """Retrieve a session by ID.

        Raises:
            KeyError: If the session ID is not found.
        """
        if session_id not in self._sessions:
            raise KeyError(f"Session '{session_id}' not found")
        return self._sessions[session_id]

    def list_sessions(self) -> list[dict]:
        """Return a summary of all sessions."""
        return [
            {"session_id": sid, "is_running": s.is_running}
            for sid, s in self._sessions.items()
        ]

    async def remove_session(self, session_id: str) -> None:
        """Stop and remove a session.

        Raises:
            KeyError: If the session ID is not found.
        """
        session = self.get_session(session_id)
        await session.stop()
        del self._sessions[session_id]
