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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
"""
Tests for the RateLimiter implementation.

This module contains unit tests and property-based tests for the RateLimiter
class, validating rate limiting, quota management, and multi-window tracking.
"""

import pytest
import pytest_asyncio
import asyncio
import time
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock

from voice_control.rate_limiter import RateLimiter, TimeWindow, WindowUsage
from voice_control.models import ProviderConfig, ProviderType, QuotaStatus, QuotaType, UsageStats
from voice_control.exceptions import QuotaExceededError, RateLimitExceededError


class TestRateLimiter:
    """Unit tests for RateLimiter class."""
    
    @pytest_asyncio.fixture
    async def rate_limiter(self):
        """Create a RateLimiter instance for testing."""
        limiter = RateLimiter(cleanup_interval=1)  # Short cleanup interval for testing
        await limiter.initialize()
        yield limiter
        await limiter.shutdown()
    
    @pytest.fixture
    def provider_config(self):
        """Create a test provider configuration."""
        return ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={
                "audio_minutes_per_day": 60,  # 60 minutes per day
                "audio_minutes_per_month": 300  # 300 minutes per month
            },
            rate_limits={
                "requests_per_minute": 10,
                "requests_per_hour": 100,
                "requests_per_day": 1000
            },
            supported_formats=["webm", "wav"],
            supported_languages=["en-US"],
            cost_per_minute=0.006,  # $0.006 per minute
            api_credentials={"api_key": "test_key"}
        )
    
    @pytest.mark.asyncio
    async def test_configure_provider(self, rate_limiter, provider_config):
        """Test provider configuration."""
        await rate_limiter.configure_provider(provider_config)
        
        # Check that windows were created
        assert "test_provider" in rate_limiter._provider_windows
        windows = rate_limiter._provider_windows["test_provider"]
        
        expected_windows = [
            "requests_per_minute",
            "requests_per_hour", 
            "requests_per_day",
            "audio_minutes_per_day",
            "audio_minutes_per_month"
        ]
        
        for window_name in expected_windows:
            assert window_name in windows
        
        # Check window configurations
        assert windows["requests_per_minute"].duration == 60
        assert windows["requests_per_minute"].max_requests == 10
        assert windows["audio_minutes_per_day"].max_audio_duration == 3600  # 60 minutes in seconds
    
    @pytest.mark.asyncio
    async def test_check_quota_no_limits(self, rate_limiter):
        """Test quota checking with no configured limits."""
        quota_status = await rate_limiter.check_quota("unknown_provider", 10.0)
        
        assert quota_status.provider == "unknown_provider"
        assert quota_status.limit == float('inf')
        assert quota_status.remaining == float('inf')
        assert quota_status.percentage_used == 0.0
        assert not quota_status.is_exceeded
    
    @pytest.mark.asyncio
    async def test_check_quota_within_limits(self, rate_limiter, provider_config):
        """Test quota checking within limits."""
        await rate_limiter.configure_provider(provider_config)
        
        quota_status = await rate_limiter.check_quota("test_provider", 30.0)  # 30 seconds
        
        assert quota_status.provider == "test_provider"
        assert not quota_status.is_exceeded
        # 30 seconds = 0.5 minutes, which is 0.5/60 = 0.0083... of the daily limit
        assert quota_status.percentage_used > 0.0
        assert quota_status.percentage_used < 0.01  # Less than 1%
    
    @pytest.mark.asyncio
    async def test_consume_quota_success(self, rate_limiter, provider_config):
        """Test successful quota consumption."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume some quota
        result = await rate_limiter.consume_quota("test_provider", 30.0, 1)
        assert result is True
        
        # Check that usage was recorded
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "minute")
        assert usage_stats.requests_count == 1
        assert usage_stats.audio_minutes == 0.5  # 30 seconds = 0.5 minutes
    
    @pytest.mark.asyncio
    async def test_consume_quota_exceeds_request_limit(self, rate_limiter, provider_config):
        """Test quota consumption that exceeds request limits."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume quota up to the limit (10 requests per minute)
        for i in range(10):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Next request should fail
        with pytest.raises(QuotaExceededError) as exc_info:
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        assert exc_info.value.provider == "test_provider"
        assert "requests_per_minute" in exc_info.value.quota_type
    
    @pytest.mark.asyncio
    async def test_consume_quota_exceeds_audio_limit(self, rate_limiter, provider_config):
        """Test quota consumption that exceeds audio duration limits."""
        await rate_limiter.configure_provider(provider_config)
        
        # Try to consume more than daily audio limit (60 minutes = 3600 seconds)
        with pytest.raises(QuotaExceededError) as exc_info:
            await rate_limiter.consume_quota("test_provider", 3700.0, 1)  # 61+ minutes
        
        assert exc_info.value.provider == "test_provider"
        assert "audio_minutes_per_day" in exc_info.value.quota_type
    
    @pytest.mark.asyncio
    async def test_sliding_window_cleanup(self, rate_limiter, provider_config):
        """Test that sliding windows clean up old entries."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume quota
        await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Check usage
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "minute")
        assert usage_stats.requests_count == 1
        
        # Wait for cleanup (simulate time passing)
        usage = rate_limiter._provider_usage["test_provider"]["requests_per_minute"]
        
        # Manually set old timestamps to simulate time passing
        old_time = time.time() - 120  # 2 minutes ago
        usage.requests.clear()
        usage.requests.append(old_time)
        
        # Trigger cleanup
        await rate_limiter._cleanup_sliding_window("test_provider", "requests_per_minute", 60)
        
        # Old entry should be removed
        assert len(usage.requests) == 0
    
    @pytest.mark.asyncio
    async def test_reset_quota(self, rate_limiter, provider_config):
        """Test quota reset functionality."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume some quota
        await rate_limiter.consume_quota("test_provider", 30.0, 5)
        
        # Verify usage
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "minute")
        assert usage_stats.requests_count == 5
        
        # Reset quota
        await rate_limiter.reset_quota("test_provider", "requests_per_minute")
        
        # Verify reset
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "minute")
        assert usage_stats.requests_count == 0
        assert usage_stats.audio_minutes == 0.0
    
    @pytest.mark.asyncio
    async def test_exponential_backoff(self, rate_limiter, provider_config):
        """Test exponential backoff on rate limit violations."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume quota to the limit
        for i in range(10):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # First violation should trigger backoff
        with pytest.raises(QuotaExceededError):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Immediate retry should fail with RateLimitExceededError
        with pytest.raises(RateLimitExceededError) as exc_info:
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        assert exc_info.value.provider == "test_provider"
        assert exc_info.value.retry_after is not None
    
    @pytest.mark.asyncio
    async def test_get_usage_stats_different_windows(self, rate_limiter, provider_config):
        """Test getting usage statistics for different time windows."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume quota
        await rate_limiter.consume_quota("test_provider", 60.0, 3)  # 1 minute, 3 requests
        
        # Test different time windows
        for window in ["minute", "hour", "day"]:
            stats = await rate_limiter.get_usage_stats("test_provider", window)
            assert stats.provider == "test_provider"
            assert stats.time_window == window
            assert stats.requests_count == 3
            assert stats.audio_minutes == 1.0
            assert stats.estimated_cost > 0  # Should calculate cost
    
    @pytest.mark.asyncio
    async def test_is_provider_available(self, rate_limiter, provider_config):
        """Test provider availability checking."""
        await rate_limiter.configure_provider(provider_config)
        
        # Provider should be available initially
        assert await rate_limiter.is_provider_available("test_provider", 30.0) is True
        
        # Consume quota to the limit
        for i in range(10):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Provider should not be available after hitting limits
        assert await rate_limiter.is_provider_available("test_provider", 1.0) is False
    
    @pytest.mark.asyncio
    async def test_get_provider_quota_status(self, rate_limiter, provider_config):
        """Test getting quota status for all provider windows."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume some quota
        await rate_limiter.consume_quota("test_provider", 30.0, 2)
        
        quota_statuses = await rate_limiter.get_provider_quota_status("test_provider")
        
        # Should have status for all configured windows
        assert len(quota_statuses) > 0
        
        # All statuses should be for the same provider
        for status in quota_statuses.values():
            assert status.provider == "test_provider"
    
    @pytest.mark.asyncio
    async def test_cleanup_loop(self, rate_limiter, provider_config):
        """Test the background cleanup loop."""
        await rate_limiter.configure_provider(provider_config)
        
        # Add some old data
        usage = rate_limiter._provider_usage["test_provider"]["requests_per_minute"]
        old_time = time.time() - 3600  # 1 hour ago
        usage.requests.append(old_time)
        usage.audio_durations.append((old_time, 30.0))
        
        # Trigger cleanup
        await rate_limiter._perform_cleanup()
        
        # Old data should be cleaned up
        assert len(usage.requests) == 0
        assert len(usage.audio_durations) == 0
    
    @pytest.mark.asyncio
    async def test_multiple_providers(self, rate_limiter):
        """Test rate limiting with multiple providers."""
        # Configure two providers with different limits
        config1 = ProviderConfig(
            name="provider1",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={"audio_minutes_per_day": 30},
            rate_limits={"requests_per_minute": 5},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.01,
            api_credentials={"key": "test1"}
        )
        
        config2 = ProviderConfig(
            name="provider2",
            provider_type=ProviderType.AZURE_SPEECH,
            enabled=True,
            priority=2,
            free_tier_limits={"audio_minutes_per_day": 60},
            rate_limits={"requests_per_minute": 10},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.02,
            api_credentials={"key": "test2"}
        )
        
        await rate_limiter.configure_provider(config1)
        await rate_limiter.configure_provider(config2)
        
        # Test that each provider has independent limits
        await rate_limiter.consume_quota("provider1", 30.0, 3)
        await rate_limiter.consume_quota("provider2", 60.0, 5)
        
        # Check usage for each provider
        stats1 = await rate_limiter.get_usage_stats("provider1", "minute")
        stats2 = await rate_limiter.get_usage_stats("provider2", "minute")
        
        assert stats1.requests_count == 3
        assert stats1.audio_minutes == 0.5
        assert stats2.requests_count == 5
        assert stats2.audio_minutes == 1.0


class TestRateLimiterEdgeCases:
    """Test edge cases and error conditions."""
    
    @pytest_asyncio.fixture
    async def rate_limiter(self):
        """Create a RateLimiter instance for testing."""
        limiter = RateLimiter()
        await limiter.initialize()
        yield limiter
        await limiter.shutdown()
    
    @pytest.fixture
    def provider_config(self):
        """Create a test provider configuration."""
        return ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={
                "audio_minutes_per_day": 60,  # 60 minutes per day
                "audio_minutes_per_month": 300  # 300 minutes per month
            },
            rate_limits={
                "requests_per_minute": 10,
                "requests_per_hour": 100,
                "requests_per_day": 1000
            },
            supported_formats=["webm", "wav"],
            supported_languages=["en-US"],
            cost_per_minute=0.006,  # $0.006 per minute
            api_credentials={"api_key": "test_key"}
        )
    
    @pytest.mark.asyncio
    async def test_automatic_provider_switching_on_quota_approach(self, rate_limiter):
        """Test automatic provider switching when approaching quota limits."""
        # Configure two providers with different limits
        config1 = ProviderConfig(
            name="provider1",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={"audio_minutes_per_day": 10},  # Small limit
            rate_limits={"requests_per_minute": 5},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={"key": "test1"}
        )
        
        config2 = ProviderConfig(
            name="provider2",
            provider_type=ProviderType.AZURE_SPEECH,
            enabled=True,
            priority=2,
            free_tier_limits={"audio_minutes_per_day": 60},  # Larger limit
            rate_limits={"requests_per_minute": 10},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={"key": "test2"}
        )
        
        await rate_limiter.configure_provider(config1)
        await rate_limiter.configure_provider(config2)
        
        # Consume most of provider1's quota (9 minutes out of 10)
        await rate_limiter.consume_quota("provider1", 540.0, 1)  # 9 minutes
        
        # Check that provider1 should switch due to approaching limit
        should_switch = await rate_limiter.should_switch_provider("provider1", 120.0)  # 2 more minutes
        assert should_switch is True
        
        # Check that provider2 should not switch
        should_switch = await rate_limiter.should_switch_provider("provider2", 120.0)
        assert should_switch is False
    
    @pytest.mark.asyncio
    async def test_is_provider_approaching_limit(self, rate_limiter, provider_config):
        """Test detection of providers approaching quota limits."""
        await rate_limiter.configure_provider(provider_config)
        
        # Initially not approaching limit
        approaching = await rate_limiter.is_provider_approaching_limit("test_provider", 30.0, 0.8)
        assert approaching is False
        
        # Consume 85% of daily audio quota (51 minutes out of 60)
        await rate_limiter.consume_quota("test_provider", 3060.0, 1)  # 51 minutes
        
        # Should now be approaching limit
        approaching = await rate_limiter.is_provider_approaching_limit("test_provider", 60.0, 0.8)
        assert approaching is True
    
    @pytest.mark.asyncio
    async def test_get_providers_by_availability(self, rate_limiter):
        """Test getting availability status for all providers."""
        # Configure multiple providers
        configs = []
        for i in range(3):
            config = ProviderConfig(
                name=f"provider{i}",
                provider_type=ProviderType.WEB_SPEECH_API,
                enabled=True,
                priority=i,
                free_tier_limits={"audio_minutes_per_day": 30},
                rate_limits={"requests_per_minute": 10},
                supported_formats=["webm"],
                supported_languages=["en-US"],
                cost_per_minute=0.0,
                api_credentials={"key": f"test{i}"}
            )
            configs.append(config)
            await rate_limiter.configure_provider(config)
        
        # Exhaust quota for provider1 by consuming just under the limit
        await rate_limiter.consume_quota("provider1", 1799.0, 1)  # Just under 30 minutes
        
        # Get availability status
        availability = await rate_limiter.get_providers_by_availability(60.0)  # 1 minute request
        
        assert "provider0" in availability
        assert "provider1" in availability
        assert "provider2" in availability
        
        assert availability["provider0"] is True   # Available
        assert availability["provider1"] is False  # Quota exhausted
        assert availability["provider2"] is True   # Available
    
    @pytest.mark.asyncio
    async def test_exponential_backoff_affects_switching(self, rate_limiter, provider_config):
        """Test that exponential backoff affects provider switching decisions."""
        await rate_limiter.configure_provider(provider_config)
        
        # Trigger backoff by exceeding quota
        for i in range(10):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Try to exceed quota to trigger backoff
        with pytest.raises(QuotaExceededError):
            await rate_limiter.consume_quota("test_provider", 1.0, 1)
        
        # Provider should now be in backoff state and recommend switching
        should_switch = await rate_limiter.should_switch_provider("test_provider", 1.0)
        assert should_switch is True
    
    @pytest.mark.asyncio
    async def test_quota_threshold_monitoring(self, rate_limiter, provider_config):
        """Test quota threshold monitoring with different thresholds."""
        await rate_limiter.configure_provider(provider_config)
        
        # Consume 50% of quota
        await rate_limiter.consume_quota("test_provider", 1800.0, 1)  # 30 minutes out of 60
        
        # Should not be approaching with 80% threshold
        approaching_80 = await rate_limiter.is_provider_approaching_limit("test_provider", 0.0, 0.8)
        assert approaching_80 is False
        
        # Should be approaching with 40% threshold
        approaching_40 = await rate_limiter.is_provider_approaching_limit("test_provider", 0.0, 0.4)
        assert approaching_40 is True
        
        # Should recommend switching with 40% threshold
        should_switch_40 = await rate_limiter.should_switch_provider("test_provider", 0.0, 0.4)
        assert should_switch_40 is True
        
        # Should not recommend switching with 80% threshold
        should_switch_80 = await rate_limiter.should_switch_provider("test_provider", 0.0, 0.8)
        assert should_switch_80 is False
    
    @pytest.mark.asyncio
    async def test_zero_audio_duration(self, rate_limiter):
        """Test handling of zero audio duration."""
        config = ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.WEB_SPEECH_API,
            enabled=True,
            priority=1,
            free_tier_limits={},
            rate_limits={"requests_per_minute": 5},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={}
        )
        
        await rate_limiter.configure_provider(config)
        
        # Should handle zero duration gracefully
        result = await rate_limiter.consume_quota("test_provider", 0.0, 1)
        assert result is True
        
        quota_status = await rate_limiter.check_quota("test_provider", 0.0)
        assert not quota_status.is_exceeded
    
    @pytest.mark.asyncio
    async def test_negative_audio_duration(self, rate_limiter):
        """Test handling of negative audio duration."""
        config = ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.WEB_SPEECH_API,
            enabled=True,
            priority=1,
            free_tier_limits={},
            rate_limits={"requests_per_minute": 5},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={}
        )
        
        await rate_limiter.configure_provider(config)
        
        # Should handle negative duration gracefully (treat as zero)
        result = await rate_limiter.consume_quota("test_provider", -10.0, 1)
        assert result is True
    
    @pytest.mark.asyncio
    async def test_very_large_audio_duration(self, rate_limiter):
        """Test handling of very large audio duration."""
        config = ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.WEB_SPEECH_API,
            enabled=True,
            priority=1,
            free_tier_limits={"audio_minutes_per_day": 60},
            rate_limits={},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={}
        )
        
        await rate_limiter.configure_provider(config)
        
        # Very large duration should exceed limits
        with pytest.raises(QuotaExceededError):
            await rate_limiter.consume_quota("test_provider", 1000000.0, 1)  # ~277 hours
    
    @pytest.mark.asyncio
    async def test_concurrent_quota_consumption(self, rate_limiter):
        """Test concurrent quota consumption."""
        config = ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.WEB_SPEECH_API,
            enabled=True,
            priority=1,
            free_tier_limits={},
            rate_limits={"requests_per_minute": 10},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={}
        )
        
        await rate_limiter.configure_provider(config)
        
        # Create multiple concurrent tasks
        async def consume_quota():
            try:
                return await rate_limiter.consume_quota("test_provider", 1.0, 1)
            except (QuotaExceededError, RateLimitExceededError):
                return False
        
        # Run 15 concurrent tasks (more than the limit of 10)
        tasks = [consume_quota() for _ in range(15)]
        results = await asyncio.gather(*tasks)
        
        # Some should succeed, some should fail
        successful = sum(1 for result in results if result is True)
        assert successful <= 10  # Should not exceed the limit
        assert successful > 0    # Some should succeed
    
    @pytest.mark.asyncio
    async def test_shutdown_cleanup(self, rate_limiter):
        """Test that shutdown properly cleans up resources."""
        config = ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.WEB_SPEECH_API,
            enabled=True,
            priority=1,
            free_tier_limits={},
            rate_limits={"requests_per_minute": 10},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.0,
            api_credentials={}
        )
        
        await rate_limiter.configure_provider(config)
        await rate_limiter.consume_quota("test_provider", 30.0, 3)
        
        # Shutdown should clean up all data
        await rate_limiter.shutdown()
        
        assert len(rate_limiter._provider_windows) == 0
        assert len(rate_limiter._provider_usage) == 0
        assert len(rate_limiter._provider_configs) == 0
        assert len(rate_limiter._backoff_state) == 0


class TestRateLimiterResetScheduling:
    """Test counter reset scheduling functionality."""
    
    @pytest_asyncio.fixture
    async def rate_limiter(self):
        """Create a RateLimiter instance for testing."""
        limiter = RateLimiter(cleanup_interval=1)  # Short cleanup interval for testing
        await limiter.initialize()
        yield limiter
        await limiter.shutdown()
    
    @pytest.fixture
    def provider_config_with_schedules(self):
        """Create a test provider configuration with various reset schedules."""
        return ProviderConfig(
            name="test_provider",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={
                "audio_minutes_per_day": 60,  # 60 minutes per day
                "audio_minutes_per_month": 300  # 300 minutes per month
            },
            rate_limits={
                "requests_per_minute": 10,
                "requests_per_hour": 100,
                "requests_per_day": 1000
            },
            supported_formats=["webm", "wav"],
            supported_languages=["en-US"],
            cost_per_minute=0.006,
            api_credentials={"api_key": "test_key"}
        )
    
    @pytest.mark.asyncio
    async def test_configure_reset_schedule(self, rate_limiter, provider_config_with_schedules):
        """Test configuring custom reset schedules."""
        await rate_limiter.configure_provider(provider_config_with_schedules)
        
        # Configure hourly reset for requests_per_minute window
        await rate_limiter.configure_reset_schedule("test_provider", "requests_per_minute", "hourly")
        
        # Verify the schedule was updated
        window = rate_limiter._provider_windows["test_provider"]["requests_per_minute"]
        assert window.reset_schedule == "hourly"
        
        # Test invalid provider
        with pytest.raises(ValueError, match="Provider unknown_provider not configured"):
            await rate_limiter.configure_reset_schedule("unknown_provider", "requests_per_minute", "daily")
        
        # Test invalid window
        with pytest.raises(ValueError, match="Window unknown_window not found"):
            await rate_limiter.configure_reset_schedule("test_provider", "unknown_window", "daily")
        
        # Test invalid schedule
        with pytest.raises(ValueError, match="Invalid reset schedule"):
            await rate_limiter.configure_reset_schedule("test_provider", "requests_per_minute", "invalid")
    
    @pytest.mark.asyncio
    async def test_get_reset_schedule_info(self, rate_limiter, provider_config_with_schedules):
        """Test getting reset schedule information."""
        await rate_limiter.configure_provider(provider_config_with_schedules)
        
        # Get reset schedule info
        reset_info = await rate_limiter.get_reset_schedule_info("test_provider")
        
        # Should have info for all configured windows
        expected_windows = [
            "requests_per_minute",
            "requests_per_hour", 
            "requests_per_day",
            "audio_minutes_per_day",
            "audio_minutes_per_month"
        ]
        
        for window_name in expected_windows:
            assert window_name in reset_info
            info = reset_info[window_name]
            
            # Check required fields
            assert "reset_schedule" in info
            assert "last_reset" in info
            assert "next_reset" in info
            assert "is_sliding_window" in info
            assert "seconds_until_reset" in info
        
        # Check specific schedules
        assert reset_info["requests_per_minute"]["is_sliding_window"] is True  # No reset schedule
        assert reset_info["requests_per_day"]["reset_schedule"] == "daily"
        assert reset_info["audio_minutes_per_month"]["reset_schedule"] == "monthly"
    
    @pytest.mark.asyncio
    async def test_is_reset_due_hourly(self, rate_limiter):
        """Test hourly reset detection."""
        from voice_control.rate_limiter import TimeWindow
        
        window = TimeWindow(
            duration=3600,
            max_requests=100,
            max_audio_duration=float('inf'),
            reset_schedule="hourly"
        )
        
        current_time = datetime.now(timezone.utc)
        
        # Last reset was in the same hour - should not be due
        last_reset_same_hour = current_time.replace(minute=30)
        assert not rate_limiter._is_reset_due(window, last_reset_same_hour, current_time)
        
        # Last reset was in previous hour - should be due
        last_reset_prev_hour = current_time.replace(hour=current_time.hour-1 if current_time.hour > 0 else 23)
        assert rate_limiter._is_reset_due(window, last_reset_prev_hour, current_time)
    
    @pytest.mark.asyncio
    async def test_is_reset_due_daily(self, rate_limiter):
        """Test daily reset detection."""
        from voice_control.rate_limiter import TimeWindow
        
        window = TimeWindow(
            duration=86400,
            max_requests=1000,
            max_audio_duration=float('inf'),
            reset_schedule="daily"
        )
        
        current_time = datetime.now(timezone.utc)
        
        # Last reset was today - should not be due
        last_reset_today = current_time.replace(hour=12, minute=0)
        assert not rate_limiter._is_reset_due(window, last_reset_today, current_time)
        
        # Last reset was yesterday - should be due
        last_reset_yesterday = current_time - timedelta(days=1)
        assert rate_limiter._is_reset_due(window, last_reset_yesterday, current_time)
    
    @pytest.mark.asyncio
    async def test_is_reset_due_weekly(self, rate_limiter):
        """Test weekly reset detection."""
        from voice_control.rate_limiter import TimeWindow
        
        window = TimeWindow(
            duration=7*86400,
            max_requests=5000,
            max_audio_duration=float('inf'),
            reset_schedule="weekly"
        )
        
        current_time = datetime.now(timezone.utc)
        
        # Last reset was this week - should not be due
        days_since_monday = current_time.weekday()
        last_reset_this_week = current_time - timedelta(days=days_since_monday//2)  # Mid-week
        assert not rate_limiter._is_reset_due(window, last_reset_this_week, current_time)
        
        # Last reset was last week - should be due
        last_reset_last_week = current_time - timedelta(days=7 + days_since_monday//2)
        assert rate_limiter._is_reset_due(window, last_reset_last_week, current_time)
    
    @pytest.mark.asyncio
    async def test_is_reset_due_monthly(self, rate_limiter):
        """Test monthly reset detection."""
        from voice_control.rate_limiter import TimeWindow
        
        window = TimeWindow(
            duration=30*86400,
            max_requests=10000,
            max_audio_duration=float('inf'),
            reset_schedule="monthly"
        )
        
        current_time = datetime.now(timezone.utc)
        
        # Last reset was this month - should not be due
        last_reset_this_month = current_time.replace(day=15)
        assert not rate_limiter._is_reset_due(window, last_reset_this_month, current_time)
        
        # Last reset was last month - should be due
        if current_time.month == 1:
            last_reset_last_month = current_time.replace(year=current_time.year-1, month=12, day=15)
        else:
            last_reset_last_month = current_time.replace(month=current_time.month-1, day=15)
        assert rate_limiter._is_reset_due(window, last_reset_last_month, current_time)
    
    @pytest.mark.asyncio
    async def test_scheduled_reset_execution(self, rate_limiter, provider_config_with_schedules):
        """Test that scheduled resets are actually executed."""
        await rate_limiter.configure_provider(provider_config_with_schedules)
        
        # Consume some quota
        await rate_limiter.consume_quota("test_provider", 30.0, 5)
        
        # Verify usage exists
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "day")
        assert usage_stats.requests_count == 5
        assert usage_stats.audio_minutes == 0.5
        
        # Manually trigger a reset by setting last_reset to yesterday
        usage = rate_limiter._provider_usage["test_provider"]["requests_per_day"]
        usage.last_reset = datetime.now(timezone.utc) - timedelta(days=1)
        
        # Trigger the reset check
        await rate_limiter._check_and_perform_resets()
        
        # Verify the reset occurred
        usage_stats = await rate_limiter.get_usage_stats("test_provider", "day")
        assert usage_stats.requests_count == 0
        assert usage_stats.audio_minutes == 0.0
        
        # Verify last_reset was updated
        assert usage.last_reset > datetime.now(timezone.utc) - timedelta(minutes=1)
    
    @pytest.mark.asyncio
    async def test_reset_scheduler_background_task(self, rate_limiter, provider_config_with_schedules):
        """Test that the reset scheduler background task works."""
        await rate_limiter.configure_provider(provider_config_with_schedules)
        
        # Consume some quota
        await rate_limiter.consume_quota("test_provider", 60.0, 3)
        
        # Set last reset to trigger a reset
        usage = rate_limiter._provider_usage["test_provider"]["audio_minutes_per_day"]
        usage.last_reset = datetime.now(timezone.utc) - timedelta(days=1)
        
        # Store original usage data for verification
        original_requests = len(usage.requests)
        original_audio_durations = len(usage.audio_durations)
        
        # Wait for the background task to run (it runs every minute)
        # We'll manually trigger it for testing
        await rate_limiter._check_and_perform_resets()
        
        # Verify the reset occurred by checking the internal data structures
        assert len(usage.requests) == 0  # Requests deque should be cleared
        assert len(usage.audio_durations) == 0  # Audio durations deque should be cleared
        assert usage.total_requests == 0  # Total should be reset
        assert usage.total_audio_duration == 0.0  # Total should be reset
        
        # Verify last_reset was updated
        assert usage.last_reset > datetime.now(timezone.utc) - timedelta(minutes=1)
    
    @pytest.mark.asyncio
    async def test_calculate_reset_time_all_schedules(self, rate_limiter):
        """Test reset time calculation for all schedule types."""
        from voice_control.rate_limiter import TimeWindow
        
        current_time = datetime.now(timezone.utc)
        
        # Test hourly
        hourly_window = TimeWindow(3600, 100, float('inf'), "hourly")
        next_reset = rate_limiter._calculate_reset_time(hourly_window)
        expected_hour = current_time.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
        assert next_reset == expected_hour
        
        # Test daily
        daily_window = TimeWindow(86400, 1000, float('inf'), "daily")
        next_reset = rate_limiter._calculate_reset_time(daily_window)
        expected_day = current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
        assert next_reset == expected_day
        
        # Test weekly
        weekly_window = TimeWindow(7*86400, 5000, float('inf'), "weekly")
        next_reset = rate_limiter._calculate_reset_time(weekly_window)
        days_until_monday = (7 - current_time.weekday()) % 7
        if days_until_monday == 0:
            days_until_monday = 7
        expected_week = current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=days_until_monday)
        assert next_reset == expected_week
        
        # Test monthly
        monthly_window = TimeWindow(30*86400, 10000, float('inf'), "monthly")
        next_reset = rate_limiter._calculate_reset_time(monthly_window)
        if current_time.month == 12:
            expected_month = current_time.replace(year=current_time.year + 1, month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
        else:
            expected_month = current_time.replace(month=current_time.month + 1, day=1, hour=0, minute=0, second=0, microsecond=0)
        assert next_reset == expected_month
        
        # Test sliding window (no schedule)
        sliding_window = TimeWindow(3600, 100, float('inf'), None)
        next_reset = rate_limiter._calculate_reset_time(sliding_window)
        expected_sliding = current_time + timedelta(seconds=3600)
        # Allow for small time differences due to execution time
        assert abs((next_reset - expected_sliding).total_seconds()) < 1
    
    @pytest.mark.asyncio
    async def test_multiple_providers_independent_resets(self, rate_limiter):
        """Test that multiple providers have independent reset schedules."""
        # Configure two providers with different schedules
        config1 = ProviderConfig(
            name="provider1",
            provider_type=ProviderType.GOOGLE_SPEECH,
            enabled=True,
            priority=1,
            free_tier_limits={"audio_minutes_per_day": 30},
            rate_limits={"requests_per_hour": 50},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.01,
            api_credentials={"key": "test1"}
        )
        
        config2 = ProviderConfig(
            name="provider2",
            provider_type=ProviderType.AZURE_SPEECH,
            enabled=True,
            priority=2,
            free_tier_limits={"audio_minutes_per_day": 60},
            rate_limits={"requests_per_hour": 100},
            supported_formats=["webm"],
            supported_languages=["en-US"],
            cost_per_minute=0.02,
            api_credentials={"key": "test2"}
        )
        
        await rate_limiter.configure_provider(config1)
        await rate_limiter.configure_provider(config2)
        
        # Consume quota for both providers
        await rate_limiter.consume_quota("provider1", 600.0, 10)  # 10 minutes, 10 requests
        await rate_limiter.consume_quota("provider2", 1200.0, 20)  # 20 minutes, 20 requests
        
        # Set provider1 to need reset, but not provider2
        usage1 = rate_limiter._provider_usage["provider1"]["audio_minutes_per_day"]
        usage1.last_reset = datetime.now(timezone.utc) - timedelta(days=1)
        
        # Store original usage data for provider2
        usage2 = rate_limiter._provider_usage["provider2"]["audio_minutes_per_day"]
        original_requests_p2 = len(usage2.requests)
        original_audio_p2 = len(usage2.audio_durations)
        
        # Trigger resets
        await rate_limiter._check_and_perform_resets()
        
        # Verify provider1 was reset but provider2 was not
        assert len(usage1.requests) == 0  # Provider1 should be reset
        assert len(usage1.audio_durations) == 0
        assert usage1.total_requests == 0
        assert usage1.total_audio_duration == 0.0
        
        # Provider2 should not be reset (data should remain)
        assert len(usage2.requests) == original_requests_p2
        assert len(usage2.audio_durations) == original_audio_p2
    
    @pytest.mark.asyncio
    async def test_reset_schedule_with_sliding_windows(self, rate_limiter, provider_config_with_schedules):
        """Test that sliding windows are not affected by scheduled resets."""
        await rate_limiter.configure_provider(provider_config_with_schedules)
        
        # Consume quota
        await rate_limiter.consume_quota("test_provider", 30.0, 5)
        
        # Set all windows to need reset (this should only affect scheduled windows)
        for window_name in rate_limiter._provider_usage["test_provider"]:
            usage = rate_limiter._provider_usage["test_provider"][window_name]
            usage.last_reset = datetime.now(timezone.utc) - timedelta(days=1)
        
        # Trigger resets
        await rate_limiter._check_and_perform_resets()
        
        # Verify sliding windows (like requests_per_minute) were not reset
        # but scheduled windows (like requests_per_day) were reset
        minute_stats = await rate_limiter.get_usage_stats("test_provider", "minute")
        day_stats = await rate_limiter.get_usage_stats("test_provider", "day")
        
        # Sliding window should still have data
        assert minute_stats.requests_count == 5
        
        # Scheduled window should be reset
        # Note: day stats might still show data because it's calculated from sliding window data
        # The actual reset affects the scheduled windows, not the sliding window calculations


if __name__ == "__main__":
    pytest.main([__file__])