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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
"""
Configuration Management System for SDG Dashboard
Supports JSON/YAML configuration files, environment variables, and runtime updates.

Author: Kilo Code
Version: 2025.1
"""

import json
import os
import logging
from typing import Any, Dict, Optional, Union
from pathlib import Path
from dataclasses import dataclass, field
from copy import deepcopy

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Try to import yaml support
try:
    import yaml
    YAML_AVAILABLE = True
except ImportError:
    YAML_AVAILABLE = False
    logger.info("PyYAML not installed. YAML config files will not be supported.")


@dataclass
class ConfigValidationError(Exception):
    """Exception raised for configuration validation errors."""
    errors: list = field(default_factory=list)
    
    def __str__(self):
        return f"Configuration validation failed: {', '.join(self.errors)}"


class ConfigManager:
    """
    Singleton Configuration Manager for SDG Dashboard.
    
    Features:
    - Load configuration from JSON/YAML files
    - Environment variable support
    - Default configuration values
    - Configuration validation
    - Environment-based configuration (dev, test, prod)
    - Runtime configuration updates
    """
    
    _instance: Optional['ConfigManager'] = None
    _initialized: bool = False
    
    # Default configuration
    DEFAULT_CONFIG = {
        "app": {
            "name": "SDG Dashboard",
            "version": "2025.1",
            "debug": False,
            "log_level": "INFO",
            "secret_key": None
        },
        "data_sources": {
            "primary_data_path": "data/SDR2025-data.xlsx",
            "fallback_data_path": "data/sdg_index_2000-2022.csv",
            "sample_data_enabled": True,
            "cache_ttl_seconds": 3600,
            "api_endpoints": {
                "sdg_api": "https://api.sdgindex.org/v1",
                "un_stats_api": "https://unstats.un.org/sdgapi"
            }
        },
        "ai_engine": {
            "enabled": True,
            "base_url": None,
            "api_key": None,
            "default_model": "azure-gpt-4.1",
            "temperature": 0.6,
            "max_tokens": 4096,
            "cache_enabled": True,
            "cache_ttl_hours": 24,
            "retry_attempts": 3,
            "retry_delay_seconds": 2
        },
        "visualization": {
            "default_theme": "plotly_white",
            "color_scheme": "sdg_official",
            "chart_height": 500,
            "map_projection": "equirectangular",
            "sdg_colors": {
                "1": "#E5243B",
                "2": "#DDA63A",
                "3": "#4C9F38",
                "4": "#C5192D",
                "5": "#FF3A21",
                "6": "#26BDE2",
                "7": "#FCC30B",
                "8": "#A21942",
                "9": "#FD6925",
                "10": "#DD1367",
                "11": "#FD9D24",
                "12": "#BF8B2E",
                "13": "#3F7E44",
                "14": "#0A97D9",
                "15": "#56C02B",
                "16": "#00689D",
                "17": "#19486A"
            },
            "traffic_light_thresholds": {
                "excellent": 80,
                "good": 65,
                "needs_improvement": 50
            }
        },
        "export": {
            "default_format": "pdf",
            "pdf_quality": "high",
            "pptx_template": None,
            "output_directory": "exports",
            "include_metadata": True,
            "max_content_per_slide": 500
        },
        "ui": {
            "page_title": "全球 SDG 互動儀表板 & AI 報告生成器",
            "page_icon": "🌍",
            "layout": "wide",
            "initial_sidebar_state": "expanded",
            "default_language": "繁體中文",
            "default_year_range": [2015, 2025],
            "max_countries_comparison": 5
        },
        "security": {
            "require_api_key": False,
            "allowed_origins": ["*"],
            "rate_limit_requests": 100,
            "rate_limit_period_seconds": 60
        }
    }
    
    # Environment variable mappings
    ENV_MAPPINGS = {
        "SDG_DEBUG": ("app", "debug", lambda x: x.lower() == "true"),
        "SDG_LOG_LEVEL": ("app", "log_level", str),
        "SDG_SECRET_KEY": ("app", "secret_key", str),
        "LITELLM_BASE_URL": ("ai_engine", "base_url", str),
        "LITELLM_API_KEY": ("ai_engine", "api_key", str),
        "SDG_AI_MODEL": ("ai_engine", "default_model", str),
        "SDG_DATA_PATH": ("data_sources", "primary_data_path", str),
        "SDG_CACHE_TTL": ("data_sources", "cache_ttl_seconds", int),
        "SDG_EXPORT_DIR": ("export", "output_directory", str),
        "SDG_ENVIRONMENT": ("app", "environment", str)
    }
    
    def __new__(cls, *args, **kwargs):
        """Implement singleton pattern."""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self, config_dir: Optional[str] = None, environment: Optional[str] = None):
        """
        Initialize the configuration manager.
        
        Args:
            config_dir: Directory containing configuration files
            environment: Environment name (development, production, test)
        """
        if self._initialized:
            return
        
        # Load environment variables first (before any configuration loading)
        self._load_dotenv_if_available()
        
        self._config: Dict[str, Any] = deepcopy(self.DEFAULT_CONFIG)
        self._config_dir = config_dir or os.path.join(os.path.dirname(os.path.dirname(__file__)), "config")
        self._environment = environment or os.environ.get("SDG_ENVIRONMENT", "development")
        self._loaded_files: list = []
        
        # Load configuration
        self._load_configuration()
        self._initialized = True
        
        logger.info(f"ConfigManager initialized for environment: {self._environment}")
    
    def _load_configuration(self):
        """Load configuration from files and environment variables."""
        # 1. Load default configuration file
        self._load_config_file("default.json")
        
        # 2. Load environment-specific configuration
        env_config_file = f"{self._environment}.json"
        self._load_config_file(env_config_file)
        
        # 3. Load environment variables (highest priority)
        self._load_environment_variables()
        
        # 4. Validate configuration
        self._validate_configuration()
    
    def _load_config_file(self, filename: str):
        """Load a configuration file and merge with current config."""
        config_path = os.path.join(self._config_dir, filename)
        
        if not os.path.exists(config_path):
            logger.debug(f"Config file not found: {config_path}")
            return
        
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                if filename.endswith('.yaml') or filename.endswith('.yml'):
                    if not YAML_AVAILABLE:
                        logger.warning(f"Cannot load YAML file {filename}: PyYAML not installed")
                        return
                    file_config = yaml.safe_load(f)
                else:
                    file_config = json.load(f)
            
            if file_config:
                self._merge_config(self._config, file_config)
                self._loaded_files.append(filename)
                logger.info(f"Loaded configuration from: {filename}")
        except Exception as e:
            logger.error(f"Error loading config file {filename}: {e}")
    
    def _merge_config(self, base: Dict, override: Dict):
        """Deep merge override config into base config."""
        for key, value in override.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._merge_config(base[key], value)
            else:
                base[key] = value
    
    def _load_dotenv_if_available(self):
        """Load .env file if python-dotenv is available."""
        try:
            from dotenv import load_dotenv
            # Try to load .env file from current directory and parent directories
            load_dotenv()
            logger.debug("Environment variables loaded from .env file")
        except ImportError:
            logger.debug("python-dotenv not available, skipping .env file loading")
        except Exception as e:
            logger.warning(f"Failed to load .env file: {e}")
    
    def _load_environment_variables(self):
        """Load configuration from environment variables."""
        for env_var, (section, key, converter) in self.ENV_MAPPINGS.items():
            value = os.environ.get(env_var)
            if value is not None:
                try:
                    converted_value = converter(value)
                    if section not in self._config:
                        self._config[section] = {}
                    self._config[section][key] = converted_value
                    logger.debug(f"Loaded {env_var} into config[{section}][{key}]")
                except Exception as e:
                    logger.warning(f"Failed to convert {env_var}={value}: {e}")
    
    def _validate_configuration(self):
        """Validate the loaded configuration."""
        errors = []
        
        # Validate required sections exist
        required_sections = ["app", "data_sources", "ai_engine", "visualization", "export", "ui"]
        for section in required_sections:
            if section not in self._config:
                errors.append(f"Missing required section: {section}")
        
        # Validate data paths
        primary_path = self.get("data_sources.primary_data_path")
        fallback_path = self.get("data_sources.fallback_data_path")
        
        if not primary_path and not fallback_path:
            errors.append("At least one data source path must be configured")
        
        # Validate AI engine settings
        if self.get("ai_engine.enabled"):
            if not self.get("ai_engine.base_url") and not self.get("ai_engine.api_key"):
                logger.info("AI engine is enabled but no credentials configured - will run in mock mode")
                logger.info("To enable AI features, set LITELLM_BASE_URL and LITELLM_API_KEY environment variables")
        
        # Validate thresholds
        thresholds = self.get("visualization.traffic_light_thresholds", {})
        if thresholds:
            if thresholds.get("excellent", 0) < thresholds.get("good", 0):
                errors.append("Excellent threshold must be greater than good threshold")
            if thresholds.get("good", 0) < thresholds.get("needs_improvement", 0):
                errors.append("Good threshold must be greater than needs_improvement threshold")
        
        if errors:
            raise ConfigValidationError(errors=errors)
        
        logger.info("Configuration validation passed")
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        Get a configuration value using dot notation.
        
        Args:
            key: Configuration key (e.g., "app.debug", "ai_engine.base_url")
            default: Default value if key not found
            
        Returns:
            Configuration value or default
        """
        keys = key.split(".")
        value = self._config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key: str, value: Any, persist: bool = False):
        """
        Set a configuration value at runtime.
        
        Args:
            key: Configuration key (dot notation)
            value: Value to set
            persist: Whether to persist to config file (not implemented)
        """
        keys = key.split(".")
        config = self._config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
        logger.debug(f"Set config[{key}] = {value}")
        
        if persist:
            logger.warning("Config persistence is not implemented yet")
    
    def get_section(self, section: str) -> Dict[str, Any]:
        """
        Get an entire configuration section.
        
        Args:
            section: Section name (e.g., "app", "ai_engine")
            
        Returns:
            Configuration section dictionary
        """
        return deepcopy(self._config.get(section, {}))
    
    def get_all(self) -> Dict[str, Any]:
        """Get the entire configuration dictionary."""
        return deepcopy(self._config)
    
    @property
    def environment(self) -> str:
        """Get the current environment name."""
        return self._environment
    
    @property
    def is_debug(self) -> bool:
        """Check if debug mode is enabled."""
        return self.get("app.debug", False)
    
    @property
    def loaded_files(self) -> list:
        """Get list of loaded configuration files."""
        return self._loaded_files.copy()
    
    def reload(self):
        """Reload configuration from files and environment."""
        self._config = deepcopy(self.DEFAULT_CONFIG)
        self._loaded_files = []
        self._load_configuration()
        logger.info("Configuration reloaded")
    
    @classmethod
    def reset_instance(cls):
        """Reset the singleton instance (useful for testing)."""
        cls._instance = None
        cls._initialized = False


# Convenience function for global access
def get_config() -> ConfigManager:
    """
    Get the global ConfigManager instance.
    
    Returns:
        ConfigManager singleton instance
    """
    return ConfigManager()


# Configuration shortcuts
def get_setting(key: str, default: Any = None) -> Any:
    """
    Quick access to configuration settings.
    
    Args:
        key: Configuration key (dot notation)
        default: Default value if not found
        
    Returns:
        Configuration value
    """
    return get_config().get(key, default)



# --- End of ConfigManager ---