"""
Centralized Configuration Loader
Loads environment-specific configuration from config/environments.json
"""

import os
import json
import logging
from typing import Dict, Any, Optional

class ConfigLoader:
    def __init__(self, config_file_path: str = None):
        """
        Initialize the configuration loader
        
        Args:
            config_file_path: Path to the environments.json file
        """
        if config_file_path is None:
            # Default to config/environments.json relative to project root
            current_dir = os.path.dirname(os.path.abspath(__file__))
            config_file_path = os.path.join(current_dir, 'environments.json')
        
        self.config_file_path = config_file_path
        self.config_data = None
        self.current_env = None
        self.logger = logging.getLogger(__name__)
        
        self._load_config()
    
    def _load_config(self):
        """Load configuration from JSON file"""
        try:
            with open(self.config_file_path, 'r') as f:
                self.config_data = json.load(f)
            
            # Determine current environment
            self.current_env = self._detect_environment()
            self.logger.info(f"Configuration loaded for environment: {self.current_env}")
            
        except FileNotFoundError:
            self.logger.error(f"Configuration file not found: {self.config_file_path}")
            raise
        except json.JSONDecodeError as e:
            self.logger.error(f"Invalid JSON in configuration file: {e}")
            raise
    
    def _detect_environment(self) -> str:
        """Detect the current environment"""
        # Check if auto-detect is enabled
        if self.config_data.get('settings', {}).get('auto_detect_environment', True):
            # Check environment variables
            env_from_var = os.environ.get('AI_TEST_ENV')
            if env_from_var and env_from_var in self.config_data.get('environments', {}):
                return env_from_var
            
            # Check if we're in development (common indicators)
            if os.path.exists('.env') or 'localhost' in os.environ.get('HOST', ''):
                return 'development'
            
            # Check if we're in production (common indicators)
            if 'production' in os.environ.get('ENVIRONMENT', '').lower():
                return 'production'
        
        # Fallback to configured current environment
        return self.config_data.get('current_environment', 'development')
    
    def get_config(self, environment: str = None) -> Dict[str, Any]:
        """
        Get configuration for a specific environment
        
        Args:
            environment: Environment name (defaults to current environment)
        
        Returns:
            Configuration dictionary for the environment
        """
        if environment is None:
            environment = self.current_env
        
        environments = self.config_data.get('environments', {})
        if environment not in environments:
            self.logger.warning(f"Environment '{environment}' not found, falling back to development")
            environment = 'development'
        
        return environments.get(environment, {})
    
    def get_current_config(self) -> Dict[str, Any]:
        """Get configuration for the current environment"""
        return self.get_config(self.current_env)
    
    def get_website_config(self) -> Dict[str, Any]:
        """Get website-specific configuration"""
        config = self.get_current_config()
        return config.get('website', {})
    
    def get_database_config(self) -> Dict[str, Any]:
        """Get database-specific configuration"""
        config = self.get_current_config()
        return config.get('database', {})
    
    def get_ai_config(self) -> Dict[str, Any]:
        """Get AI-specific configuration"""
        config = self.get_current_config()
        return config.get('ai', {})
    
    def get_integrations_config(self) -> Dict[str, Any]:
        """Get integrations configuration"""
        config = self.get_current_config()
        return config.get('integrations', {})
    
    def get_email_config(self) -> Dict[str, Any]:
        """Get email configuration"""
        config = self.get_current_config()
        return config.get('email', {})
    
    def get_security_config(self) -> Dict[str, Any]:
        """Get security configuration"""
        config = self.get_current_config()
        return config.get('security', {})
    
    def get_logging_config(self) -> Dict[str, Any]:
        """Get logging configuration"""
        config = self.get_current_config()
        return config.get('logging', {})
    
    def set_environment(self, environment: str):
        """Set the current environment"""
        if environment in self.config_data.get('environments', {}):
            self.current_env = environment
            self.logger.info(f"Environment changed to: {environment}")
        else:
            self.logger.error(f"Invalid environment: {environment}")
    
    def get_available_environments(self) -> list:
        """Get list of available environments"""
        return list(self.config_data.get('environments', {}).keys())
    
    def validate_config(self) -> bool:
        """Validate the current configuration"""
        try:
            config = self.get_current_config()
            
            # Check required fields
            required_sections = ['website', 'database', 'ai', 'security']
            for section in required_sections:
                if section not in config:
                    self.logger.error(f"Missing required section: {section}")
                    return False
            
            # Check website URL
            website_url = config.get('website', {}).get('url')
            if not website_url:
                self.logger.error("Website URL is required")
                return False
            
            self.logger.info("Configuration validation passed")
            return True
            
        except Exception as e:
            self.logger.error(f"Configuration validation failed: {e}")
            return False
    
    def export_to_env_format(self) -> Dict[str, str]:
        """Export configuration as environment variables format"""
        config = self.get_current_config()
        env_vars = {}
        
        # Website config
        website = config.get('website', {})
        env_vars['BASE_URL'] = website.get('url', '')
        env_vars['WEBSITE_URL'] = website.get('url', '')
        env_vars['FLASK_HOST'] = website.get('host', 'localhost')
        env_vars['FLASK_PORT'] = str(website.get('port', 5008))
        
        # Database config
        database = config.get('database', {})
        env_vars['MONGODB_URI'] = database.get('mongodb_uri', '')
        env_vars['MONGODB_DB'] = database.get('mongodb_db', '')
        env_vars['MONGO_URI'] = database.get('mongodb_uri', '')
        env_vars['MONGO_DB'] = database.get('mongodb_db', '')
        env_vars['MONGO_COLLECTION'] = database.get('mongodb_collection', '')
        
        # AI config
        ai = config.get('ai', {})
        env_vars['OPENAI_API_KEY'] = ai.get('openai_api_key', '')
        env_vars['OPENROUTER_API_KEY'] = ai.get('openrouter_api_key', '')
        env_vars['OPENROUTER_SITE_URL'] = ai.get('openrouter_site_url', '')
        env_vars['OPENROUTER_SITE_NAME'] = ai.get('openrouter_site_name', '')
        
        # Integrations
        integrations = config.get('integrations', {})
        jira = integrations.get('jira', {})
        env_vars['JIRA_URL'] = jira.get('url', '')
        env_vars['JIRA_USER'] = jira.get('user', '')
        env_vars['JIRA_API_TOKEN'] = jira.get('api_token', '')
        
        azure = integrations.get('azure_devops', {})
        env_vars['AZURE_DEVOPS_URL'] = azure.get('url', '')
        env_vars['AZURE_DEVOPS_ORG'] = azure.get('org', '')
        env_vars['AZURE_DEVOPS_PROJECT'] = azure.get('project', '')
        env_vars['AZURE_DEVOPS_PAT'] = azure.get('pat', '')
        env_vars['AZURE_DEVOPS_WORKITEM_ID'] = azure.get('workitem_id', '')
        
        # Email config
        email = config.get('email', {})
        env_vars['EMAIL_SMTP_SERVER'] = email.get('smtp_server', '')
        env_vars['EMAIL_SMTP_PORT'] = str(email.get('smtp_port', 587))
        env_vars['EMAIL_USERNAME'] = email.get('username', '')
        env_vars['EMAIL_PASSWORD'] = email.get('password', '')
        env_vars['EMAIL_FROM_ADDRESS'] = email.get('from_address', '')
        env_vars['EMAIL_USE_TLS'] = str(email.get('use_tls', True)).lower()
        env_vars['EMAIL_USE_SSL'] = str(email.get('use_ssl', False)).lower()
        env_vars['EMAIL_RECIPIENTS'] = ','.join(email.get('recipients', []))
        
        # Security config
        security = config.get('security', {})
        env_vars['JWT_SECRET_KEY'] = security.get('jwt_secret_key', '')
        
        # Logging config
        logging_config = config.get('logging', {})
        env_vars['LOG_LEVEL'] = logging_config.get('level', 'info')
        env_vars['LOG_FILE'] = logging_config.get('file', 'app.log')
        env_vars['ENABLE_MONGO_LOGGER'] = str(logging_config.get('enable_mongo_logger', False)).lower()
        
        return env_vars

