"""
Session Service

Service layer for session management operations.
"""

from honeydb_ai.domain.interfaces import SessionStore
from honeydb_ai.domain.models import Session, SessionMetadata
from honeydb_ai.utils.logging import get_logger, log_session_operation


class SessionService:
    """
    Service for session management.

    Coordinates session operations between controllers and storage layer.
    """

    def __init__(self, session_store: SessionStore):
        """
        Initialize session service.

        Args:
            session_store: Session storage implementation
        """
        self.session_store = session_store
        self.logger = get_logger()

    def create_session(self, title: str = "New Session") -> Session:
        """
        Create a new session.

        Args:
            title: Session title

        Returns:
            New Session object
        """
        session = Session(title=title)
        self.logger.info(f"Created new session: {session.id}")
        return session

    def save_session(self, session: Session) -> None:
        """
        Save a session.

        v2.0: Uses file locking and atomic writes in storage layer.

        Args:
            session: Session to save

        Raises:
            SessionSaveError: If save fails
            SessionTooLargeError: If session exceeds size limits
            SessionLockTimeoutError: If lock cannot be acquired
        """
        try:
            self.session_store.save(session)
            log_session_operation(self.logger, "save", session.id, True)
        except Exception as e:
            log_session_operation(self.logger, "save", session.id, False, str(e))
            raise

    def load_session(self, session_id: str) -> Session:
        """
        Load a session.

        Args:
            session_id: Session ID to load

        Returns:
            Loaded Session object

        Raises:
            SessionNotFoundError: If session doesn't exist
            SessionLoadError: If session cannot be loaded
            SessionCorruptedError: If session file is corrupted
        """
        try:
            session = self.session_store.load(session_id)
            log_session_operation(self.logger, "load", session_id, True)
            return session
        except Exception as e:
            log_session_operation(self.logger, "load", session_id, False, str(e))
            raise

    def delete_session(self, session_id: str) -> None:
        """
        Delete a session.

        Args:
            session_id: Session ID to delete

        Raises:
            SessionNotFoundError: If session doesn't exist
        """
        try:
            self.session_store.delete(session_id)
            log_session_operation(self.logger, "delete", session_id, True)
        except Exception as e:
            log_session_operation(self.logger, "delete", session_id, False, str(e))
            raise

    def list_sessions(self) -> list[SessionMetadata]:
        """
        List all sessions.

        v2.0: Uses persistent metadata cache for performance.

        Returns:
            List of session metadata, sorted by updated_at (most recent first)
        """
        return self.session_store.list_all()

    def session_exists(self, session_id: str) -> bool:
        """
        Check if a session exists.

        Args:
            session_id: Session ID to check

        Returns:
            True if session exists
        """
        return self.session_store.exists(session_id)

    def get_session_metadata(self, session: Session) -> SessionMetadata:
        """
        Get metadata for a session.

        Args:
            session: Session object

        Returns:
            SessionMetadata
        """
        return SessionMetadata.from_session(session)
