from __future__ import annotations

from pathlib import Path

from app.modules.rag.persistence.repository import RagRepository
from tests.pipeline_setup.suite_02_pipeline.pipeline_intent_rag.helpers.models import PhraseCase
from tests.pipeline_setup.suite_02_pipeline.pipeline_intent_rag.helpers.pipeline_config import PipelineRunConfig
from tests.pipeline_setup.utils.rag_indexer import RagSessionIndexer


class RagSessionResolver:
    def __init__(self, config: PipelineRunConfig, repository: RagRepository) -> None:
        self._config = config
        self._repository = repository
        self._indexed_session_id: str | None = None

    def resolve(self, case: PhraseCase) -> str:
        if self._config.forced_rag_session_id:
            return self._config.forced_rag_session_id
        if self._config.reindex_repo_path:
            return self._resolve_from_reindex(self._config.reindex_repo_path)
        if case.rag_session_id:
            return case.rag_session_id
        if self._config.default_rag_session_id:
            return self._config.default_rag_session_id
        raise ValueError(
            f"Case '{case.case_id}' has no rag_session_id and INTENT_PIPELINE_RAG_SESSION_ID is not set"
        )

    def _resolve_from_reindex(self, repo_path: Path) -> str:
        if self._indexed_session_id:
            return self._indexed_session_id
        self._indexed_session_id = RagSessionIndexer(self._repository).index_repo(
            repo_path=repo_path,
            project_id=self._config.reindex_project_id,
        )
        return self._indexed_session_id
