import importlib

http_client = importlib.import_module("gjalla_precommit.protocol.http_client")


def test_rate_limit_headers_parsed():
    headers = {
        "X-RateLimit-Limit": "100",
        "X-RateLimit-Remaining": "87",
        "X-RateLimit-Reset": "1704153600",
    }
    info = http_client.parse_rate_limit_headers(headers)
    assert info.limit == 100
    assert info.remaining == 87
    assert info.reset == 1704153600


def test_rate_limit_warning_at_10():
    message = http_client.rate_limit_warning_message(remaining=9)
    assert message is not None
    assert "10" in message or "remaining" in message.lower()


def test_rate_limit_warning_at_5():
    message = http_client.rate_limit_warning_message(remaining=4)
    assert message is not None
    assert "5" in message or "low" in message.lower()


def test_rate_limit_429_handled():
    calls = {"sleep": []}

    def _sleep(seconds: int) -> None:
        calls["sleep"].append(seconds)

    def _warn(message: str) -> None:
        return None

    response = type("Response", (), {"status_code": 429, "headers": {"Retry-After": "7"}})()
    http_client.handle_rate_limit_response(response, sleep_fn=_sleep, warn_fn=_warn)

    assert calls["sleep"] == [7]


def test_rate_limit_429_message():
    messages = []

    def _sleep(seconds: int) -> None:
        return None

    def _warn(message: str) -> None:
        messages.append(message)

    response = type("Response", (), {"status_code": 429, "headers": {"Retry-After": "5"}})()
    http_client.handle_rate_limit_response(response, sleep_fn=_sleep, warn_fn=_warn)

    assert any("rate limit" in message.lower() for message in messages)
