from __future__ import annotations

from app.modules.agent.runtime.docs_qa_pipeline.models import DocsEvidenceBundle


class DocsAnswerSynthesizer:
    def synthesize(self, query: str, evidence_bundle: DocsEvidenceBundle) -> str:
        mode = "graph_summary" if evidence_bundle.sub_intent == "RELATED_DOCS_EXPLAIN" else "prose"
        if mode == "list":
            return self._list_answer(evidence_bundle)
        if mode == "graph_summary":
            return self._graph_summary(evidence_bundle)
        return self._prose_answer(query, evidence_bundle)

    def _prose_answer(self, query: str, bundle: DocsEvidenceBundle) -> str:
        parts = [item["content"] for item in bundle.facts[:3] if item.get("content")]
        if not parts:
            parts = [item["content"] for item in bundle.entities[:2] if item.get("content")]
        if not parts:
            parts = [item["content"] for item in bundle.workflows[:2] if item.get("content")]
        if not parts:
            parts = [item["content"] for item in bundle.documents[:2] if item.get("content")]
        if not parts:
            parts = [item["content"] for item in bundle.chunks[:2] if item.get("content")]
        if not parts:
            return f"Недостаточно данных в документации для ответа на запрос: {query}"
        return "\n".join(parts)

    def _list_answer(self, bundle: DocsEvidenceBundle) -> str:
        items = [item["title"] or item["path"] for item in bundle.documents[:5]]
        if not items:
            items = [item["title"] or item["path"] for item in bundle.facts[:5]]
        if not items:
            return "Подходящие документы не найдены."
        return "\n".join(f"- {item}" for item in items)

    def _graph_summary(self, bundle: DocsEvidenceBundle) -> str:
        items = [item["title"] or item["content"] for item in bundle.relations[:5]]
        if not items:
            items = [item["title"] or item["path"] for item in bundle.documents[:5]]
        if not items:
            return "Связанные документы не найдены."
        return "\n".join(f"- {item}" for item in items)
