"""Tests for MCP interface."""

from pathlib import Path

from dpe.mcp.server import MCP_TOOL_SCHEMA, generate_prd


class TestMCPSchema:
    def test_tool_name(self) -> None:
        assert MCP_TOOL_SCHEMA["name"] == "dialectic.generate_prd"

    def test_required_input(self) -> None:
        assert "idea" in MCP_TOOL_SCHEMA["inputSchema"]["required"]

    def test_optional_fields(self) -> None:
        props = MCP_TOOL_SCHEMA["inputSchema"]["properties"]
        assert "context" in props
        assert "config_overrides" in props

    def test_output_schema_present(self) -> None:
        assert "outputSchema" in MCP_TOOL_SCHEMA
        output = MCP_TOOL_SCHEMA["outputSchema"]
        assert "final_prd_markdown" in output["properties"]
        assert "run_manifest" in output["properties"]
        assert "warnings" in output["properties"]


class TestMCPGeneratePRD:
    def test_simulation_run(self, tmp_path: Path) -> None:
        result = generate_prd(
            idea="Test app",
            config_overrides={"simulation_mode": True, "output_dir": str(tmp_path)},
        )
        assert result["run_id"]
        assert result["final_prd_markdown"]
        assert result["run_manifest"]["stop_reason"] == "completed"

    def test_returns_warnings_on_budget_breach(self, tmp_path: Path) -> None:
        result = generate_prd(
            idea="Test app",
            config_overrides={
                "simulation_mode": True,
                "output_dir": str(tmp_path),
                "budget": {"max_total_calls": 2},
            },
        )
        assert result["run_manifest"]["stop_reason"] == "budget_exceeded"

    def test_structured_error_on_invalid_config(self) -> None:
        """MCP must return structured error dict, not raise exceptions."""
        result = generate_prd(
            idea="Test app",
            config_overrides={"budget": {"max_total_calls": -5}},
        )
        assert result["run_id"] == ""
        assert result["run_manifest"]["stop_reason"] == "config_error"
        assert "error" in result["run_manifest"]
        assert len(result["warnings"]) > 0
