from __future__ import annotations

from pathlib import Path

from tests.pipeline_setup_v2.core.models import CaseInput


class RagSessionProvider:
    def __init__(self) -> None:
        self._repository = None
        self._cache: dict[tuple[Path, str | None], str] = {}

    def resolve(self, case_input: CaseInput) -> str | None:
        if case_input.rag_session_id:
            return case_input.rag_session_id
        if not case_input.repo_path:
            return None
        key = (case_input.repo_path, case_input.project_id)
        if key not in self._cache:
            self._cache[key] = self._build_indexer().index_repo(
                case_input.repo_path,
                project_id=case_input.project_id,
            )
        return self._cache[key]

    def _build_indexer(self):
        from app.modules.rag.persistence.repository import RagRepository
        from tests.pipeline_setup.utils.rag_indexer import RagSessionIndexer

        if self._repository is None:
            self._repository = RagRepository()
        return RagSessionIndexer(self._repository)
