from __future__ import annotations

from datetime import datetime, timezone

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


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

    def create(self) -> AgentSession:
        session = AgentSession.create(self._ids.create())
        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 bind_rag_session(self, session_id: str, rag_session_id: str) -> AgentSession:
        if not self._rag_session_exists(rag_session_id):
            raise AppError("rag_session_not_found", f"RAG session not found: {rag_session_id}", ModuleName.RAG)
        session = self.get(session_id)
        session.active_rag_session_id = rag_session_id
        session.updated_at = datetime.now(timezone.utc)
        return self._store.save(session)

    def reset(self, session_id: str) -> AgentSession:
        session = self.get(session_id)
        session.active_rag_session_id = None
        session.updated_at = datetime.now(timezone.utc)
        return self._store.save(session)
