from __future__ import annotations

from app.modules.rag.contracts import EvidenceLink, EvidenceType, RagDocument, RagLayer, RagSource, RagSpan
from app.modules.rag.indexing.code.edges.dataflow_slice_builder import DataflowSlice
from app.modules.rag.retrieval.test_filter import is_test_path


class DataflowDocumentBuilder:
    def build(self, source: RagSource, item: DataflowSlice) -> RagDocument:
        text = "\n -> ".join(item.path_symbols)
        return RagDocument(
            layer=RagLayer.CODE_DEPENDENCY_GRAPH,
            lang="python",
            source=source,
            title=f"{item.path_symbols[0]}:dataflow_slice",
            text=text,
            span=RagSpan(item.start_line, item.end_line),
            metadata={
                "edge_id": item.slice_id,
                "edge_type": "dataflow_slice",
                "src_symbol_id": item.root_symbol_id,
                "src_qname": item.path_symbols[0],
                "dst_symbol_id": item.path_symbol_ids[-1] if item.path_symbol_ids else None,
                "dst_ref": item.path_symbols[-1],
                "resolution": "resolved" if len(item.path_symbol_ids) >= 2 else "partial",
                "slice_id": item.slice_id,
                "root_symbol_id": item.root_symbol_id,
                "path_symbols": item.path_symbols,
                "path_symbol_ids": item.path_symbol_ids,
                "path_edge_types": item.path_edge_types,
                "path_length": item.path_length,
                "is_test": is_test_path(source.path),
            },
            links=[
                EvidenceLink(
                    type=EvidenceType.EDGE,
                    target_id=item.slice_id,
                    path=source.path,
                    start_line=item.start_line,
                    end_line=item.end_line,
                )
            ],
        )
