#!/usr/bin/env python
"""
Production Deployment Script - Quick & Non-Interactive
Handles migrations, static files, and post-deployment tasks
"""
import os
import sys
import subprocess
from datetime import datetime

def run_command(command, description):
    """Run a shell command quickly"""
    print(f"\n▶ {description}...")
    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=60
        )
        if result.returncode == 0:
            print(f"✓ {description} completed")
            return True
        else:
            print(f"⚠ {description} had issues: {result.stderr[:200]}")
            return False
    except subprocess.TimeoutExpired:
        print(f"⚠ {description} timed out")
        return False
    except Exception as e:
        print(f"⚠ {description} failed: {str(e)[:200]}")
        return False

def main():
    """Main deployment process"""
    print(f"\n{'='*50}")
    print(f"  Quick Deployment - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*50}")
    
    success = True
    
    # 1. Migrate database
    if not run_command("python manage.py migrate --noinput", "Database migrations"):
        success = False
    
    # 2. Collect static files
    run_command("python manage.py collectstatic --noinput --clear", "Static files")
    
    # 3. Clear cache
    print("\n▶ Clearing cache...")
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        import django
        django.setup()
        from django.core.cache import cache
        cache.clear()
        print("✓ Cache cleared")
    except:
        print("⚠ Cache clear skipped")
    
    # Summary
    print(f"\n{'='*50}")
    if success:
        print("✓ Deployment completed successfully!")
        print("\nNext steps:")
        print("  • Restart server: touch tmp/restart.txt (cPanel)")
        print("  • Test the application")
    else:
        print("⚠ Deployment completed with warnings")
        print("  Review the output above")
    print(f"{'='*50}\n")
    
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())
