#!/usr/bin/env python3
"""
Automated cPanel deployment script for Yatra booking system.
Run this script after uploading files to cPanel to set up the application.
"""
import os
import sys
import subprocess
import getpass

def run_command(command, description=""):
    """Execute a shell command and handle errors."""
    print(f"\n{'='*50}")
    if description:
        print(f"📋 {description}")
    print(f"🔧 Running: {command}")
    print(f"{'='*50}")
    
    try:
        result = subprocess.run(command, shell=True, check=True, 
                              capture_output=True, text=True)
        if result.stdout:
            print(f"✅ Output:\n{result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Error: {e}")
        if e.stdout:
            print(f"Output: {e.stdout}")
        if e.stderr:
            print(f"Error output: {e.stderr}")
        return False

def check_environment():
    """Check if the environment supports our deployment."""
    print("🔍 Checking cPanel environment...")
    
    # Check Python version
    python_version = run_command("python3 --version", "Checking Python 3 version")
    if not python_version:
        python_version = run_command("python --version", "Checking Python version")
    
    # Check pip
    pip_available = run_command("pip3 --version", "Checking pip3 availability")
    if not pip_available:
        pip_available = run_command("python3 -m pip --version", "Checking pip via python3 -m")
    
    return python_version and pip_available

def install_dependencies():
    """Install Python dependencies."""
    print("\n📦 Installing Python dependencies...")
    
    # Try different pip installation methods
    pip_commands = [
        "pip3 install --user -r requirements.txt",
        "python3 -m pip install --user -r requirements.txt",
        "pip install --user -r requirements.txt"
    ]
    
    for cmd in pip_commands:
        if run_command(cmd, f"Installing dependencies with: {cmd}"):
            return True
    
    print("❌ Failed to install dependencies with any method")
    return False

def setup_database():
    """Set up Django database."""
    print("\n🗄️ Setting up database...")
    
    # Run migrations
    commands = [
        ("python3 manage.py makemigrations", "Creating migrations"),
        ("python3 manage.py makemigrations testing_app", "Creating testing_app migrations"),
        ("python3 manage.py migrate --run-syncdb", "Running database migrations"),
    ]
    
    for cmd, desc in commands:
        if not run_command(cmd, desc):
            return False
    
    return True

def collect_static_files():
    """Collect static files for production."""
    print("\n📁 Collecting static files...")
    return run_command("python3 manage.py collectstatic --noinput", 
                      "Collecting static files")

def create_superuser():
    """Create Django superuser."""
    print("\n👤 Creating superuser account...")
    print("You'll need to create an admin account for the Django admin panel.")
    
    choice = input("Create superuser now? (y/n): ").lower().strip()
    if choice == 'y':
        return run_command("python3 manage.py createsuperuser", 
                          "Creating superuser account")
    else:
        print("⏭️  Skipping superuser creation. Run 'python3 manage.py createsuperuser' later.")
        return True

def create_htaccess():
    """Create .htaccess file for Apache."""
    htaccess_content = """# Yatra Booking System - cPanel Configuration
RewriteEngine On
RewriteBase /

# Handle Django static files
RewriteRule ^static/(.*)$ /static/$1 [L]
RewriteRule ^media/(.*)$ /media/$1 [L]

# Route all other requests to Django WSGI
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /passenger_wsgi.py/$1 [QSA,L]

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
</IfModule>

# Compress static files
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Cache static files
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
</IfModule>
"""
    
    try:
        with open('.htaccess', 'w') as f:
            f.write(htaccess_content)
        print("✅ Created .htaccess file")
        return True
    except Exception as e:
        print(f"❌ Failed to create .htaccess: {e}")
        return False

def set_permissions():
    """Set proper file permissions."""
    print("\n🔐 Setting file permissions...")
    
    commands = [
        ("chmod 755 passenger_wsgi.py", "Setting WSGI permissions"),
        ("chmod 755 manage.py", "Setting manage.py permissions"),
        ("find . -name '*.py' -exec chmod 644 {} \\;", "Setting Python file permissions"),
    ]
    
    for cmd, desc in commands:
        run_command(cmd, desc)

def display_final_instructions():
    """Display final setup instructions."""
    print(f"\n{'='*60}")
    print("🎉 cPanel Deployment Complete!")
    print(f"{'='*60}")
    print("""
📋 FINAL STEPS TO COMPLETE:

1. 🗄️ DATABASE SETUP:
   - Go to cPanel → MySQL Databases
   - Create database: yourusername_yatra
   - Create user and assign to database
   - Update yatra_testing/settings.py with your database details

2. 🌐 PYTHON APP SETUP (Recommended):
   - Go to cPanel → Setup Python App
   - Create new app with these settings:
     * Python version: 3.8+
     * Application root: /public_html/
     * Application URL: your domain
     * Application startup file: passenger_wsgi.py

3. 🔧 UPDATE SETTINGS:
   Edit yatra_testing/settings.py:
   - ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
   - Database credentials
   - DEBUG = False
   - STATIC_ROOT and MEDIA_ROOT paths

4. 🔒 SSL CERTIFICATE (Recommended):
   - cPanel → SSL/TLS → Enable "Force HTTPS Redirect"

5. 📊 TEST YOUR DEPLOYMENT:
   - Visit: yourdomain.com
   - Admin panel: yourdomain.com/admin/
   - Check that CSS/JS loads properly

6. ⚡ REDIS (For real-time features):
   - Option A: Use Redis cloud service (Redis Labs, AWS)
   - Option B: Keep current in-memory setup (single process only)

📚 For detailed instructions, see: cpanel_deployment_guide.md

🚀 Your Yatra booking system is ready for production!
""")

def main():
    """Main deployment function."""
    print("🚀 Yatra Booking System - cPanel Deployment Script")
    print("=" * 60)
    
    # Check if we're in the right directory
    if not os.path.exists('manage.py'):
        print("❌ Error: manage.py not found!")
        print("Please run this script from the Django project directory.")
        sys.exit(1)
    
    # Step 1: Check environment
    if not check_environment():
        print("❌ Environment check failed. Please ensure Python 3 and pip are available.")
        sys.exit(1)
    
    # Step 2: Install dependencies
    if not install_dependencies():
        print("❌ Failed to install dependencies.")
        sys.exit(1)
    
    # Step 3: Setup database
    database_setup = input("\nSetup database now? (y/n): ").lower().strip()
    if database_setup == 'y':
        if not setup_database():
            print("❌ Database setup failed.")
            sys.exit(1)
    else:
        print("⏭️  Skipping database setup.")
    
    # Step 4: Collect static files
    if not collect_static_files():
        print("⚠️  Static file collection failed, but continuing...")
    
    # Step 5: Create superuser
    create_superuser()
    
    # Step 6: Create .htaccess
    create_htaccess()
    
    # Step 7: Set permissions
    set_permissions()
    
    # Step 8: Final instructions
    display_final_instructions()

if __name__ == "__main__":
    main()