"""
Fix loans that have 'DELETED' suffix incorrectly added to their loan_number field.

This script:
1. Finds all loans with 'DELETED' in their loan_number
2. Removes the 'DELETED' suffix from the loan_number
3. Ensures is_deleted flag is properly set
4. Reports on the fixes made
"""

import os
import django

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

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

def fix_deleted_loan_numbers():
    """Fix loan numbers that have DELETED suffix"""
    print("=" * 80)
    print("FIXING DELETED LOAN NUMBERS")
    print("=" * 80)
    
    # Find all loans with 'DELETED' in their loan_number
    corrupted_loans = Loan.objects.filter(loan_number__icontains='DELETED')
    
    print(f"\nFound {corrupted_loans.count()} loans with 'DELETED' in loan_number")
    
    if corrupted_loans.count() == 0:
        print("✅ No corrupted loan numbers found!")
        return
    
    fixed_count = 0
    errors = []
    
    for loan in corrupted_loans:
        print(f"\n{'='*60}")
        print(f"Processing: {loan.loan_number}")
        print(f"  Current status: {loan.status}")
        print(f"  is_deleted: {loan.is_deleted}")
        print(f"  Borrower: {loan.borrower.get_full_name()}")
        
        # Extract the original loan number (remove DELETED suffix)
        original_number = loan.loan_number.replace('DELETED', '').replace('deleted', '')
        
        # Check if the original number already exists
        existing_loan = Loan.objects.filter(loan_number=original_number).exclude(pk=loan.pk).first()
        
        if existing_loan:
            print(f"  ⚠️  WARNING: Loan number {original_number} already exists!")
            print(f"     Existing loan: {existing_loan.pk}")
            print(f"     This loan: {loan.pk}")
            print(f"     Skipping to avoid conflict...")
            errors.append(f"{loan.loan_number} - conflict with existing loan")
            continue
        
        try:
            with transaction.atomic():
                # Update the loan number
                loan.loan_number = original_number
                
                # Ensure is_deleted is set correctly
                if not loan.is_deleted:
                    print(f"  ⚠️  Setting is_deleted=True (was False)")
                    loan.is_deleted = True
                    if not loan.deleted_at:
                        from django.utils import timezone
                        loan.deleted_at = timezone.now()
                
                loan.save()
                
                print(f"  ✅ Fixed: {original_number}")
                print(f"     is_deleted: {loan.is_deleted}")
                print(f"     status: {loan.status}")
                fixed_count += 1
                
        except Exception as e:
            print(f"  ❌ Error fixing loan: {str(e)}")
            errors.append(f"{loan.loan_number} - {str(e)}")
    
    # Summary
    print(f"\n{'='*80}")
    print("SUMMARY")
    print(f"{'='*80}")
    print(f"Total loans processed: {corrupted_loans.count()}")
    print(f"Successfully fixed: {fixed_count}")
    print(f"Errors: {len(errors)}")
    
    if errors:
        print(f"\nErrors encountered:")
        for error in errors:
            print(f"  - {error}")
    
    if fixed_count > 0:
        print(f"\n✅ Successfully fixed {fixed_count} loan number(s)!")
    
    print(f"\n{'='*80}")

if __name__ == '__main__':
    fix_deleted_loan_numbers()
