from __future__ import annotations

from app.infra.exceptions import AppError
from app.core.api.domain.models.agent_session import AgentSession
from app.core.api.infrastructure.ids.session_id_factory import SessionIdFactory
from app.core.api.infrastructure.stores.in_memory_session_store import InMemorySessionStore
from app.schemas.common import ModuleName


class SessionService:
    def __init__(self, store: InMemorySessionStore, ids: SessionIdFactory) -> None:
        self._store = store
        self._ids = ids

    def create(self, rag_session_id: str | None = None) -> AgentSession:
        session = AgentSession.create(self._ids.create(), rag_session_id=rag_session_id)
        return self._store.save(session)

    def get(self, session_id: str) -> AgentSession:
        session = self._store.get(session_id)
        if session is None:
            raise AppError("session_not_found", f"Agent session not found: {session_id}", ModuleName.BACKEND)
        return session

    def save(self, session: AgentSession) -> AgentSession:
        return self._store.save(session)
