"""Builds AnswerSynthesisInput from EvidenceBundle for LLM stage."""

from __future__ import annotations

from app.modules.rag.code_qa_pipeline.contracts import AnswerSynthesisInput, EvidenceBundle


def build_answer_synthesis_input(
    user_question: str,
    bundle: EvidenceBundle,
) -> AnswerSynthesisInput:
    """Build LLM input from EvidenceBundle; fast context (summary) + deep context (payload)."""
    scenario = bundle.resolved_sub_intent or "EXPLAIN"
    target = bundle.resolved_target
    sufficient = bundle.sufficient

    fast_lines = [
        f"Scenario: {scenario}",
        f"Target: {target or 'none'}",
        f"Evidence chunks: {bundle.evidence_count}",
        f"Sufficient: {sufficient}",
    ]
    if bundle.failure_reasons:
        fast_lines.append(f"Failure reasons: {', '.join(bundle.failure_reasons)}")
    fast_context = "\n".join(fast_lines)

    deep_parts = []
    for i, c in enumerate(bundle.code_chunks[:30], 1):
        deep_parts.append(f"[{i}] {c.path}:{c.start_line or '?'}-{c.end_line or '?'}\n{c.content[:800]}")
    deep_context = "\n\n---\n\n".join(deep_parts) if deep_parts else "(no code chunks)"

    evidence_summary = []
    for c in bundle.code_chunks[:20]:
        evidence_summary.append({
            "layer": c.layer,
            "path": c.path,
            "title": c.title,
            "lines": f"{c.start_line or '?'}-{c.end_line or '?'}",
        })
    if bundle.entrypoints:
        evidence_summary.append({"kind": "entrypoints", "count": len(bundle.entrypoints)})
    if bundle.test_evidence:
        evidence_summary.append({"kind": "tests", "count": len(bundle.test_evidence)})

    hints = list(bundle.failure_reasons) if bundle.failure_reasons else []
    if not sufficient and bundle.retrieval_summary.get("missing_layers"):
        hints.append(f"Missing layers: {', '.join(bundle.retrieval_summary['missing_layers'])}")

    return AnswerSynthesisInput(
        user_question=user_question,
        resolved_scenario=scenario,
        resolved_target=target,
        fast_context=fast_context,
        deep_context=deep_context,
        evidence_summary=evidence_summary,
        evidence_sufficient=sufficient,
        diagnostic_hints=hints,
    )
