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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
"""
Configuration management for the voice control optimization system.

This module handles loading, validation, and management of configuration
settings for all voice control components.
"""

import os
import json
import logging
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, field, asdict
from pathlib import Path
from datetime import datetime, timedelta

from .models import ProviderConfig, ProviderType
from .exceptions import ConfigurationError, ValidationError


logger = logging.getLogger(__name__)


@dataclass
class VoiceControlConfig:
    """Main configuration class for the voice control system."""
    
    # Provider configurations
    providers: Dict[str, ProviderConfig] = field(default_factory=dict)
    
    # Rate limiting settings
    rate_limiting: Dict[str, Any] = field(default_factory=lambda: {
        "enabled": True,
        "default_window_size": 60,  # seconds
        "cleanup_interval": 300,    # seconds
        "redis_url": None,          # Use in-memory if None
    })
    
    # Caching settings
    caching: Dict[str, Any] = field(default_factory=lambda: {
        "enabled": True,
        "max_size_mb": 100,
        "default_ttl": 3600,        # seconds
        "cleanup_interval": 600,    # seconds
        "redis_url": None,          # Use in-memory if None
    })
    
    # Audio processing settings
    audio_processing: Dict[str, Any] = field(default_factory=lambda: {
        # Silence detection settings
        "silence_threshold": 0.01,
        "min_silence_duration": 0.5,        # seconds
        "min_speech_duration": 0.1,         # seconds
        "silence_window_size_ms": 50,       # milliseconds
        "silence_removal_enabled": True,
        
        # Noise reduction settings
        "noise_reduction_enabled": True,
        "noise_reduction_strength": 0.5,
        "noise_reduction_algorithm": "spectral_subtraction",  # spectral_subtraction, wiener_filter, adaptive_filter
        "noise_reduction_adaptive": True,
        "noise_reduction_preserve_speech": True,
        
        # Audio chunking settings
        "default_chunk_duration": 30.0,     # seconds
        "default_chunk_overlap": 0.0,       # seconds
        "chunk_at_silence_boundaries": True,
        "min_chunk_duration": 1.0,          # seconds
        "max_chunk_duration": 60.0,         # seconds
        
        # General audio settings
        "max_audio_duration": 300.0,        # seconds
        "supported_formats": ["webm", "wav", "mp3", "ogg"],
    })
    
    # Cost monitoring settings
    cost_monitoring: Dict[str, Any] = field(default_factory=lambda: {
        "enabled": True,
        "alert_thresholds": {
            "daily": 10.0,    # USD
            "monthly": 100.0  # USD
        },
        "report_interval": 86400,  # seconds (daily)
    })
    
    # WebSocket settings
    websocket: Dict[str, Any] = field(default_factory=lambda: {
        "max_connections": 100,
        "heartbeat_interval": 30,  # seconds
        "message_timeout": 10,     # seconds
        "max_message_size": 1024 * 1024,  # 1MB
    })
    
    # Logging settings
    logging: Dict[str, Any] = field(default_factory=lambda: {
        "level": "INFO",
        "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        "file": None,  # Log to stdout if None
        "max_file_size": 10 * 1024 * 1024,  # 10MB
        "backup_count": 5,
    })
    
    # Environment-specific settings
    environment: str = "development"
    debug: bool = False
    
    def __post_init__(self):
        """Validate configuration after initialization."""
        self._validate_config()
    
    def _validate_config(self):
        """Validate the configuration settings."""
        # Validate rate limiting settings
        if self.rate_limiting["default_window_size"] <= 0:
            raise ValidationError("rate_limiting.default_window_size", 
                                self.rate_limiting["default_window_size"],
                                "Must be positive")
        
        # Validate caching settings
        if self.caching["max_size_mb"] <= 0:
            raise ValidationError("caching.max_size_mb",
                                self.caching["max_size_mb"],
                                "Must be positive")
        
        # Validate audio processing settings
        if not (0.0 <= self.audio_processing["silence_threshold"] <= 1.0):
            raise ValidationError("audio_processing.silence_threshold",
                                self.audio_processing["silence_threshold"],
                                "Must be between 0.0 and 1.0")
        
        if not (0.0 <= self.audio_processing["noise_reduction_strength"] <= 1.0):
            raise ValidationError("audio_processing.noise_reduction_strength",
                                self.audio_processing["noise_reduction_strength"],
                                "Must be between 0.0 and 1.0")
        
        if self.audio_processing["min_silence_duration"] <= 0:
            raise ValidationError("audio_processing.min_silence_duration",
                                self.audio_processing["min_silence_duration"],
                                "Must be positive")
        
        if self.audio_processing["min_speech_duration"] <= 0:
            raise ValidationError("audio_processing.min_speech_duration",
                                self.audio_processing["min_speech_duration"],
                                "Must be positive")
        
        if self.audio_processing["default_chunk_duration"] <= 0:
            raise ValidationError("audio_processing.default_chunk_duration",
                                self.audio_processing["default_chunk_duration"],
                                "Must be positive")
        
        valid_algorithms = ["spectral_subtraction", "wiener_filter", "adaptive_filter"]
        if self.audio_processing["noise_reduction_algorithm"] not in valid_algorithms:
            raise ValidationError("audio_processing.noise_reduction_algorithm",
                                self.audio_processing["noise_reduction_algorithm"],
                                f"Must be one of: {valid_algorithms}")
        
        # Validate environment
        if self.environment not in ["development", "testing", "staging", "production"]:
            raise ValidationError("environment", self.environment,
                                "Must be one of: development, testing, staging, production")


