from __future__ import annotations

import logging

from typing import TYPE_CHECKING

from app.modules.agent.engine.orchestrator.actions.common import ActionSupport
from app.modules.agent.engine.orchestrator.execution_context import ExecutionContext
from app.modules.agent.engine.orchestrator.models import ArtifactType
from app.modules.rag.explain.intent_builder import ExplainIntentBuilder
from app.modules.rag.explain.models import ExplainPack

if TYPE_CHECKING:
    from app.modules.rag.explain.retriever_v2 import CodeExplainRetrieverV2

LOGGER = logging.getLogger(__name__)


class CodeExplainActions(ActionSupport):
    def __init__(self, retriever: CodeExplainRetrieverV2 | None = None) -> None:
        self._retriever = retriever
        self._intent_builder = ExplainIntentBuilder()

    def build_code_explain_pack(self, ctx: ExecutionContext) -> list[str]:
        file_candidates = list((self.get(ctx, "source_bundle", {}) or {}).get("file_candidates", []) or [])
        if self._retriever is None:
            pack = ExplainPack(
                intent=self._intent_builder.build(ctx.task.user_message),
                missing=["code_explain_retriever_unavailable"],
            )
        else:
            pack = self._retriever.build_pack(
                ctx.task.rag_session_id,
                ctx.task.user_message,
                file_candidates=file_candidates,
            )
        LOGGER.warning(
            "code explain action: task_id=%s entrypoints=%s seeds=%s paths=%s excerpts=%s missing=%s",
            ctx.task.task_id,
            len(pack.selected_entrypoints),
            len(pack.seed_symbols),
            len(pack.trace_paths),
            len(pack.code_excerpts),
            pack.missing,
        )
        return [self.put(ctx, "explain_pack", ArtifactType.STRUCTURED_JSON, pack.model_dump(mode="json"))]
