#!/usr/bin/env python3
"""
Deploy script to change rollover interest from percentage to amount in KES
This script will:
1. Run the migration to change the field from DECIMAL(5,2) to DECIMAL(12,2)
2. Update any existing rollover requests (if needed)
"""

import os
import sys
import django
from decimal import Decimal

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Load environment variables
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    print("⚠️  Warning: python-dotenv not installed, using system environment variables")

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from loans.models import RolloverRequest

def main():
    print("🚀 Deploying Rollover Interest Amount Change")
    print("=" * 60)
    
    # Step 1: Run migrations
    print("\n📦 Step 1: Running database migrations...")
    try:
        call_command('migrate', 'loans', verbosity=2)
        print("✅ Migrations completed successfully")
    except Exception as e:
        print(f"❌ Migration failed: {str(e)}")
        return False
    
    # Step 2: Check existing rollover requests
    print("\n📊 Step 2: Checking existing rollover requests...")
    try:
        pending_rollovers = RolloverRequest.objects.filter(status='pending')
        count = pending_rollovers.count()
        print(f"Found {count} pending rollover requests")
        
        if count > 0:
            print("\n⚠️  Note: Existing pending rollover requests have interest values stored as percentages.")
            print("   These will need to be reviewed and updated by admins if they need to be approved.")
            print("   Future rollover requests will use actual KES amounts.")
            
            for rollover in pending_rollovers[:5]:  # Show first 5
                print(f"   - Loan {rollover.loan.loan_number}: Interest value = {rollover.requested_interest_rate}")
        else:
            print("✅ No pending rollover requests to worry about")
            
    except Exception as e:
        print(f"❌ Error checking rollover requests: {str(e)}")
        return False
    
    print("\n" + "=" * 60)
    print("✅ Deployment completed successfully!")
    print("\nChanges made:")
    print("1. Database field changed from DECIMAL(5,2) to DECIMAL(12,2)")
    print("2. Field now accepts interest amount in KES instead of percentage")
    print("3. Templates updated to show 'Custom Interest Amount (KES)'")
    print("4. Validation updated to accept amounts (no max limit)")
    print("\nNext steps:")
    print("- Restart the Django server to load the updated templates")
    print("- Test creating a new rollover request with custom interest amount")
    print("- Review any existing pending rollover requests")
    
    return True

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
