"""
Configuration file for database settings.

Environment modes:
- ENV=local: Uses local .env file variables (DB_HOST, DB_USER, etc.)
- ENV=dev: Uses AWS dev environment (Parameter Store + Secrets Manager)
- ENV=qa: Uses AWS QA environment (Parameter Store + Secrets Manager)

For local development, set ENV=local in your .env file to bypass AWS entirely.
"""
import os
import json
import logging
import boto3
from dotenv import load_dotenv

# Load environment variables from .env file
# Force .env to override any pre-set environment variables so server-local .env wins
load_dotenv(override=True)

def get_aws_credentials():
    """Get database credentials from AWS Parameter Store and Secrets Manager."""
    # Resolve environment: prefer .env value (already loaded), fallback to QA
    environment = os.getenv('ENV') or 'qa'
    if environment not in {'dev', 'qa', 'local'}:
        # Harden against unexpected values, but allow 'local'
        environment = 'qa'
    # Ensure downstream reads see the resolved value
    os.environ['ENV'] = environment
    
    # If local environment, this function shouldn't be called
    if environment == 'local':
        raise ValueError("get_aws_credentials() called for local environment. Use get_local_credentials() instead.")
    
    # Define environment-specific configurations
    configs = {
        'dev': {
            'secret_name': "rds!cluster-91f2520d-663f-4a7b-9f72-cc0878bdf354",
            'ssm_param_name': "rdsDetails"
        },
        'qa': {
            'secret_name': "rds!cluster-252d62f4-d31e-4fe7-a51e-7f96a6a82e3f",
            'ssm_param_name': "rdsDetailsQA"
        }
    }
    
    # Get configuration for current environment
    config = configs.get(environment)
    if not config:
        raise ValueError(f"Unsupported environment: {environment}. Supported environments: {list(configs.keys())}")
    
    region = os.getenv('AWS_REGION', 'ap-southeast-2')
    
    try:
        # Get secrets from AWS Secrets Manager
        secrets_client = boto3.client('secretsmanager', region_name=region)
        secret_response = secrets_client.get_secret_value(SecretId=config['secret_name'])
        secret_data = json.loads(secret_response['SecretString'])
        
        # Get parameters from AWS Parameter Store
        ssm_client = boto3.client('ssm', region_name=region)
        param_response = ssm_client.get_parameter(
            Name=config['ssm_param_name'],
            WithDecryption=False
        )
        param_values = param_response['Parameter']['Value'].split(',')
        
        # Parse parameter values (format: key=value)
        param_dict = {}
        for param in param_values:
            key, value = param.split('=', 1)
            param_dict[key] = value
        
        # Build credentials dictionary
        credentials = {
            'host': param_dict.get('host', 'localhost'),
            'database': param_dict.get('database', 'auto_clicker'),
            'user': secret_data.get('username', 'auto_clicker_user'),
            'password': secret_data.get('password'),
            'port': int(param_dict.get('port', 3306)),
            'autocommit': True
        }
        
        return credentials
        
    except Exception as e:
        raise Exception(f"Failed to retrieve AWS credentials: {str(e)}")

def get_local_credentials():
    """Get database credentials from environment variables (fallback)."""
    return {
        'host': os.getenv('DB_HOST', 'localhost'),
        'database': os.getenv('DB_NAME', 'BigPond'),
        'user': os.getenv('DB_USER', 'auto_clicker_user'),
        'password': os.getenv('DB_PASSWORD', 'your_password'),
        'port': int(os.getenv('DB_PORT', 3306)),
        'autocommit': True
    }

# Check environment and use appropriate credentials
environment = os.getenv('ENV', 'qa')

if environment == 'local':
    print(f"🏠 Using local environment variables for ENV={environment}")
    MYSQL_CONFIG = get_local_credentials()
else:
    # Try to get AWS credentials for dev/qa environments
    try:
        MYSQL_CONFIG = get_aws_credentials()
        print(f"✅ Using AWS credentials for environment: {environment}")
    except Exception as e:
        print(f"⚠️  AWS credentials not available ({str(e)}), falling back to local environment variables")
        MYSQL_CONFIG = get_local_credentials()

def refresh_mysql_config():
    """Refresh MySQL configuration by re-fetching credentials from AWS or local env.
    
    This is useful when credentials are rotated (e.g., every 7 days) or when
    connection errors occur. Updates the global MYSQL_CONFIG dictionary.
    """
    global MYSQL_CONFIG
    environment = os.getenv('ENV', 'qa')
    
    try:
        if environment == 'local':
            # Reload .env file to get latest local credentials
            load_dotenv(override=True)
            MYSQL_CONFIG = get_local_credentials()
            logging.info(f"[MySQL] Refreshed local MySQL config for ENV={environment}")
        else:
            # Re-fetch from AWS Secrets Manager and Parameter Store
            MYSQL_CONFIG = get_aws_credentials()
            logging.info(f"[MySQL] Refreshed AWS MySQL config for ENV={environment}")
        return True
    except Exception as e:
        logging.error(f"[MySQL] Failed to refresh MySQL config: {e}")
        # Fallback to local credentials if AWS fails
        try:
            load_dotenv(override=True)
            MYSQL_CONFIG = get_local_credentials()
            logging.warning(f"[MySQL] Fallback to local credentials after refresh failure")
            return True
        except Exception as fallback_error:
            logging.error(f"[MySQL] Fallback to local credentials also failed: {fallback_error}")
            return False

# Validate configuration
def validate_config():
    """Validate that all required configuration values are set."""
    required_fields = ['host', 'database', 'user', 'password']
    missing_fields = []
    
    for field in required_fields:
        if not MYSQL_CONFIG.get(field) or MYSQL_CONFIG[field] == 'your_password':
            missing_fields.append(field)
    
    if missing_fields:
        raise ValueError(f"Missing required configuration fields: {missing_fields}. Please check your .env file.")
    
    return True

if __name__ == "__main__":
    try:
        validate_config()
        print("Configuration is valid!")
        print(f"Database: {MYSQL_CONFIG['database']} on {MYSQL_CONFIG['host']}:{MYSQL_CONFIG['port']}")
        print(f"User: {MYSQL_CONFIG['user']}")
    except ValueError as e:
        print(f"Configuration error: {e}")