#!/usr/bin/env python3
"""
Environment Switcher Script
Quickly switch between development, staging, and production environments
"""

import sys
import os
import json
from config_loader import ConfigLoader

def main():
    if len(sys.argv) < 2:
        print("Usage: python switch_env.py <environment>")
        print("Available environments:")
        config_loader = ConfigLoader()
        for env in config_loader.get_available_environments():
            config = config_loader.get_config(env)
            print(f"  - {env}: {config.get('name', env)} - {config.get('description', '')}")
        return
    
    environment = sys.argv[1]
    
    try:
        config_loader = ConfigLoader()
        
        if environment not in config_loader.get_available_environments():
            print(f"Error: Environment '{environment}' not found")
            print("Available environments:", config_loader.get_available_environments())
            return
        
        # Set the environment
        config_loader.set_environment(environment)
        
        # Get the configuration
        config = config_loader.get_current_config()
        
        print(f"✅ Switched to {environment} environment")
        print(f"   Name: {config.get('name', environment)}")
        print(f"   Description: {config.get('description', '')}")
        print(f"   Website URL: {config.get('website', {}).get('url', 'N/A')}")
        print(f"   Database: {config.get('database', {}).get('mongodb_db', 'N/A')}")
        
        # Validate configuration
        if config_loader.validate_config():
            print("✅ Configuration is valid")
        else:
            print("⚠️ Configuration has issues - check the logs")
        
        # Export environment variables
        env_vars = config_loader.export_to_env_format()
        
        # Create .env file for current environment
        env_file_path = '.env'
        with open(env_file_path, 'w') as f:
            f.write(f"# Environment: {environment}\n")
            f.write(f"# Generated by switch_env.py\n\n")
            for key, value in env_vars.items():
                if value:  # Only write non-empty values
                    f.write(f"{key}={value}\n")
        
        print(f"✅ Environment variables exported to {env_file_path}")
        print(f"✅ You can now run your application with the {environment} configuration")
        
    except Exception as e:
        print(f"Error: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
