#!/usr/bin/env python
"""
Environment Configuration Validator
This script validates that all required environment variables are properly configured.
"""

import os
import sys
from pathlib import Path

# Add the project root to Python path
BASE_DIR = Path(__file__).resolve().parent
sys.path.append(str(BASE_DIR))

def load_environment():
    """Load environment variables from .env file"""
    try:
        from dotenv import load_dotenv
        load_dotenv()
        print("✅ Environment variables loaded from .env file")
        return True
    except ImportError:
        print("❌ python-dotenv not installed. Run: pip install python-dotenv")
        return False
    except Exception as e:
        print(f"❌ Error loading .env file: {e}")
        return False

def validate_django_settings():
    """Validate Django settings configuration"""
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
        import django
        from django.conf import settings
        django.setup()
        
        print("\n🔧 Django Configuration Validation:")
        
        # Check DEBUG setting
        if settings.DEBUG:
            print("✅ DEBUG mode: Enabled (development)")
        else:
            print("⚠️  DEBUG mode: Disabled (production)")
        
        # Check SECRET_KEY
        if settings.SECRET_KEY and len(settings.SECRET_KEY) > 20:
            print("✅ SECRET_KEY: Configured")
        else:
            print("❌ SECRET_KEY: Missing or too short")
        
        # Check database configuration
        db_engine = settings.DATABASES['default']['ENGINE']
        if 'sqlite3' in db_engine:
            print("✅ Database: SQLite (development)")
        elif 'mysql' in db_engine:
            print("✅ Database: MySQL (production)")
        else:
            print(f"⚠️  Database: {db_engine}")
        
        # Check ALLOWED_HOSTS
        if settings.ALLOWED_HOSTS:
            print(f"✅ ALLOWED_HOSTS: {settings.ALLOWED_HOSTS}")
        else:
            print("❌ ALLOWED_HOSTS: Not configured")
        
        return True
        
    except Exception as e:
        print(f"❌ Django configuration error: {e}")
        return False

def validate_cloudinary():
    """Validate Cloudinary configuration"""
    print("\n☁️  Cloudinary Configuration Validation:")
    
    required_vars = ['CLOUDINARY_CLOUD_NAME', 'CLOUDINARY_API_KEY', 'CLOUDINARY_API_SECRET']
    all_present = True
    
    for var in required_vars:
        value = os.getenv(var)
        if value:
            print(f"✅ {var}: Configured")
        else:
            print(f"❌ {var}: Missing")
            all_present = False
    
    # Check storage backend
    storage_backend = os.getenv('REVIEW_IMAGE_STORAGE_BACKEND', 'filesystem')
    print(f"✅ REVIEW_IMAGE_STORAGE_BACKEND: {storage_backend}")
    
    return all_present

def validate_email():
    """Validate email configuration"""
    print("\n📧 Email Configuration Validation:")
    
    email_vars = {
        'EMAIL_HOST': os.getenv('EMAIL_HOST'),
        'EMAIL_PORT': os.getenv('EMAIL_PORT'),
        'EMAIL_HOST_USER': os.getenv('EMAIL_HOST_USER'),
        'EMAIL_HOST_PASSWORD': os.getenv('EMAIL_HOST_PASSWORD')
    }
    
    all_present = True
    for var, value in email_vars.items():
        if value:
            if 'PASSWORD' in var:
                print(f"✅ {var}: Configured (hidden)")
            else:
                print(f"✅ {var}: {value}")
        else:
            print(f"❌ {var}: Missing")
            all_present = False
    
    return all_present

def main():
    """Main validation function"""
    print("🔍 Panjabiz Backend Environment Validation")
    print("=" * 50)
    
    # Check if .env file exists
    env_file = BASE_DIR / '.env'
    if env_file.exists():
        print("✅ .env file found")
    else:
        print("❌ .env file not found. Copy .env.example to .env and configure it.")
        return False
    
    # Load environment
    if not load_environment():
        return False
    
    # Validate configurations
    django_ok = validate_django_settings()
    cloudinary_ok = validate_cloudinary()
    email_ok = validate_email()
    
    print("\n" + "=" * 50)
    if django_ok and cloudinary_ok and email_ok:
        print("🎉 All configurations are valid! Your development environment is ready.")
        return True
    else:
        print("⚠️  Some configurations need attention. Please check the issues above.")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)