from __future__ import annotations

from app.modules.rag.contracts import EvidenceLink, EvidenceType, RagDocument, RagLayer, RagSource, RagSpan
from app.modules.rag.indexing.code.entrypoints.execution_trace_builder import ExecutionTrace
from app.modules.rag.retrieval.test_filter import is_test_path


class ExecutionTraceDocumentBuilder:
    def build(self, source: RagSource, item: ExecutionTrace) -> RagDocument:
        text = "\n -> ".join(item.path_symbols)
        return RagDocument(
            layer=RagLayer.CODE_ENTRYPOINTS,
            lang="python",
            source=source,
            title=f"{item.path_symbols[0]}:execution_trace",
            text=text,
            span=RagSpan(item.start_line, item.end_line),
            metadata={
                "edge_id": item.trace_id,
                "edge_type": "execution_trace",
                "src_symbol_id": item.entry_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",
                "trace_id": item.trace_id,
                "entry_id": item.entry_id,
                "entry_symbol_id": item.entry_symbol_id,
                "path_symbols": item.path_symbols,
                "path_symbol_ids": item.path_symbol_ids,
                "path_length": item.path_length,
                "is_test": is_test_path(source.path),
            },
            links=[
                EvidenceLink(
                    type=EvidenceType.EDGE,
                    target_id=item.trace_id,
                    path=source.path,
                    start_line=item.start_line,
                    end_line=item.end_line,
                )
            ],
        )
