"""Tests for LLM API rate limiter."""

import time

from bilgeai.llm.rate_limiter import RateLimiter, get_rate_limiter, reset_rate_limiter


class TestRateLimiter:
    def test_init_defaults(self):
        rl = RateLimiter()
        assert rl.max_requests_per_minute == 60
        assert rl.max_tokens_per_minute == 100_000

    def test_custom_limits(self):
        rl = RateLimiter(max_requests_per_minute=10, max_tokens_per_minute=5000)
        assert rl.max_requests_per_minute == 10
        assert rl.max_tokens_per_minute == 5000

    def test_record_request(self):
        rl = RateLimiter()
        rl.record_request(tokens_used=100)
        assert rl.current_rpm == 1
        assert rl.current_tpm == 100

    def test_multiple_records(self):
        rl = RateLimiter()
        rl.record_request(tokens_used=50)
        rl.record_request(tokens_used=75)
        rl.record_request(tokens_used=25)
        assert rl.current_rpm == 3
        assert rl.current_tpm == 150

    def test_can_proceed_under_limit(self):
        rl = RateLimiter(max_requests_per_minute=5)
        rl.record_request()
        assert rl.can_proceed() is True

    def test_can_proceed_at_limit(self):
        rl = RateLimiter(max_requests_per_minute=3)
        rl.record_request()
        rl.record_request()
        rl.record_request()
        assert rl.can_proceed() is False

    def test_can_proceed_token_limit(self):
        rl = RateLimiter(max_tokens_per_minute=100)
        rl.record_request(tokens_used=80)
        assert rl.can_proceed(estimated_tokens=30) is False
        assert rl.can_proceed(estimated_tokens=10) is True

    def test_zero_tokens_recorded(self):
        rl = RateLimiter()
        rl.record_request(tokens_used=0)
        assert rl.current_rpm == 1
        assert rl.current_tpm == 0

    def test_wait_if_needed_no_wait(self):
        rl = RateLimiter(max_requests_per_minute=60)
        waited = rl.wait_if_needed()
        assert waited == 0.0

    def test_cleanup_old_entries(self):
        rl = RateLimiter()
        # Manually add old timestamp
        old_time = time.monotonic() - 120  # 2 minutes ago
        rl._request_timestamps.append(old_time)
        rl._token_counts.append((old_time, 500))
        rl._cleanup_old_entries()
        assert rl.current_rpm == 0
        assert rl.current_tpm == 0


class TestGlobalLimiter:
    def test_get_rate_limiter(self):
        reset_rate_limiter()
        rl = get_rate_limiter(max_rpm=30)
        assert rl.max_requests_per_minute == 30

    def test_singleton(self):
        reset_rate_limiter()
        rl1 = get_rate_limiter()
        rl2 = get_rate_limiter()
        assert rl1 is rl2

    def test_reset(self):
        reset_rate_limiter()
        rl1 = get_rate_limiter()
        rl1.record_request(100)
        reset_rate_limiter()
        rl2 = get_rate_limiter()
        assert rl2.current_rpm == 0
