"""AutoDetector — detects current tool and session from registered sources."""

from session_store.errors import NoActiveSessionError
from session_store.models import SessionInfo
from session_store.registry import SourceRegistry


class AutoDetector:
    """Checks all registered sources and picks the one with the most recent activity."""

    def __init__(self, registry: SourceRegistry) -> None:
        self._registry = registry

    def detect_tool(self) -> str:
        """Detect which AI agent tool was most recently active.

        Queries each registered source's list_sessions(limit=1), compares
        last_activity timestamps, and returns the tool name with the most
        recent activity.

        Raises:
            NoActiveSessionError: If no source has any sessions.
        """
        latest: SessionInfo | None = None

        for source in self._registry.all_sources():
            sessions = source.list_sessions(limit=1)
            if not sessions:
                continue
            session = sessions[0]
            if latest is None or session.last_activity > latest.last_activity:
                latest = session

        if latest is None:
            raise NoActiveSessionError("No active session detected from any source")

        return latest.tool

    def detect_session(self, tool: str, cwd: str | None = None) -> str | None:
        """Detect the current session ID for a given tool.

        If cwd is provided, prefers a session whose working_directory matches
        the cwd. Falls back to detect_current_session() on the source.

        Returns:
            The session ID, or None if no session could be detected.
        """
        source = self._registry.get(tool)

        if cwd is not None:
            sessions = source.list_sessions(limit=50)
            for session in sessions:
                if session.working_directory == cwd:
                    return session.session_id

        return source.detect_current_session()
