#!/usr/bin/env python3
"""
Auto-deploy rollover fixes (non-interactive)
Runs migrations and restarts Django automatically
"""

import os
import sys
import subprocess

print("=" * 70)
print("🚀 AUTO-DEPLOYING ROLLOVER FIXES")
print("=" * 70)

# Check we're in the right directory
if not os.path.exists('manage.py'):
    print("\n❌ Error: manage.py not found!")
    sys.exit(1)

print("\n✅ Found Django project")

# Step 1: Run migrations
print("\n1️⃣ Running migrations...")
print("-" * 70)

migrations = [
    ('0031_change_interest_to_amount', 'Interest as amount'),
    ('0032_add_rollover_payment_offset', 'Payment offset field'),
]

all_success = True

for migration_file, description in migrations:
    print(f"\n📦 {description} ({migration_file})...")
    try:
        result = subprocess.run(
            [sys.executable, 'manage.py', 'migrate', 'loans'],
            capture_output=True,
            text=True,
            timeout=60
        )
        
        if result.returncode == 0:
            print(f"✅ Migrations completed")
            # Show relevant output lines
            for line in result.stdout.split('\n'):
                if 'Applying' in line or 'OK' in line or 'No migrations' in line:
                    print(f"   {line.strip()}")
        else:
            print(f"❌ Migration failed!")
            print(f"Error: {result.stderr}")
            all_success = False
            
    except Exception as e:
        print(f"❌ Error: {e}")
        all_success = False

# Step 2: Restart Django
print("\n2️⃣ Restarting Django...")
print("-" * 70)

try:
    os.makedirs('tmp', exist_ok=True)
    with open('tmp/restart.txt', 'a'):
        os.utime('tmp/restart.txt', None)
    print("✅ Django restart triggered")
except Exception as e:
    print(f"⚠️  Could not restart: {e}")
    print("   Please restart via cPanel manually")

# Summary
print("\n" + "=" * 70)
if all_success:
    print("✅ DEPLOYMENT SUCCESSFUL!")
else:
    print("⚠️  DEPLOYMENT COMPLETED WITH WARNINGS")
print("=" * 70)

print("\n📊 What was deployed:")
print("   ✅ Migration 0031: Interest field (DECIMAL 5,2 → 12,2)")
print("   ✅ Migration 0032: rollover_payment_offset column")
print("   ✅ Django restart triggered")

print("\n🧪 Next steps:")
print("   1. Visit: https://grazuri.uzuriapps.xyz/loans/")
print("   2. Page should load without column errors")
print("   3. Test approving a rollover")

print("\n" + "=" * 70)

sys.exit(0 if all_success else 1)
