#!/usr/bin/env python3
"""
Deploy ALL rollover fixes to production
- Rollover update (not create new loan)
- Rollover payment offset
- Custom interest amounts
"""

import os
import sys
import subprocess

print("=" * 70)
print("🚀 DEPLOYING ROLLOVER FIXES TO PRODUCTION")
print("=" * 70)

# Check we're in the right directory
if not os.path.exists('manage.py'):
    print("\n❌ Error: manage.py not found!")
    print("Please run from Django project root:")
    print("  cd ~/phingrazuri && python deploy_rollover_fixes_production.py")
    sys.exit(1)

print("\n✅ Found Django project")

# Show what will be deployed
print("\n📋 FIXES TO DEPLOY:")
print("-" * 70)
print("1. Rollover Update Logic")
print("   - Updates existing loan instead of creating new one")
print("   - No more duplicate loan number errors")
print("")
print("2. Rollover Payment Offset")
print("   - Tracks payments made before rollover")
print("   - New loan balance excludes old payments")
print("   - Outstanding amount now correct after rollover")
print("")
print("3. Custom Interest Amounts")
print("   - Changed from percentage to actual KES amounts")
print("   - Form shows 'Custom Interest Amount (KES)'")
print("")
print("=" * 70)

response = input("\n🔄 Deploy these fixes now? (yes/no): ")

if response.lower() != 'yes':
    print("❌ Deployment cancelled")
    sys.exit(0)

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

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

migrations_to_run = [
    ('loans', '0031', 'Change interest from percentage to amount'),
    ('loans', '0032', 'Add rollover payment offset field'),
]

for app, migration, description in migrations_to_run:
    print(f"\n📦 {description}...")
    try:
        result = subprocess.run(
            [sys.executable, 'manage.py', 'migrate', app, migration],
            capture_output=True,
            text=True,
            timeout=60
        )
        
        if result.returncode == 0:
            print(f"✅ Migration {migration} completed")
            if result.stdout:
                for line in result.stdout.split('\n'):
                    if line.strip():
                        print(f"   {line}")
        else:
            print(f"❌ Migration {migration} failed!")
            print(f"Error: {result.stderr}")
            
            # Ask if should continue
            cont = input("\n⚠️  Continue with remaining steps? (yes/no): ")
            if cont.lower() != 'yes':
                sys.exit(1)
    except subprocess.TimeoutExpired:
        print(f"❌ Migration {migration} timed out!")
        sys.exit(1)
    except Exception as e:
        print(f"❌ Error running migration {migration}: {e}")
        sys.exit(1)

# Step 2: Verify migrations
print("\n2️⃣ Verifying database schema...")
print("-" * 70)

try:
    result = subprocess.run(
        ['mysql', '-u', 'xygbfpsg_graz', '-pj.ez-xy6##y.rllB', '-D', 'xygbfpsg_loans',
         '-e', 'DESCRIBE loans;'],
        capture_output=True,
        text=True,
        timeout=10
    )
    
    if 'rollover_payment_offset' in result.stdout:
        print("✅ Column 'rollover_payment_offset' exists")
    else:
        print("⚠️  Column 'rollover_payment_offset' not found in schema")
        print("   Migration may not have applied correctly")
        
except Exception as e:
    print(f"⚠️  Could not verify schema: {e}")
    print("   (This is okay - verification is optional)")

# Step 3: Restart Django
print("\n3️⃣ Restarting Django application...")
print("-" * 70)

try:
    os.makedirs('tmp', exist_ok=True)
    restart_file = 'tmp/restart.txt'
    
    # Touch the restart file
    with open(restart_file, 'a'):
        os.utime(restart_file, None)
    
    print(f"✅ Triggered restart (touched {restart_file})")
    print("   Django will reload with new code in a few seconds")
    
except Exception as e:
    print(f"⚠️  Could not trigger automatic restart: {e}")
    print("\n   Please restart manually:")
    print("   - Via cPanel: Application → Python Apps → Restart")
    print("   - Or SSH: touch ~/phingrazuri/tmp/restart.txt")

# Summary
print("\n" + "=" * 70)
print("✅ DEPLOYMENT COMPLETE!")
print("=" * 70)

print("\n📊 DEPLOYED CHANGES:")
print("   ✅ Migration 0031: Interest as amount (not percentage)")
print("   ✅ Migration 0032: Rollover payment offset field")
print("   ✅ Updated models.py: Rollover update logic")
print("   ✅ Updated calculation_service.py: Offset calculation")
print("   ✅ Django restart triggered")

print("\n🧪 TESTING STEPS:")
print("   1. Go to: https://grazuri.uzuriapps.xyz/loans/")
print("   2. Page should load without errors")
print("   3. Try to approve a rollover request")
print("   4. Should work without IntegrityError")
print("   5. Check rolled-over loan:")
print("      - Outstanding balance should be correct")
print("      - Old payments shouldn't count towards new loan")

print("\n📝 NOTES:")
print("   - Existing rolled loans have rollover_payment_offset = 0 (default)")
print("   - To fix existing rolled loans, run the SQL update in the docs")
print("   - New rollovers will automatically set the offset correctly")

print("\n" + "=" * 70)
print("🎉 All done! Test the rollover functionality now.")
print("=" * 70)
