"""Сборка AnswerSynthesisInput из EvidenceBundle для этапа LLM."""

from __future__ import annotations

from app.modules.agent.runtime.steps.context.answer_fact_curator import build_curated_answer_facts
from app.modules.agent.runtime.steps.context.contracts import AnswerSynthesisInput, EvidenceBundle


def build_answer_synthesis_input(
    user_question: str,
    bundle: EvidenceBundle,
) -> AnswerSynthesisInput:
    scenario = bundle.resolved_sub_intent or "EXPLAIN"
    target = bundle.resolved_target
    sufficient = bundle.sufficient
    curated = build_curated_answer_facts(bundle)
    semantic_hints = list(curated.get("semantic_hints") or [])

    fast_lines = [
        f"Scenario: {scenario}",
        f"Target: {target or 'none'}",
        f"Evidence chunks: {bundle.evidence_count}",
        f"Primary chunks: {curated.get('primary_chunk_count', 0)}",
        f"Semantic hints: {len(semantic_hints)}",
        f"Relations: {curated.get('relation_count', 0)}",
        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 = []
    primary_chunks = [chunk for chunk in bundle.code_chunks if scenario.upper() not in {"EXPLAIN", "ARCHITECTURE"} or chunk.layer != "C4_SEMANTIC_ROLES"]
    for i, c in enumerate(primary_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 primary_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 semantic_hints:
        evidence_summary.append({"kind": "semantic_hints", "count": len(semantic_hints)})
    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'])}")
    scenario_key = scenario.lower()
    scenario_facts = dict(curated.get(scenario_key) or {})
    hints.extend(list(scenario_facts.get("fact_gaps") or []))

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