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
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
"""
Unit tests for the ProviderManager class.

This module tests the provider management functionality including registration,
discovery, health checking, and provider selection logic.
"""

import pytest
import asyncio
from unittest.mock import AsyncMock, Mock, patch
from datetime import datetime, timedelta

from voice_control.provider_manager import ProviderManager
from voice_control.models import (
    ProviderConfig, ProviderType, TranscriptionResult, ProviderStatus, QuotaStatus, QuotaType
)
from voice_control.exceptions import (
    NoProvidersAvailableError, ProviderUnavailableError, QuotaExceededError,
    UnsupportedFormatError, UnsupportedLanguageError
)
from voice_control.interfaces import STTProvider, RateLimiterInterface


class MockSTTProvider(STTProvider):
    """Mock STT provider for testing."""
    
    def __init__(self, config: ProviderConfig):
        super().__init__(config)
        self.health_status = True
        self.quota_status = {}
        self.transcription_result = TranscriptionResult(
            text="test transcription",
            confidence=0.95,
            provider=config.name,
            processing_time=1.0,
            audio_duration=2.0,
            language="en-US"
        )
        self.should_fail = False
        self.failure_message = "Mock failure"
    
    async def transcribe_audio(self, audio_data: bytes, format: str, language: str = "en-US", **kwargs):
        if self.should_fail:
            raise Exception(self.failure_message)
        return self.transcription_result
    
    async def transcribe_streaming(self, audio_stream, format: str, language: str = "en-US", **kwargs):
        if self.should_fail:
            raise Exception(self.failure_message)
        async for chunk in audio_stream:
            yield self.transcription_result
    
    async def check_health(self) -> bool:
        return self.health_status
    
    async def get_quota_status(self):
        return self.quota_status
    
    def supports_format(self, format: str) -> bool:
        return format in self.config.supported_formats
    
    def supports_language(self, language: str) -> bool:
        return language in self.config.supported_languages
    
    async def estimate_cost(self, audio_duration: float) -> float:
        return audio_duration * self.config.cost_per_minute / 60.0


class MockRateLimiter(RateLimiterInterface):
    """Mock rate limiter for testing."""
    
    def __init__(self):
        self.quota_exceeded = False
        self.quota_status = QuotaStatus(
            provider="test",
            quota_type=QuotaType.REQUESTS_PER_MINUTE,
            current_usage=5,
            limit=10,
            remaining=5,
            reset_time=datetime.utcnow() + timedelta(minutes=1),
            percentage_used=0.5
        )
        self.provider_configs = {}
        self.should_switch_providers = {}
        self.provider_usage = {}  # Track usage per provider
    
    async def configure_provider(self, provider_config):
        """Configure a provider for testing."""
        self.provider_configs[provider_config.name] = provider_config
        # Initialize usage tracking
        self.provider_usage[provider_config.name] = 0.0
    
    async def should_switch_provider(self, provider: str, audio_duration: float = 0.0, threshold: float = 0.9):
        """Mock should switch provider method."""
        # Check if explicitly set to switch
        if provider in self.should_switch_providers:
            return self.should_switch_providers[provider]
        
        # Check if provider is approaching limits based on usage
        if provider in self.provider_configs and provider in self.provider_usage:
            config = self.provider_configs[provider]
            current_usage = self.provider_usage[provider]
            
            # Check audio minutes per day limit
            if "audio_minutes_per_day" in config.free_tier_limits:
                limit = config.free_tier_limits["audio_minutes_per_day"] * 60.0  # Convert to seconds
                projected_usage = current_usage + audio_duration
                usage_percentage = projected_usage / limit
                
                if usage_percentage >= threshold:
                    return True
        
        return False
    
    async def check_quota(self, provider: str, audio_duration: float):
        if self.quota_exceeded:
            self.quota_status.current_usage = self.quota_status.limit + 1
            return self.quota_status
        
        # Create provider-specific quota status
        if provider in self.provider_configs and provider in self.provider_usage:
            config = self.provider_configs[provider]
            current_usage = self.provider_usage[provider]
            
            # Check audio minutes per day limit
            if "audio_minutes_per_day" in config.free_tier_limits:
                limit = config.free_tier_limits["audio_minutes_per_day"] * 60.0  # Convert to seconds
                projected_usage = current_usage + audio_duration
                
                return QuotaStatus(
                    provider=provider,
                    quota_type=QuotaType.AUDIO_MINUTES_PER_DAY,
                    current_usage=projected_usage / 60.0,  # Convert back to minutes
                    limit=config.free_tier_limits["audio_minutes_per_day"],
                    remaining=max(0, (limit - projected_usage) / 60.0),
                    reset_time=datetime.utcnow() + timedelta(days=1),
                    percentage_used=0.0  # Will be calculated in __post_init__
                )
        
        return self.quota_status
    
    async def consume_quota(self, provider: str, audio_duration: float, request_count: int = 1):
        if self.quota_exceeded:
            return False
        
        # Track usage per provider
        if provider not in self.provider_usage:
            self.provider_usage[provider] = 0.0
        
        self.provider_usage[provider] += audio_duration
        return True
    
    async def get_usage_stats(self, provider: str, time_window: str):
        pass
    
    async def reset_quota(self, provider: str, quota_type: str):
        if provider in self.provider_usage:
            self.provider_usage[provider] = 0.0


