from kagimcp.server import format_search_results


def test_happy_path():
    resp = {
        "data": [
            {"t": 0, "title": "Test", "url": "https://example.com", "snippet": "A snippet"},
            {"t": 1, "url": "https://related.com"},  # related search, should be filtered
        ]
    }
    result = format_search_results(["test query"], [resp])
    assert "Test" in result
    assert "https://example.com" in result
    assert "A snippet" in result
    assert "https://related.com" not in result


def test_error_response():
    resp = {"error": [{"code": 0, "msg": "Unauthorized"}]}
    result = format_search_results(["bad query"], [resp])
    assert "ERROR" in result


def test_missing_fields():
    resp = {"data": [{"t": 0}]}
    result = format_search_results(["sparse"], [resp])
    assert "Not Available" in result


def test_multiple_queries():
    resp1 = {"data": [{"t": 0, "title": "First", "url": "https://a.com", "snippet": "snap1"}]}
    resp2 = {"data": [{"t": 0, "title": "Second", "url": "https://b.com", "snippet": "snap2"}]}
    result = format_search_results(["q1", "q2"], [resp1, resp2])
    assert "q1" in result
    assert "q2" in result
    # Result numbering should be continuous
    assert "1:" in result
    assert "2:" in result


def test_continuous_numbering():
    resp1 = {
        "data": [
            {"t": 0, "title": "A", "url": "https://a.com", "snippet": "s1"},
            {"t": 0, "title": "B", "url": "https://b.com", "snippet": "s2"},
        ]
    }
    resp2 = {"data": [{"t": 0, "title": "C", "url": "https://c.com", "snippet": "s3"}]}
    result = format_search_results(["q1", "q2"], [resp1, resp2])
    assert "1:" in result
    assert "2:" in result
    assert "3:" in result


if __name__ == "__main__":
    test_happy_path()
    test_error_response()
    test_missing_fields()
    test_multiple_queries()
    test_continuous_numbering()
    print("All tests passed.")
