from pathlib import Path
from typing import TYPE_CHECKING

from app.modules.agent.llm import AgentLlmService
from app.modules.contracts import RagRetriever

if TYPE_CHECKING:
    from app.modules.agent.repository import AgentRepository
    from app.modules.agent.engine.router.router_service import RouterService


def build_router_service(llm: AgentLlmService, agent_repository: "AgentRepository", rag: RagRetriever) -> "RouterService":
    from app.modules.agent.engine.graphs import (
        BaseGraphFactory,
        CodeQaGraphFactory,
        DocsGraphFactory,
        ProjectEditsGraphFactory,
        ProjectQaAnalysisGraphFactory,
        ProjectQaAnswerGraphFactory,
        ProjectQaClassificationGraphFactory,
        ProjectQaConversationGraphFactory,
        ProjectQaGraphFactory,
        ProjectQaRetrievalGraphFactory,
    )
    from app.modules.agent.engine.router.context_store import RouterContextStore
    from app.modules.agent.engine.router.intent_classifier import IntentClassifier
    from app.modules.agent.engine.router.intent_switch_detector import IntentSwitchDetector
    from app.modules.agent.engine.router.registry import IntentRegistry
    from app.modules.agent.engine.router.router_service import RouterService

    registry_path = Path(__file__).resolve().parent / "intents_registry.yaml"
    registry = IntentRegistry(registry_path=registry_path)
    registry.register("default", "general", BaseGraphFactory(llm).build)
    registry.register("project", "qa", ProjectQaGraphFactory(llm).build)
    registry.register("project_qa", "code_qa_runtime", CodeQaGraphFactory(llm).build)
    registry.register("project", "edits", ProjectEditsGraphFactory(llm).build)
    registry.register("docs", "generation", DocsGraphFactory(llm).build)
    registry.register("project_qa", "conversation_understanding", ProjectQaConversationGraphFactory(llm).build)
    registry.register("project_qa", "question_classification", ProjectQaClassificationGraphFactory(llm).build)
    registry.register("project_qa", "context_retrieval", ProjectQaRetrievalGraphFactory(rag, llm).build)
    registry.register("project_qa", "context_analysis", ProjectQaAnalysisGraphFactory(llm).build)
    registry.register("project_qa", "answer_composition", ProjectQaAnswerGraphFactory(llm).build)

    classifier = IntentClassifier(llm)
    switch_detector = IntentSwitchDetector()
    context_store = RouterContextStore(agent_repository)
    return RouterService(
        registry=registry,
        classifier=classifier,
        context_store=context_store,
        switch_detector=switch_detector,
    )


__all__ = ["build_router_service"]