@pytest.fixture
def provider_manager():
    """Create a ProviderManager instance for testing."""
    return ProviderManager()


@pytest.fixture
def provider_manager_with_rate_limiter():
    """Create a ProviderManager with rate limiter for testing."""
    rate_limiter = MockRateLimiter()
    return ProviderManager(rate_limiter=rate_limiter), rate_limiter


@pytest.fixture
def free_provider_config():
    """Create a free tier provider configuration."""
    return ProviderConfig(
        name="free_provider",
        provider_type=ProviderType.WEB_SPEECH_API,
        enabled=True,
        priority=1,
        free_tier_limits={"requests_per_day": 1000},
        rate_limits={"requests_per_minute": 10},
        supported_formats=["webm", "wav"],
        supported_languages=["en-US", "en-GB"],
        cost_per_minute=0.0,  # Free
        api_credentials={"api_key": "free_key"}
    )


@pytest.fixture
def paid_provider_config():
    """Create a paid provider configuration."""
    return ProviderConfig(
        name="paid_provider",
        provider_type=ProviderType.DEEPGRAM,
        enabled=True,
        priority=2,
        free_tier_limits={},
        rate_limits={"requests_per_minute": 100},
        supported_formats=["webm", "wav", "mp3"],
        supported_languages=["en-US", "es-ES"],
        cost_per_minute=0.05,  # Paid
        api_credentials={"api_key": "paid_key"}
    )


