from __future__ import annotations

from app.modules.rag.contracts import EvidenceLink, EvidenceType, RagDocument, RagLayer, RagSource, RagSpan
from app.modules.rag.indexing.code.roles.models import SemanticRoleRecord
from app.modules.rag.retrieval.test_filter import is_test_path


class SemanticRoleDocumentBuilder:
    def build(self, source: RagSource, role_record: SemanticRoleRecord) -> RagDocument:
        responsibilities = "\n".join(f"- {item}" for item in role_record.responsibilities)
        content = (
            f"{role_record.symbol_name}\n"
            f"role: {role_record.role}\n\n"
            f"Responsibilities:\n{responsibilities}"
        )
        return RagDocument(
            layer=RagLayer.CODE_SEMANTIC_ROLES,
            lang="python",
            source=source,
            title=role_record.symbol_name,
            text=content,
            span=RagSpan(role_record.start_line, role_record.end_line),
            metadata={
                "symbol_id": role_record.symbol_id,
                "symbol_name": role_record.symbol_name,
                "qname": role_record.symbol_name,
                "role": role_record.role,
                "confidence": role_record.confidence,
                "dataflow_participation": role_record.dataflow_participation,
                "execution_trace_proximity": role_record.execution_trace_proximity,
                "is_test": is_test_path(source.path),
            },
            links=[
                EvidenceLink(
                    type=EvidenceType.SYMBOL,
                    target_id=role_record.symbol_id,
                    path=source.path,
                    start_line=role_record.start_line,
                    end_line=role_record.end_line,
                )
            ],
        )
