#!/usr/bin/env python3
"""
Production deployment script for rollover interest change
Run this on the production server to deploy the changes
"""

import os
import sys
import subprocess
from datetime import datetime

# Production database credentials
DB_USER = "xygbfpsg_graz"
DB_PASS = "j.ez-xy6##y.rllB"
DB_NAME = "xygbfpsg_loans"
DB_TABLE = "loans_rolloverrequest"

def run_command(cmd, description, critical=True):
    """Run a shell command and handle errors"""
    print(f"\n{description}...")
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ {description} - Success")
            return True, result.stdout
        else:
            print(f"❌ {description} - Failed")
            print(f"Error: {result.stderr}")
            if critical:
                sys.exit(1)
            return False, result.stderr
    except Exception as e:
        print(f"❌ {description} - Exception: {str(e)}")
        if critical:
            sys.exit(1)
        return False, str(e)

def main():
    print("🚀 Deploying Rollover Interest Amount Change to Production")
    print("=" * 60)
    
    # Step 1: Check current directory
    if not os.path.exists('manage.py'):
        print("\n❌ Error: manage.py not found!")
        print("Please run this script from your Django project root directory")
        print("Example: cd ~/public_html && python deploy_to_production.py")
        sys.exit(1)
    
    print("✅ Found manage.py - proceeding with deployment")
    
    # Step 2: Backup database
    print("\n📦 Step 1: Creating database backup...")
    backup_file = f"backup_before_interest_change_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql"
    
    backup_cmd = f"mysqldump -u {DB_USER} -p'{DB_PASS}' {DB_NAME} {DB_TABLE} > {backup_file}"
    run_command(backup_cmd, "Database backup", critical=True)
    print(f"   Backup saved to: {backup_file}")
    
    # Step 3: Check for pending rollovers
    print("\n📊 Step 2: Checking for pending rollover requests...")
    check_cmd = f"mysql -u {DB_USER} -p'{DB_PASS}' -D {DB_NAME} -se \"SELECT COUNT(*) FROM {DB_TABLE} WHERE status='pending' AND requested_interest_rate IS NOT NULL;\""
    
    success, output = run_command(check_cmd, "Checking pending rollovers", critical=False)
    
    if success and output.strip():
        pending_count = int(output.strip())
        print(f"   Found {pending_count} pending rollover requests with custom interest")
        
        if pending_count > 0:
            print("\n⚠️  WARNING: You have pending rollover requests!")
            print("   These have interest stored as percentages.")
            print("   After migration, they will be treated as KES amounts.")
            print("\n   Example: If a request has 8.5 (meant 8.5%),")
            print("            it will be read as KES 8.50 after migration!")
            
            response = input("\n   Continue with migration? (yes/no): ")
            if response.lower() != 'yes':
                print("❌ Deployment cancelled by user")
                sys.exit(0)
    
    # Step 4: Run Django migration
    print("\n🔄 Step 3: Running database migration...")
    migration_cmd = f"{sys.executable} manage.py migrate loans 0031"
    
    run_command(migration_cmd, "Django migration", critical=True)
    
    # Step 5: Verify migration
    print("\n🔍 Step 4: Verifying migration...")
    verify_cmd = f"mysql -u {DB_USER} -p'{DB_PASS}' -D {DB_NAME} -se \"DESCRIBE {DB_TABLE};\""
    
    success, output = run_command(verify_cmd, "Verifying schema", critical=False)
    if success and 'requested_interest_rate' in output:
        if 'decimal(12,2)' in output.lower():
            print("✅ Schema verified: requested_interest_rate is DECIMAL(12,2)")
        else:
            print("⚠️  Schema check: Could not verify field size")
    
    # Step 6: Restart application
    print("\n🔄 Step 5: Restarting Django application...")
    restart_file = "tmp/restart.txt"
    
    try:
        os.makedirs('tmp', exist_ok=True)
        with open(restart_file, 'a'):
            os.utime(restart_file, None)
        print("✅ Application restart triggered (touched tmp/restart.txt)")
    except Exception as e:
        print(f"⚠️  Could not trigger automatic restart: {str(e)}")
        print("   Please restart manually via cPanel:")
        print("   Application → Python Apps → Restart")
    
    # Summary
    print("\n" + "=" * 60)
    print("✅ Deployment completed successfully!")
    print("\nChanges deployed:")
    print("  ✓ Database field: DECIMAL(5,2) → DECIMAL(12,2)")
    print("  ✓ Form field: 'Custom Interest Rate (%)' → 'Custom Interest Amount (KES)'")
    print("  ✓ Calculation: Now uses direct amount instead of percentage")
    print("\nNext steps:")
    print("  1. Test creating a new rollover request")
    print("  2. Verify the form shows 'Custom Interest Amount (KES)'")
    print("  3. Enter an amount like 5000 (means KES 5,000)")
    print("  4. Approve the rollover and verify interest amount is correct")
    print("  5. Review any existing pending rollovers (if any)")
    print(f"\nBackup location: {backup_file}")
    print("=" * 60)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n❌ Deployment cancelled by user (Ctrl+C)")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ Unexpected error: {str(e)}")
        sys.exit(1)
