from __future__ import annotations

import pytest

from eip_mcp.server import ValidationError, _tool_search
from eip_mcp import api_client, formatters


def _patch_search(monkeypatch: pytest.MonkeyPatch) -> dict:
    captured: dict = {}

    def fake_search(params: dict) -> dict:
        captured.update(params)
        return {
            "total": 0,
            "page": 1,
            "per_page": params.get("per_page", 10),
            "total_pages": 0,
            "items": [],
        }

    monkeypatch.setattr(api_client, "search_vulns", fake_search)
    monkeypatch.setattr(formatters, "format_search_results", lambda data: "OK")
    return captured


def test_tool_search_forwards_false_booleans(monkeypatch: pytest.MonkeyPatch) -> None:
    captured = _patch_search(monkeypatch)

    result = _tool_search(
        {
            "query": "apache",
            "has_exploits": False,
            "is_kev": False,
            "any_exploited": False,
            "ransomware": False,
            "has_nuclei": False,
            "per_page": 5,
        }
    )

    assert result == "OK"
    assert captured["q"] == "apache"
    assert captured["has_exploits"] is False
    assert captured["is_kev"] is False
    assert captured["any_exploited"] is False
    assert captured["ransomware"] is False
    assert captured["has_nuclei"] is False


def test_tool_search_forwards_true_booleans(monkeypatch: pytest.MonkeyPatch) -> None:
    captured = _patch_search(monkeypatch)

    result = _tool_search(
        {
            "query": "apache",
            "has_exploits": True,
            "is_kev": True,
            "any_exploited": True,
            "ransomware": True,
            "has_nuclei": True,
            "per_page": 5,
        }
    )

    assert result == "OK"
    assert captured["has_exploits"] is True
    assert captured["is_kev"] is True
    assert captured["any_exploited"] is True
    assert captured["ransomware"] is True
    assert captured["has_nuclei"] is True


def test_tool_search_rejects_non_boolean_filter_value() -> None:
    with pytest.raises(ValidationError, match="has_exploits must be a boolean"):
        _tool_search({"query": "apache", "has_exploits": "false"})
