from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from tests.pipeline_setup.suite_02_pipeline.pipeline_intent_rag.helpers.env_bootstrap import PipelineEnvLoader


@dataclass(frozen=True, slots=True)
class PipelineRunConfig:
    mode: str
    test_name: str
    tag: str
    phrases_path: Path
    test_results_dir: Path
    forced_rag_session_id: str | None
    default_rag_session_id: str | None
    reindex_repo_path: Path | None
    reindex_project_id: str | None

    @classmethod
    def from_env(cls, mode: str, test_name: str, test_root: Path) -> "PipelineRunConfig":
        PipelineEnvLoader(test_root).load()
        mode_tag = {
            "router_only": "router_only",
            "router_rag": "router_rag",
            "full_chain": "full_chain",
        }[mode]
        forced_sid = os.getenv("INTENT_PIPELINE_FORCE_RAG_SESSION_ID", "").strip() or None
        default_sid = os.getenv("INTENT_PIPELINE_RAG_SESSION_ID", "").strip() or None
        raw_reindex_path = os.getenv("INTENT_PIPELINE_REINDEX_REPO_PATH", "").strip()
        reindex_repo_path = Path(raw_reindex_path).expanduser().resolve() if raw_reindex_path else None
        reindex_project_id = os.getenv("INTENT_PIPELINE_REINDEX_PROJECT_ID", "").strip() or None
        return cls(
            mode=mode,
            test_name=test_name,
            tag=mode_tag,
            phrases_path=test_root / "fixtures" / "phrases.yaml",
            test_results_dir=test_root.parent / "test_results",
            forced_rag_session_id=forced_sid,
            default_rag_session_id=default_sid,
            reindex_repo_path=reindex_repo_path,
            reindex_project_id=reindex_project_id,
        )


def mode_enabled(mode: str, test_root: Path) -> bool:
    PipelineEnvLoader(test_root).load()
    if mode == "router_only":
        return True
    if mode == "router_rag":
        return _truthy(os.getenv("RUN_INTENT_PIPELINE_ROUTER_RAG") or os.getenv("RUN_INTENT_ROUTER_RAG_PIPELINE"))
    if mode == "full_chain":
        return _truthy(os.getenv("RUN_INTENT_PIPELINE_FULL_CHAIN"))
    return False


def _truthy(value: str | None) -> bool:
    return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
