import sys
import types

langgraph = types.ModuleType("langgraph")
langgraph_graph = types.ModuleType("langgraph.graph")
langgraph_graph.END = "END"
langgraph_graph.START = "START"
langgraph_graph.StateGraph = object
sys.modules.setdefault("langgraph", langgraph)
sys.modules.setdefault("langgraph.graph", langgraph_graph)

from app.modules.agent.engine.graphs.project_qa_step_graphs import ProjectQaAnswerGraphFactory


class _FakeLlm:
    def __init__(self) -> None:
        self.calls: list[tuple[str, str, str | None]] = []

    def generate(self, prompt_name: str, user_input: str, *, log_context: str | None = None) -> str:
        self.calls.append((prompt_name, user_input, log_context))
        return "## Summary\n[entrypoint_1] [excerpt_1]"


def test_project_qa_answer_graph_uses_v2_prompt_when_explain_pack_present() -> None:
    llm = _FakeLlm()
    factory = ProjectQaAnswerGraphFactory(llm)

    result = factory._compose_answer(
        {
            "message": "Explain endpoint get_user",
            "question_profile": {"russian": False},
            "analysis_brief": {"findings": [], "evidence": [], "gaps": [], "answer_mode": "summary"},
            "explain_pack": {
                "intent": {
                    "raw_query": "Explain endpoint get_user",
                    "normalized_query": "Explain endpoint get_user",
                    "keywords": ["get_user"],
                    "hints": {"paths": [], "symbols": [], "endpoints": [], "commands": []},
                    "expected_entry_types": ["http"],
                    "depth": "medium",
                },
                "selected_entrypoints": [],
                "seed_symbols": [],
                "trace_paths": [],
                "evidence_index": {
                    "entrypoint_1": {
                        "evidence_id": "entrypoint_1",
                        "kind": "entrypoint",
                        "summary": "/users/{id}",
                        "location": {"path": "app/api/users.py", "start_line": 10, "end_line": 10},
                        "supports": ["handler-1"],
                    }
                },
                "code_excerpts": [
                    {
                        "evidence_id": "excerpt_1",
                        "symbol_id": "handler-1",
                        "title": "get_user",
                        "path": "app/api/users.py",
                        "start_line": 10,
                        "end_line": 18,
                        "content": "async def get_user():\n    return 1",
                        "focus": "overview",
                    }
                ],
                "missing": [],
                "conflicts": [],
            },
        }
    )

    assert result["final_answer"].startswith("## Summary")
    assert llm.calls[0][0] == "code_explain_answer_v2"
    assert '"evidence_id": "excerpt_1"' in llm.calls[0][1]
