from __future__ import annotations

from app.modules.rag.contracts import RagDocument, RagLayer, RagSource, RagSpan
from app.modules.rag.indexing.code.symbols.extractor import PySymbol
from app.modules.rag.retrieval.test_filter import is_test_path


class SymbolDocumentBuilder:
    def build(self, source: RagSource, symbol: PySymbol) -> RagDocument:
        body = [f"{symbol.kind} {symbol.qname}", symbol.signature]
        if symbol.docstring:
            body.append(symbol.docstring.strip())
        return RagDocument(
            layer=RagLayer.CODE_SYMBOL_CATALOG,
            lang="python",
            source=source,
            title=symbol.qname,
            text="\n".join(part for part in body if part),
            span=RagSpan(symbol.start_line, symbol.end_line),
            metadata={
                "symbol_id": symbol.symbol_id,
                "qname": symbol.qname,
                "kind": symbol.kind,
                "signature": symbol.signature,
                "parent_symbol_id": symbol.parent_symbol_id,
                "package_or_module": source.path.replace("/", ".").removesuffix(".py"),
                "is_test": is_test_path(source.path),
            },
        )
