from __future__ import annotations

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


class EntrypointDocumentBuilder:
    def build(self, source: RagSource, entrypoint: Entrypoint) -> RagDocument:
        title = entrypoint.summary_text or entrypoint.route_or_command
        text = self._text(entrypoint)
        return RagDocument(
            layer=RagLayer.CODE_ENTRYPOINTS,
            lang="python",
            source=source,
            title=title,
            text=text,
            span=RagSpan(entrypoint.start_line, entrypoint.end_line),
            metadata={
                "entry_id": entrypoint.entry_id,
                "entry_type": entrypoint.entry_type,
                "framework": entrypoint.framework,
                "route_or_command": entrypoint.route_or_command,
                "handler_symbol_id": entrypoint.handler_symbol_id,
                "handler_symbol": entrypoint.handler_symbol,
                "declaring_symbol": entrypoint.declaring_symbol,
                "entrypoint_kind": entrypoint.entrypoint_kind,
                "http_method": entrypoint.http_method,
                "route_path": entrypoint.route_path,
                "decorator_text": entrypoint.decorator_text,
                "summary_text": entrypoint.summary_text,
                "is_test": is_test_path(source.path),
                "lang_payload": entrypoint.metadata,
                "artifact_type": "CODE",
            },
            links=[EvidenceLink(type=EvidenceType.CODE_SPAN, target_id=entrypoint.entry_id, path=source.path, start_line=entrypoint.start_line, end_line=entrypoint.end_line)],
        )

    def _text(self, entrypoint: Entrypoint) -> str:
        if not entrypoint.http_method or not entrypoint.route_path:
            return f"{entrypoint.framework} {entrypoint.entry_type} {entrypoint.route_or_command}"
        parts = [f"{entrypoint.http_method} {entrypoint.route_path}"]
        if entrypoint.declaring_symbol:
            parts.append(f"declared in {entrypoint.declaring_symbol}")
        if entrypoint.handler_symbol:
            parts.append(f"handled by {entrypoint.handler_symbol}")
        if entrypoint.decorator_text:
            parts.append(f"decorator {entrypoint.decorator_text}")
        return " | ".join(parts)