# Global instance
config_loader = ConfigLoader()

def get_config(environment: str = None) -> Dict[str, Any]:
    """Get configuration for a specific environment"""
    return config_loader.get_config(environment)

def get_current_config() -> Dict[str, Any]:
    """Get configuration for the current environment"""
    return config_loader.get_current_config()

def get_website_config() -> Dict[str, Any]:
    """Get website-specific configuration"""
    return config_loader.get_website_config()

def get_database_config() -> Dict[str, Any]:
    """Get database-specific configuration"""
    return config_loader.get_database_config()

def get_ai_config() -> Dict[str, Any]:
    """Get AI-specific configuration"""
    return config_loader.get_ai_config()

def get_integrations_config() -> Dict[str, Any]:
    """Get integrations configuration"""
    return config_loader.get_integrations_config()

def get_email_config() -> Dict[str, Any]:
    """Get email configuration"""
    return config_loader.get_email_config()

def get_security_config() -> Dict[str, Any]:
    """Get security configuration"""
    return config_loader.get_security_config()

def get_logging_config() -> Dict[str, Any]:
    """Get logging configuration"""
    return config_loader.get_logging_config()

def set_environment(environment: str):
    """Set the current environment"""
    config_loader.set_environment(environment)

def get_available_environments() -> list:
    """Get list of available environments"""
    return config_loader.get_available_environments()

def validate_config() -> bool:
    """Validate the current configuration"""
    return config_loader.validate_config()

def export_to_env_format() -> Dict[str, str]:
    """Export configuration as environment variables format"""
    return config_loader.export_to_env_format()

def apply_to_process_env():
    """Apply configuration to process environment variables"""
    env_vars = config_loader.export_to_env_format()
    
    # Apply environment variables to the current process
    for key, value in env_vars.items():
        if value:  # Only set non-empty values
            os.environ[key] = value