class ConfigManager:
    """Manages configuration loading, validation, and updates."""
    
    def __init__(self, config_path: Optional[str] = None):
        """
        Initialize the configuration manager.
        
        Args:
            config_path: Path to configuration file (optional)
        """
        self.config_path = config_path or self._get_default_config_path()
        self.config: Optional[VoiceControlConfig] = None
        self._config_history: List[Dict[str, Any]] = []
    
    def _get_default_config_path(self) -> str:
        """Get the default configuration file path."""
        # Check environment variable first
        env_path = os.environ.get("VOICE_CONTROL_CONFIG")
        if env_path and os.path.exists(env_path):
            return env_path
        
        # Check common locations
        possible_paths = [
            "voice_control_config.json",
            "config/voice_control.json",
            "/etc/voice_control/config.json",
            os.path.expanduser("~/.voice_control/config.json")
        ]
        
        for path in possible_paths:
            if os.path.exists(path):
                return path
        
        # Return default path (may not exist yet)
        return "voice_control_config.json"
    
    def load_config(self) -> VoiceControlConfig:
        """
        Load configuration from file or environment variables.
        
        Returns:
            VoiceControlConfig instance
            
        Raises:
            ConfigurationError: If configuration loading fails
        """
        try:
            # Start with default configuration
            config_dict = {}
            
            # Load from file if it exists
            if os.path.exists(self.config_path):
                with open(self.config_path, 'r') as f:
                    file_config = json.load(f)
                    config_dict.update(file_config)
                logger.info(f"Loaded configuration from {self.config_path}")
            else:
                logger.info(f"Configuration file {self.config_path} not found, using defaults")
            
            # Override with environment variables
            env_overrides = self._load_from_environment()
            if env_overrides:
                config_dict.update(env_overrides)
                logger.info("Applied environment variable overrides")
            
            # Create configuration object
            self.config = self._create_config_from_dict(config_dict)
            
            # Save current config to history
            self._save_to_history("load", config_dict)
            
            return self.config
            
        except Exception as e:
            raise ConfigurationError("config_loading", f"Failed to load configuration: {e}")
    
    def _load_from_environment(self) -> Dict[str, Any]:
        """Load configuration overrides from environment variables."""
        env_config = {}
        
        # Environment detection
        if "VOICE_CONTROL_ENV" in os.environ:
            env_config["environment"] = os.environ["VOICE_CONTROL_ENV"]
        
        if "VOICE_CONTROL_DEBUG" in os.environ:
            env_config["debug"] = os.environ["VOICE_CONTROL_DEBUG"].lower() in ("true", "1", "yes")
        
        # Redis URLs
        if "REDIS_URL" in os.environ:
            env_config["rate_limiting"] = {"redis_url": os.environ["REDIS_URL"]}
            env_config["caching"] = {"redis_url": os.environ["REDIS_URL"]}
        
        # Provider API keys
        provider_configs = {}
        
        # Google Speech API
        if "GOOGLE_SPEECH_API_KEY" in os.environ:
            provider_configs["google_speech"] = {
                "name": "google_speech",
                "provider_type": "google_speech",
                "enabled": True,
                "priority": 2,
                "api_credentials": {"api_key": os.environ["GOOGLE_SPEECH_API_KEY"]}
            }
        
        # Azure Speech API
        if "AZURE_SPEECH_KEY" in os.environ and "AZURE_SPEECH_REGION" in os.environ:
            provider_configs["azure_speech"] = {
                "name": "azure_speech", 
                "provider_type": "azure_speech",
                "enabled": True,
                "priority": 3,
                "api_credentials": {
                    "subscription_key": os.environ["AZURE_SPEECH_KEY"],
                    "region": os.environ["AZURE_SPEECH_REGION"]
                }
            }
        
        # AssemblyAI
        if "ASSEMBLYAI_API_KEY" in os.environ:
            provider_configs["assembly_ai"] = {
                "name": "assembly_ai",
                "provider_type": "assembly_ai", 
                "enabled": True,
                "priority": 4,
                "api_credentials": {"api_key": os.environ["ASSEMBLYAI_API_KEY"]}
            }
        
        # Deepgram (existing)
        if "DEEPGRAM_API_KEY" in os.environ:
            provider_configs["deepgram"] = {
                "name": "deepgram",
                "provider_type": "deepgram",
                "enabled": True,
                "priority": 5,
                "api_credentials": {"api_key": os.environ["DEEPGRAM_API_KEY"]}
            }
        
        if provider_configs:
            env_config["providers"] = provider_configs
        
        return env_config
    
    def _create_config_from_dict(self, config_dict: Dict[str, Any]) -> VoiceControlConfig:
        """Create VoiceControlConfig from dictionary."""
        # Handle provider configurations specially
        providers = {}
        if "providers" in config_dict:
            for name, provider_dict in config_dict["providers"].items():
                providers[name] = self._create_provider_config(provider_dict)
            config_dict["providers"] = providers
        
        return VoiceControlConfig(**config_dict)
    
    def _create_provider_config(self, provider_dict: Dict[str, Any]) -> ProviderConfig:
        """Create ProviderConfig from dictionary."""
        # Convert provider_type string to enum
        if "provider_type" in provider_dict and isinstance(provider_dict["provider_type"], str):
            provider_type_str = provider_dict["provider_type"]
            # Handle both enum value strings and full enum representations
            if provider_type_str.startswith("ProviderType."):
                provider_type_str = provider_type_str.split(".")[-1]
            provider_dict["provider_type"] = ProviderType[provider_type_str.upper()]
        
        # Set defaults for missing fields
        defaults = {
            "enabled": True,
            "priority": 10,
            "free_tier_limits": {},
            "rate_limits": {"requests_per_minute": 60},
            "supported_formats": ["webm", "wav", "mp3"],
            "supported_languages": ["en-US"],
            "cost_per_minute": 0.0,
            "api_credentials": {},
            "timeout_seconds": 30,
            "max_retries": 3
        }
        
        for key, default_value in defaults.items():
            if key not in provider_dict:
                provider_dict[key] = default_value
        
        return ProviderConfig(**provider_dict)
    
    def save_config(self, config: Optional[VoiceControlConfig] = None) -> None:
        """
        Save configuration to file.
        
        Args:
            config: Configuration to save (uses current if None)
            
        Raises:
            ConfigurationError: If saving fails
        """
        if config is None:
            config = self.config
        
        if config is None:
            raise ConfigurationError("save_config", "No configuration to save")
        
        try:
            # Convert to dictionary
            config_dict = self._config_to_dict(config)
            
            # Ensure directory exists
            config_dir = os.path.dirname(self.config_path)
            if config_dir:
                os.makedirs(config_dir, exist_ok=True)
            
            # Write to file
            with open(self.config_path, 'w') as f:
                json.dump(config_dict, f, indent=2, default=str)
            
            logger.info(f"Saved configuration to {self.config_path}")
            
            # Save to history
            self._save_to_history("save", config_dict)
            
        except Exception as e:
            raise ConfigurationError("save_config", f"Failed to save configuration: {e}")
    
    def _config_to_dict(self, config: VoiceControlConfig) -> Dict[str, Any]:
        """Convert VoiceControlConfig to dictionary."""
        config_dict = asdict(config)
        
        # Convert provider configs to dictionaries
        if "providers" in config_dict:
            providers_dict = {}
            for name, provider_config in config_dict["providers"].items():
                if isinstance(provider_config, ProviderConfig):
                    provider_dict = asdict(provider_config)
                    # Convert enum to string
                    if "provider_type" in provider_dict:
                        provider_dict["provider_type"] = provider_dict["provider_type"].value
                    providers_dict[name] = provider_dict
                else:
                    # Already a dictionary
                    providers_dict[name] = provider_config
            config_dict["providers"] = providers_dict
        
        return config_dict
    
    def update_config(self, updates: Dict[str, Any]) -> VoiceControlConfig:
        """
        Update configuration with new values.
        
        Args:
            updates: Dictionary of configuration updates
            
        Returns:
            Updated VoiceControlConfig
            
        Raises:
            ConfigurationError: If update fails
        """
        if self.config is None:
            raise ConfigurationError("update_config", "No configuration loaded")
        
        try:
            # Convert current config to dict
            config_dict = self._config_to_dict(self.config)
            
            # Apply updates
            self._deep_update(config_dict, updates)
            
            # Create new config object
            new_config = self._create_config_from_dict(config_dict)
            
            # Validate new configuration
            new_config._validate_config()
            
            # Update current config
            self.config = new_config
            
            # Save to history
            self._save_to_history("update", updates)
            
            logger.info("Configuration updated successfully")
            return self.config
            
        except Exception as e:
            raise ConfigurationError("update_config", f"Failed to update configuration: {e}")
    
    def _deep_update(self, base_dict: Dict[str, Any], updates: Dict[str, Any]) -> None:
        """Recursively update nested dictionary."""
        for key, value in updates.items():
            if key in base_dict and isinstance(base_dict[key], dict) and isinstance(value, dict):
                self._deep_update(base_dict[key], value)
            else:
                base_dict[key] = value
    
    def _save_to_history(self, action: str, data: Dict[str, Any]) -> None:
        """Save configuration change to history."""
        history_entry = {
            "timestamp": datetime.now().isoformat(),
            "action": action,
            "data": data,
            "user": os.environ.get("USER", "system")
        }
        
        self._config_history.append(history_entry)
        
        # Keep only last 100 entries
        if len(self._config_history) > 100:
            self._config_history = self._config_history[-100:]
    
    def get_config_history(self) -> List[Dict[str, Any]]:
        """Get configuration change history."""
        return self._config_history.copy()
    
    def backup_config(self, backup_path: Optional[str] = None) -> str:
        """
        Create a backup of the current configuration.
        
        Args:
            backup_path: Path for backup file (auto-generated if None)
            
        Returns:
            Path to backup file
        """
        if backup_path is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_path = f"{self.config_path}.backup_{timestamp}"
        
        if self.config is None:
            raise ConfigurationError("backup_config", "No configuration to backup")
        
        try:
            config_dict = self._config_to_dict(self.config)
            
            with open(backup_path, 'w') as f:
                json.dump(config_dict, f, indent=2, default=str)
            
            logger.info(f"Configuration backed up to {backup_path}")
            return backup_path
            
        except Exception as e:
            raise ConfigurationError("backup_config", f"Failed to backup configuration: {e}")
    
    def restore_config(self, backup_path: str) -> VoiceControlConfig:
        """
        Restore configuration from backup.
        
        Args:
            backup_path: Path to backup file
            
        Returns:
            Restored VoiceControlConfig
        """
        try:
            with open(backup_path, 'r') as f:
                config_dict = json.load(f)
            
            self.config = self._create_config_from_dict(config_dict)
            
            # Save to history
            self._save_to_history("restore", {"backup_path": backup_path})
            
            logger.info(f"Configuration restored from {backup_path}")
            return self.config
            
        except Exception as e:
            raise ConfigurationError("restore_config", f"Failed to restore configuration: {e}")


# Global configuration manager instance
_config_manager: Optional[ConfigManager] = None


def get_config_manager() -> ConfigManager:
    """Get the global configuration manager instance."""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager


def get_config() -> VoiceControlConfig:
    """Get the current configuration."""
    manager = get_config_manager()
    if manager.config is None:
        manager.load_config()
    return manager.config


def reload_config() -> VoiceControlConfig:
    """Reload configuration from file."""
    manager = get_config_manager()
    return manager.load_config()