"""Builds EvidenceBundle from RetrievalResult and router context."""

from __future__ import annotations

from app.modules.rag.code_qa_pipeline.contracts import EvidenceBundle, RetrievalResult, RouterResult


def build_evidence_bundle(
    retrieval_result: RetrievalResult,
    router_result: RouterResult,
) -> EvidenceBundle:
    """Build EvidenceBundle from normalized retrieval and router result."""
    intent = router_result.intent or "CODE_QA"
    sub_intent = (router_result.query_plan and router_result.query_plan.sub_intent) or "EXPLAIN"
    resolved_target: str | None = None
    target_type: str = "none"

    if retrieval_result.resolved_symbol:
        resolved_target = retrieval_result.resolved_symbol
        target_type = "symbol"
    elif retrieval_result.file_candidates:
        resolved_target = retrieval_result.file_candidates[0]
        target_type = "file"
    if retrieval_result.entrypoints and not resolved_target:
        resolved_target = retrieval_result.entrypoints[0].get("title") or retrieval_result.entrypoints[0].get("path")
        target_type = "entrypoint"

    summary = {
        "chunk_count": len(retrieval_result.code_chunks),
        "relation_count": len(retrieval_result.relations),
        "entrypoint_count": len(retrieval_result.entrypoints),
        "test_candidate_count": len(retrieval_result.test_candidates),
        "layers_with_hits": [
            o.layer_id for o in retrieval_result.layer_outcomes if o.hit_count > 0
        ],
        "missing_layers": list(retrieval_result.missing_layers),
    }

    file_candidates = list(retrieval_result.file_candidates)
    target_symbols = list(retrieval_result.target_symbol_candidates)

    return EvidenceBundle(
        resolved_intent=intent,
        resolved_sub_intent=sub_intent,
        resolved_target=resolved_target,
        target_type=target_type,
        target_symbol_candidates=target_symbols,
        file_candidates=file_candidates,
        code_chunks=list(retrieval_result.code_chunks),
        relations=list(retrieval_result.relations),
        entrypoints=list(retrieval_result.entrypoints),
        test_evidence=list(retrieval_result.test_candidates),
        evidence_count=len(retrieval_result.code_chunks),
        sufficient=False,
        failure_reasons=[],
        retrieval_summary=summary,
    )
