"""Builds RetrievalRequest from RouterResult for the CODE_QA pipeline."""

from __future__ import annotations

from app.modules.rag.code_qa_pipeline.contracts import RetrievalRequest, RouterResult


def build_retrieval_request(router_result: RouterResult, rag_session_id: str) -> RetrievalRequest:
    """Convert router output to RetrievalRequest; router is source of truth."""
    query_plan = router_result.query_plan
    spec = router_result.retrieval_spec
    path_scope = list(getattr(spec.filters, "path_scope", []) or [])
    layers = [str(q.layer_id) for q in (spec.layer_queries or [])]
    return RetrievalRequest(
        rag_session_id=rag_session_id,
        query=query_plan.normalized or query_plan.raw or "",
        sub_intent=query_plan.sub_intent or "EXPLAIN",
        path_scope=path_scope,
        keyword_hints=list(query_plan.keyword_hints or []),
        symbol_candidates=list(query_plan.symbol_candidates or []),
        requested_layers=layers,
        retrieval_spec=spec,
        retrieval_constraints=router_result.retrieval_constraints,
        query_plan=query_plan,
    )