class TestProviderManager:
    """Test cases for ProviderManager class."""
    
    @pytest.mark.asyncio
    async def test_provider_registration(self, provider_manager, free_provider_config):
        """Test registering a provider."""
        provider = MockSTTProvider(free_provider_config)
        
        await provider_manager.register_provider(provider)
        
        # Check provider is registered
        assert "free_provider" in provider_manager._providers
        assert provider_manager._providers["free_provider"] == provider
        
        # Check status is initialized
        status = await provider_manager.get_provider_status()
        assert "free_provider" in status
        assert status["free_provider"].name == "free_provider"
        assert status["free_provider"].available is True
    
    @pytest.mark.asyncio
    async def test_duplicate_provider_registration_fails(self, provider_manager, free_provider_config):
        """Test that registering a provider with duplicate name fails."""
        provider1 = MockSTTProvider(free_provider_config)
        provider2 = MockSTTProvider(free_provider_config)
        
        await provider_manager.register_provider(provider1)
        
        with pytest.raises(ValueError, match="already registered"):
            await provider_manager.register_provider(provider2)
    
    @pytest.mark.asyncio
    async def test_provider_unregistration(self, provider_manager, free_provider_config):
        """Test unregistering a provider."""
        provider = MockSTTProvider(free_provider_config)
        
        await provider_manager.register_provider(provider)
        await provider_manager.unregister_provider("free_provider")
        
        # Check provider is removed
        assert "free_provider" not in provider_manager._providers
        
        status = await provider_manager.get_provider_status()
        assert "free_provider" not in status
    
    @pytest.mark.asyncio
    async def test_unregister_nonexistent_provider_fails(self, provider_manager):
        """Test that unregistering a non-existent provider fails."""
        with pytest.raises(KeyError, match="not registered"):
            await provider_manager.unregister_provider("nonexistent")
    
    @pytest.mark.asyncio
    async def test_provider_config_update(self, provider_manager, free_provider_config):
        """Test updating provider configuration."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Update config
        new_config = free_provider_config
        new_config.priority = 5
        
        result = await provider_manager.update_provider_config("free_provider", new_config)
        
        assert result is True
        assert provider_manager._providers["free_provider"].config.priority == 5
    
    @pytest.mark.asyncio
    async def test_update_nonexistent_provider_config_fails(self, provider_manager, free_provider_config):
        """Test that updating config for non-existent provider fails."""
        result = await provider_manager.update_provider_config("nonexistent", free_provider_config)
        assert result is False
    
    @pytest.mark.asyncio
    async def test_free_tier_prioritization(self, provider_manager, free_provider_config, paid_provider_config):
        """Test that free tier providers are prioritized over paid ones."""
        # Create providers with same priority but different costs
        free_provider_config.priority = 2
        paid_provider_config.priority = 1  # Lower priority number but paid
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await provider_manager.register_provider(paid_provider)
        await provider_manager.register_provider(free_provider)
        
        # Get ordered providers
        ordered = await provider_manager._get_ordered_providers("webm", "en-US")
        
        # Free provider should come first despite higher priority number
        assert ordered[0] == "free_provider"
        assert ordered[1] == "paid_provider"
    
    @pytest.mark.asyncio
    async def test_preferred_provider_gets_highest_priority(self, provider_manager, free_provider_config, paid_provider_config):
        """Test that preferred provider gets highest priority regardless of other factors."""
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await provider_manager.register_provider(free_provider)
        await provider_manager.register_provider(paid_provider)
        
        # Get ordered providers with preferred provider
        ordered = await provider_manager._get_ordered_providers("webm", "en-US", preferred_provider="paid_provider")
        
        # Paid provider should come first because it's preferred
        assert ordered[0] == "paid_provider"
        assert ordered[1] == "free_provider"
    
    @pytest.mark.asyncio
    async def test_format_filtering(self, provider_manager, free_provider_config):
        """Test that providers are filtered by supported formats."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Request supported format
        ordered = await provider_manager._get_ordered_providers("webm", "en-US")
        assert "free_provider" in ordered
        
        # Request unsupported format
        ordered = await provider_manager._get_ordered_providers("mp3", "en-US")
        assert "free_provider" not in ordered
    
    @pytest.mark.asyncio
    async def test_language_filtering(self, provider_manager, free_provider_config):
        """Test that providers are filtered by supported languages."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Request supported language
        ordered = await provider_manager._get_ordered_providers("webm", "en-US")
        assert "free_provider" in ordered
        
        # Request unsupported language
        ordered = await provider_manager._get_ordered_providers("webm", "fr-FR")
        assert "free_provider" not in ordered
    
    @pytest.mark.asyncio
    async def test_disabled_provider_filtering(self, provider_manager, free_provider_config):
        """Test that disabled providers are filtered out."""
        free_provider_config.enabled = False
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        ordered = await provider_manager._get_ordered_providers("webm", "en-US")
        assert "free_provider" not in ordered
    
    @pytest.mark.asyncio
    async def test_successful_transcription(self, provider_manager, free_provider_config, sample_audio_data):
        """Test successful audio transcription."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        result = await provider_manager.transcribe_audio(sample_audio_data, "webm", "en-US")
        
        assert result.text == "test transcription"
        assert result.provider == "free_provider"
        assert result.confidence == 0.95
    
    @pytest.mark.asyncio
    async def test_transcription_with_no_providers(self, provider_manager, sample_audio_data):
        """Test transcription fails when no providers are available."""
        with pytest.raises(NoProvidersAvailableError):
            await provider_manager.transcribe_audio(sample_audio_data, "webm", "en-US")
    
    @pytest.mark.asyncio
    async def test_transcription_fallback_on_failure(self, provider_manager, free_provider_config, paid_provider_config, sample_audio_data):
        """Test that transcription falls back to next provider on failure."""
        # Set up providers with different priorities
        free_provider_config.priority = 1
        paid_provider_config.priority = 2
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        # Make free provider fail
        free_provider.should_fail = True
        free_provider.failure_message = "Free provider failed"
        
        await provider_manager.register_provider(free_provider)
        await provider_manager.register_provider(paid_provider)
        
        result = await provider_manager.transcribe_audio(sample_audio_data, "webm", "en-US")
        
        # Should get result from paid provider (fallback)
        assert result.provider == "paid_provider"
    
    @pytest.mark.asyncio
    async def test_circuit_breaker_opens_after_failures(self, provider_manager, free_provider_config, sample_audio_data):
        """Test that circuit breaker opens after consecutive failures."""
        provider = MockSTTProvider(free_provider_config)
        provider.should_fail = True
        
        await provider_manager.register_provider(provider)
        
        # Cause multiple failures to trigger circuit breaker
        for _ in range(6):  # Threshold is 5
            try:
                await provider_manager.transcribe_audio(sample_audio_data, "webm", "en-US")
            except:
                pass
        
        # Check circuit breaker is open
        status = await provider_manager.get_provider_status()
        assert status["free_provider"].circuit_breaker_state == "OPEN"
        assert status["free_provider"].consecutive_failures >= 5
    
    @pytest.mark.asyncio
    async def test_circuit_breaker_reset(self, provider_manager, free_provider_config):
        """Test manual circuit breaker reset."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Manually set circuit breaker to open
        provider_manager._provider_status["free_provider"].circuit_breaker_state = "OPEN"
        provider_manager._provider_status["free_provider"].consecutive_failures = 10
        
        # Reset circuit breaker
        result = await provider_manager.reset_provider_circuit_breaker("free_provider")
        
        assert result is True
        status = await provider_manager.get_provider_status()
        assert status["free_provider"].circuit_breaker_state == "CLOSED"
        assert status["free_provider"].consecutive_failures == 0
    
    @pytest.mark.asyncio
    async def test_rate_limiter_integration(self, free_provider_config, sample_audio_data):
        """Test integration with rate limiter."""
        manager, rate_limiter = provider_manager_with_rate_limiter()
        provider = MockSTTProvider(free_provider_config)
        
        await manager.register_provider(provider)
        
        # Test successful transcription with quota available
        result = await manager.transcribe_audio(sample_audio_data, "webm", "en-US")
        assert result.provider == "free_provider"
        
        # Test quota exceeded scenario
        rate_limiter.quota_exceeded = True
        
        with pytest.raises(NoProvidersAvailableError):
            await manager.transcribe_audio(sample_audio_data, "webm", "en-US")
    
    @pytest.mark.asyncio
    async def test_provider_metrics_tracking(self, provider_manager, free_provider_config, sample_audio_data):
        """Test that provider metrics are tracked correctly."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Perform successful transcription
        await provider_manager.transcribe_audio(sample_audio_data, "webm", "en-US")
        
        # Check metrics
        metrics = await provider_manager.get_provider_metrics()
        assert "free_provider" in metrics
        
        provider_metrics = metrics["free_provider"]
        assert provider_metrics["total_requests"] == 1
        assert provider_metrics["successful_requests"] == 1
        assert provider_metrics["failed_requests"] == 0
    
    @pytest.mark.asyncio
    async def test_health_check_updates_status(self, provider_manager, free_provider_config):
        """Test that health checks update provider status."""
        provider = MockSTTProvider(free_provider_config)
        provider.health_status = False  # Set unhealthy
        
        await provider_manager.register_provider(provider)
        
        # Perform health check
        await provider_manager._check_provider_health("free_provider", provider)
        
        # Check status updated
        status = await provider_manager.get_provider_status()
        assert status["free_provider"].available is False
    
    @pytest.mark.asyncio
    async def test_streaming_transcription(self, provider_manager, free_provider_config):
        """Test streaming transcription functionality."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Create mock audio stream
        async def audio_stream():
            yield b"chunk1"
            yield b"chunk2"
        
        results = []
        async for result in provider_manager.transcribe_streaming(audio_stream(), "webm", "en-US"):
            results.append(result)
        
        assert len(results) == 2
        assert all(result.provider == "free_provider" for result in results)
    
    @pytest.mark.asyncio
    async def test_automatic_provider_switching_integration(self, free_provider_config, paid_provider_config, sample_audio_data):
        """Test automatic provider switching when quota is approached."""
        manager, rate_limiter = provider_manager_with_rate_limiter()
        
        # Configure providers with different quota limits
        free_provider_config.free_tier_limits = {"audio_minutes_per_day": 5}  # Small limit
        paid_provider_config.free_tier_limits = {"audio_minutes_per_day": 60}  # Large limit
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await manager.register_provider(free_provider)
        await manager.register_provider(paid_provider)
        
        # Configure rate limiter with the same providers
        await rate_limiter.configure_provider(free_provider_config)
        await rate_limiter.configure_provider(paid_provider_config)
        
        # Set up mock to simulate free provider approaching limits
        rate_limiter.should_switch_providers["free_provider"] = True
        rate_limiter.should_switch_providers["paid_provider"] = False
        
        # Next transcription should automatically switch to paid provider
        result = await manager.transcribe_audio(sample_audio_data, "webm", "en-US")
        
        # Should use paid provider due to free provider approaching limits
        assert result.provider == "paid_provider"
    
    @pytest.mark.asyncio
    async def test_get_alternative_provider(self, provider_manager, free_provider_config, paid_provider_config, sample_audio_data):
        """Test getting alternative provider when current one is approaching limits."""
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await provider_manager.register_provider(free_provider)
        await provider_manager.register_provider(paid_provider)
        
        # Get alternative to free provider
        alternative = await provider_manager.get_alternative_provider(
            "free_provider", "webm", "en-US", 30.0
        )
        
        assert alternative == "paid_provider"
        
        # Get alternative to paid provider
        alternative = await provider_manager.get_alternative_provider(
            "paid_provider", "webm", "en-US", 30.0
        )
        
        assert alternative == "free_provider"
    
    @pytest.mark.asyncio
    async def test_recommend_provider_switch(self, free_provider_config, paid_provider_config):
        """Test provider switch recommendation functionality."""
        manager, rate_limiter = provider_manager_with_rate_limiter()
        
        # Configure providers
        free_provider_config.free_tier_limits = {"audio_minutes_per_day": 10}
        paid_provider_config.free_tier_limits = {"audio_minutes_per_day": 60}
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await manager.register_provider(free_provider)
        await manager.register_provider(paid_provider)
        
        await rate_limiter.configure_provider(free_provider_config)
        await rate_limiter.configure_provider(paid_provider_config)
        
        # Set up mock to recommend switching for free provider
        rate_limiter.should_switch_providers["free_provider"] = True
        rate_limiter.should_switch_providers["paid_provider"] = False
        
        # Get switch recommendation
        recommendation = await manager.recommend_provider_switch(
            "free_provider", "webm", "en-US", 120.0  # 2 more minutes
        )
        
        assert recommendation is not None
        assert recommendation["should_switch"] is True
        assert recommendation["alternative_provider"] == "paid_provider"
        assert "approaching limits" in recommendation["reason"].lower() or "quota" in recommendation["reason"].lower()
    
    @pytest.mark.asyncio
    async def test_no_switch_recommendation_when_quota_available(self, free_provider_config, paid_provider_config):
        """Test that no switch is recommended when quota is available."""
        manager, rate_limiter = provider_manager_with_rate_limiter()
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await manager.register_provider(free_provider)
        await manager.register_provider(paid_provider)
        
        await rate_limiter.configure_provider(free_provider_config)
        await rate_limiter.configure_provider(paid_provider_config)
        
        # Don't consume much quota
        await rate_limiter.consume_quota("free_provider", 60.0, 1)  # 1 minute
        
        # Get switch recommendation
        recommendation = await manager.recommend_provider_switch(
            "free_provider", "webm", "en-US", 60.0  # 1 more minute
        )
        
        assert recommendation is None
    
    @pytest.mark.asyncio
    async def test_provider_ordering_considers_quota_status(self, free_provider_config, paid_provider_config):
        """Test that provider ordering considers quota status."""
        manager, rate_limiter = provider_manager_with_rate_limiter()
        
        # Configure providers with same priority but different quota usage
        free_provider_config.priority = 1
        paid_provider_config.priority = 1
        free_provider_config.free_tier_limits = {"audio_minutes_per_day": 10}
        paid_provider_config.free_tier_limits = {"audio_minutes_per_day": 60}
        
        free_provider = MockSTTProvider(free_provider_config)
        paid_provider = MockSTTProvider(paid_provider_config)
        
        await manager.register_provider(free_provider)
        await manager.register_provider(paid_provider)
        
        await rate_limiter.configure_provider(free_provider_config)
        await rate_limiter.configure_provider(paid_provider_config)
        
        # Consume most of free provider's quota
        await rate_limiter.consume_quota("free_provider", 540.0, 1)  # 9 minutes out of 10
        
        # Get ordered providers
        ordered = await manager._get_ordered_providers("webm", "en-US", audio_duration=120.0)
        
        # Paid provider should come first due to better quota availability
        # (even though free provider normally has priority)
        assert ordered[0] == "paid_provider"
        assert ordered[1] == "free_provider"
    
    @pytest.mark.asyncio
    async def test_shutdown_cleanup(self, provider_manager, free_provider_config):
        """Test that shutdown properly cleans up resources."""
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Shutdown
        await provider_manager.shutdown()
        
        # Check cleanup
        assert len(provider_manager._providers) == 0
        assert len(provider_manager._provider_status) == 0
        assert len(provider_manager._provider_metrics) == 0


@pytest.fixture
def sample_audio_data():
    """Create sample audio data for testing."""
    return b"fake_audio_data_for_testing"


def provider_manager_with_rate_limiter():
    """Helper function to create provider manager with rate limiter."""
    rate_limiter = MockRateLimiter()
    manager = ProviderManager(rate_limiter=rate_limiter)
    return manager, rate_limiter


@pytest.mark.integration
class TestProviderManagerCacheIntegration:
    """Test cache integration with ProviderManager (Task 5.2)."""
    
    @pytest.fixture
    def cache_manager(self):
        """Create a mock cache manager for testing."""
        from voice_control.cache_manager import CacheManager
        return CacheManager(max_size_mb=10, default_ttl=3600, enable_stats=True)
    
    @pytest.fixture
    def provider_manager_with_cache(self, cache_manager):
        """Create provider manager with cache integration."""
        return ProviderManager(cache_manager=cache_manager)
    
    @pytest.fixture
    def sample_transcription_result(self):
        """Create a sample transcription result."""
        return TranscriptionResult(
            text="cached transcription result",
            confidence=0.95,
            provider="cache_test_provider",
            processing_time=1.5,
            audio_duration=3.0,
            language="en-US",
            alternatives=["alternative result"]
        )
    
    @pytest.mark.asyncio
    async def test_cache_hit_avoids_provider_calls(self, provider_manager_with_cache, free_provider_config, sample_audio_data, sample_transcription_result):
        """
        Test that cache hits avoid calling STT providers (Requirement 4.3).
        
        **Validates: Requirements 4.3**
        """
        # Start cache manager
        await provider_manager_with_cache._cache_manager.start()
        
        try:
            # Pre-populate cache
            fingerprint = await provider_manager_with_cache._cache_manager.generate_audio_fingerprint(sample_audio_data)
            await provider_manager_with_cache._cache_manager.cache_transcription(fingerprint, sample_transcription_result)
            
            # Create a provider that should NOT be called
            provider = MockSTTProvider(free_provider_config)
            provider.should_fail = True  # If called, it will fail
            provider.failure_message = "Provider should not be called due to cache hit"
            
            await provider_manager_with_cache.register_provider(provider)
            
            # Transcribe audio - should get cached result without calling provider
            result = await provider_manager_with_cache.transcribe_audio(
                sample_audio_data, 
                format="webm",
                language="en-US"
            )
            
            # Should get cached result, not provider result
            assert result.text == sample_transcription_result.text
            assert result.provider == sample_transcription_result.provider
            assert result.confidence == sample_transcription_result.confidence
            
            # Verify cache statistics show hit
            cache_stats = await provider_manager_with_cache.get_cache_stats()
            assert cache_stats is not None
            assert cache_stats["cache_hits"] >= 1
            
        finally:
            await provider_manager_with_cache._cache_manager.stop()
    
    @pytest.mark.asyncio
    async def test_cache_miss_calls_provider_and_caches_result(self, provider_manager_with_cache, free_provider_config, sample_audio_data):
        """
        Test that cache misses call providers and cache the result.
        
        **Validates: Requirements 4.1, 4.3**
        """
        # Start cache manager
        await provider_manager_with_cache._cache_manager.start()
        
        try:
            # Create provider with specific result
            provider_result = TranscriptionResult(
                text="provider transcription result",
                confidence=0.90,
                provider=free_provider_config.name,
                processing_time=2.0,
                audio_duration=3.0,
                language="en-US"
            )
            
            provider = MockSTTProvider(free_provider_config)
            provider.transcription_result = provider_result
            
            await provider_manager_with_cache.register_provider(provider)
            
            # First transcription - should be cache miss and call provider
            result1 = await provider_manager_with_cache.transcribe_audio(
                sample_audio_data,
                format="webm",
                language="en-US"
            )
            
            # Should get provider result
            assert result1.text == provider_result.text
            assert result1.provider == provider_result.provider
            
            # Now make provider fail to ensure second call uses cache
            provider.should_fail = True
            provider.failure_message = "Provider should not be called on second request"
            
            # Second transcription - should be cache hit
            result2 = await provider_manager_with_cache.transcribe_audio(
                sample_audio_data,
                format="webm", 
                language="en-US"
            )
            
            # Should get same result from cache
            assert result2.text == result1.text
            assert result2.provider == result1.provider
            assert result2.confidence == result1.confidence
            
            # Verify cache statistics
            cache_stats = await provider_manager_with_cache.get_cache_stats()
            assert cache_stats is not None
            assert cache_stats["cache_hits"] >= 1
            assert cache_stats["cache_misses"] >= 1
            assert cache_stats["total_requests"] >= 2
            
        finally:
            await provider_manager_with_cache._cache_manager.stop()
    
    @pytest.mark.asyncio
    async def test_different_audio_produces_different_cache_entries(self, provider_manager_with_cache, free_provider_config):
        """
        Test that different audio produces different cache entries.
        
        **Validates: Requirements 4.5**
        """
        # Start cache manager
        await provider_manager_with_cache._cache_manager.start()
        
        try:
            # Create provider
            provider = MockSTTProvider(free_provider_config)
            await provider_manager_with_cache.register_provider(provider)
            
            # Different audio samples
            audio1 = b"first_audio_sample" * 100
            audio2 = b"second_audio_sample" * 100
            
            # Transcribe first audio
            result1 = await provider_manager_with_cache.transcribe_audio(
                audio1,
                format="webm",
                language="en-US"
            )
            
            # Transcribe second audio
            result2 = await provider_manager_with_cache.transcribe_audio(
                audio2,
                format="webm",
                language="en-US"
            )
            
            # Both should be cache misses (different audio)
            cache_stats = await provider_manager_with_cache.get_cache_stats()
            assert cache_stats is not None
            assert cache_stats["cache_misses"] >= 2
            assert cache_stats["entry_count"] >= 2
            
        finally:
            await provider_manager_with_cache._cache_manager.stop()
    
    @pytest.mark.asyncio
    async def test_cache_statistics_integration(self, provider_manager_with_cache, free_provider_config):
        """
        Test comprehensive cache statistics through provider manager.
        
        **Validates: Requirements 4.3**
        """
        # Start cache manager
        await provider_manager_with_cache._cache_manager.start()
        
        try:
            # Create provider
            provider = MockSTTProvider(free_provider_config)
            await provider_manager_with_cache.register_provider(provider)
            
            # Perform multiple transcriptions
            audio_samples = [
                b"audio_sample_1" * 50,
                b"audio_sample_2" * 50,
                b"audio_sample_1" * 50,  # Repeat first sample for cache hit
                b"audio_sample_3" * 50,
                b"audio_sample_2" * 50,  # Repeat second sample for cache hit
            ]
            
            for audio_data in audio_samples:
                await provider_manager_with_cache.transcribe_audio(
                    audio_data,
                    format="webm",
                    language="en-US"
                )
            
            # Check cache statistics
            cache_stats = await provider_manager_with_cache.get_cache_stats()
            assert cache_stats is not None
            
            # Should have 5 total requests: 3 misses + 2 hits
            assert cache_stats["total_requests"] == 5
            assert cache_stats["cache_misses"] == 3  # First occurrence of each unique audio
            assert cache_stats["cache_hits"] == 2    # Repeated audio samples
            assert cache_stats["entry_count"] == 3   # 3 unique audio samples cached
            
            # Hit rate should be 2/5 = 0.4
            expected_hit_rate = 2.0 / 5.0
            assert abs(cache_stats["hit_rate"] - expected_hit_rate) < 0.01
            
            # Check system stats integration
            system_stats = await provider_manager_with_cache.get_system_stats()
            assert system_stats["cache"] is not None
            assert system_stats["cache"]["total_requests"] == 5
            assert system_stats["system_overview"]["cache_enabled"] is True
            
        finally:
            await provider_manager_with_cache._cache_manager.stop()
    
    @pytest.mark.asyncio
    async def test_cache_failure_does_not_break_transcription(self, provider_manager_with_cache, free_provider_config, sample_audio_data):
        """
        Test that cache failures don't break transcription functionality.
        
        **Validates: Requirements 4.3**
        """
        # Start cache manager
        await provider_manager_with_cache._cache_manager.start()
        
        try:
            # Create provider
            provider = MockSTTProvider(free_provider_config)
            await provider_manager_with_cache.register_provider(provider)
            
            # Mock cache manager to fail on operations
            original_get_cached = provider_manager_with_cache._cache_manager.get_cached_transcription
            original_cache_transcription = provider_manager_with_cache._cache_manager.cache_transcription
            
            async def failing_get_cached(*args, **kwargs):
                raise Exception("Cache lookup failed")
            
            async def failing_cache_transcription(*args, **kwargs):
                raise Exception("Cache storage failed")
            
            provider_manager_with_cache._cache_manager.get_cached_transcription = failing_get_cached
            provider_manager_with_cache._cache_manager.cache_transcription = failing_cache_transcription
            
            # Transcription should still work despite cache failures
            result = await provider_manager_with_cache.transcribe_audio(
                sample_audio_data,
                format="webm",
                language="en-US"
            )
            
            # Should get provider result
            assert result is not None
            assert result.text == provider.transcription_result.text
            
            # Restore original methods
            provider_manager_with_cache._cache_manager.get_cached_transcription = original_get_cached
            provider_manager_with_cache._cache_manager.cache_transcription = original_cache_transcription
            
        finally:
            await provider_manager_with_cache._cache_manager.stop()
    
    @pytest.mark.asyncio
    async def test_provider_manager_without_cache(self, free_provider_config, sample_audio_data):
        """
        Test that provider manager works correctly without cache manager.
        
        **Validates: Requirements 4.3**
        """
        # Create provider manager without cache
        provider_manager = ProviderManager()
        
        # Create provider
        provider = MockSTTProvider(free_provider_config)
        await provider_manager.register_provider(provider)
        
        # Transcription should work normally
        result = await provider_manager.transcribe_audio(
            sample_audio_data,
            format="webm",
            language="en-US"
        )
        
        assert result is not None
        assert result.text == provider.transcription_result.text
        
        # Cache stats should be None
        cache_stats = await provider_manager.get_cache_stats()
        assert cache_stats is None
        
        # System stats should show cache disabled
        system_stats = await provider_manager.get_system_stats()
        assert system_stats["cache"] is None
        assert system_stats["system_overview"]["cache_enabled"] is False