"""
Script to fix inconsistent rollover states in the database.

This script identifies and fixes loans that have inconsistent rollover states:
1. Loans with is_rolled_over=True but status != 'rolled_over'
2. Loans with status='rolled_over' but is_rolled_over=False

Run this AFTER deploying the code fix to ensure data consistency.
"""
import os
import django

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

from loans.models import Loan
from django.db.models import Q

def fix_inconsistent_rollover_states():
    """Fix loans with inconsistent rollover states"""
    
    print("=" * 80)
    print("FIXING INCONSISTENT ROLLOVER STATES")
    print("=" * 80)
    
    # Find loans with is_rolled_over=True but status != 'rolled_over'
    print("\n1. Finding loans with is_rolled_over=True but status != 'rolled_over'...")
    inconsistent_flag = Loan.objects.filter(
        is_rolled_over=True
    ).exclude(status='rolled_over')
    
    count_flag = inconsistent_flag.count()
    print(f"   Found {count_flag} loans with inconsistent flag")
    
    if count_flag > 0:
        print("\n   Loans to fix:")
        for loan in inconsistent_flag[:10]:  # Show first 10
            print(f"   - {loan.loan_number}: status={loan.status}, is_rolled_over={loan.is_rolled_over}")
        
        response = input("\n   Fix these loans? (yes/no): ")
        if response.lower() == 'yes':
            updated = inconsistent_flag.update(status='rolled_over')
            print(f"   ✅ Updated {updated} loans to status='rolled_over'")
        else:
            print("   ⏭️  Skipped")
    else:
        print("   ✅ No inconsistent loans found")
    
    # Find loans with status='rolled_over' but is_rolled_over=False
    print("\n2. Finding loans with status='rolled_over' but is_rolled_over=False...")
    inconsistent_status = Loan.objects.filter(
        status='rolled_over',
        is_rolled_over=False
    )
    
    count_status = inconsistent_status.count()
    print(f"   Found {count_status} loans with inconsistent status")
    
    if count_status > 0:
        print("\n   Loans to fix:")
        for loan in inconsistent_status[:10]:  # Show first 10
            print(f"   - {loan.loan_number}: status={loan.status}, is_rolled_over={loan.is_rolled_over}")
        
        response = input("\n   Fix these loans? (yes/no): ")
        if response.lower() == 'yes':
            updated = inconsistent_status.update(is_rolled_over=True)
            print(f"   ✅ Updated {updated} loans to is_rolled_over=True")
        else:
            print("   ⏭️  Skipped")
    else:
        print("   ✅ No inconsistent loans found")
    
    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    
    # Count all rolled-over loans
    all_rolled_over = Loan.objects.filter(
        Q(is_rolled_over=True) | Q(status='rolled_over')
    )
    print(f"\nTotal rolled-over loans: {all_rolled_over.count()}")
    
    # Count consistent rolled-over loans
    consistent_rolled_over = Loan.objects.filter(
        is_rolled_over=True,
        status='rolled_over'
    )
    print(f"Consistent rolled-over loans: {consistent_rolled_over.count()}")
    
    # Count active loans (excluding rolled-over)
    active_loans = Loan.objects.filter(
        status='active',
        is_deleted=False,
        is_rolled_over=False
    ).exclude(status='rolled_over')
    print(f"Active loans (excluding rolled-over): {active_loans.count()}")
    
    print("\n✅ Done!")
    print("=" * 80)

if __name__ == '__main__':
    fix_inconsistent_rollover_states()
