from mcpbridge.config import PromptConfig
from mcpbridge.prompt_builder import PromptBuilder
from mcpbridge.registry import MCPTool


def test_prompt_assembly_order_and_interpolation():
    pc = PromptConfig(
        system="System for {lang}",
        interpolate=True,
        context_vars={"lang": "EN"},
        inject_tool_descriptions=True,
        inject_internal_instructions=True,
    )
    pb = PromptBuilder(pc)
    pb.set_tools_context(
        [
            MCPTool(
                name="search",
                description="Search tool",
                input_schema={"type": "object", "properties": {"q": {"type": "string"}}, "required": ["q"]},
                server_name="srv",
                namespaced_name="srv__search",
            )
        ]
    )
    sys = pb.build_system_prompt()
    assert "You have access to external tools via an MCP server connection" in sys
    assert "System for EN" in sys
    assert "Tool: srv__search" in sys


def test_build_messages_system_injection():
    pc = PromptConfig(system="Hello", interpolate=False)
    pb = PromptBuilder(pc)
    history = [{"role": "user", "content": "prev"}]
    system_prompt, messages = pb.build_messages(history=history, user_query="next")
    assert system_prompt is not None
    assert messages[-1]["content"] == "next"

    pb.set_system_in_messages(True)
    system_prompt2, messages2 = pb.build_messages(history=history, user_query="next2")
    assert system_prompt2 is None
    assert messages2[0]["role"] == "system"
    assert messages2[-1]["content"] == "next2"

