from app.modules.agent.engine.orchestrator.actions.code_explain_actions import CodeExplainActions
from app.modules.agent.engine.orchestrator.execution_context import ExecutionContext
from app.modules.agent.engine.orchestrator.models import (
    ArtifactType,
    ExecutionPlan,
    OutputContract,
    RoutingMeta,
    Scenario,
    TaskConstraints,
    TaskSpec,
)
from app.modules.rag.explain.models import ExplainIntent, ExplainPack


class _FakeRetriever:
    def build_pack(self, rag_session_id: str, user_query: str, *, file_candidates: list[dict] | None = None) -> ExplainPack:
        assert rag_session_id == "rag-1"
        assert "endpoint" in user_query
        assert file_candidates == [{"path": "app/api/users.py", "content": "..." }]
        return ExplainPack(intent=ExplainIntent(raw_query=user_query, normalized_query=user_query))


def _ctx() -> ExecutionContext:
    task = TaskSpec(
        task_id="task-1",
        dialog_session_id="dialog-1",
        rag_session_id="rag-1",
        user_message="Explain endpoint get_user",
        scenario=Scenario.EXPLAIN_PART,
        routing=RoutingMeta(domain_id="project", process_id="qa", confidence=0.9, reason="test"),
        constraints=TaskConstraints(),
        output_contract=OutputContract(result_type="answer"),
        metadata={"rag_context": "", "confluence_context": "", "files_map": {}},
    )
    plan = ExecutionPlan(
        plan_id="plan-1",
        task_id="task-1",
        scenario=Scenario.EXPLAIN_PART,
        template_id="tpl",
        template_version="1",
        steps=[],
    )
    ctx = ExecutionContext(task=task, plan=plan, graph_resolver=lambda *_: None, graph_invoker=lambda *_: {})
    ctx.artifacts.put(
        key="source_bundle",
        artifact_type=ArtifactType.STRUCTURED_JSON,
        content={"file_candidates": [{"path": "app/api/users.py", "content": "..."}]},
    )
    return ctx


def test_code_explain_actions_store_explain_pack() -> None:
    ctx = _ctx()
    actions = CodeExplainActions(_FakeRetriever())

    actions.build_code_explain_pack(ctx)

    stored = ctx.artifacts.get_content("explain_pack", {})
    assert stored["intent"]["raw_query"] == "Explain endpoint get_user"
