"""
Production Fix for LOAN-000113
This script will fix the incorrect interest and processing fee calculations
"""
import os
import sys

# Set production database credentials
os.environ['DB_NAME'] = 'xygbfpsg_graz'
os.environ['DB_USER'] = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = ',qdN3O_!}oC67(]W'
os.environ['DB_HOST'] = 'localhost'
os.environ['DB_PORT'] = '3306'

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

from loans.models import Loan, LoanApplication
from decimal import Decimal

print(f"\n{'='*80}")
print(f"FIXING LOAN-000113")
print(f"{'='*80}\n")

try:
    # Get the loan
    loan = Loan.objects.get(loan_number='LOAN-000113')
    
    print(f"Found loan: {loan.loan_number}")
    print(f"Borrower: {loan.borrower.get_full_name()}")
    print(f"Product: {loan.application.loan_product.name}")
    
    print(f"\nCURRENT VALUES:")
    print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
    print(f"  Interest:        KES {loan.interest_amount:>12,.2f}")
    print(f"  Processing Fee:  KES {loan.processing_fee:>12,.2f}")
    print(f"  Total:           KES {loan.total_amount:>12,.2f}")
    print(f"  Duration:        {loan.duration_days} days")
    
    # Calculate correct values
    months = loan.duration_days / 30  # 3 months
    
    # Calculate correct interest (using product method which uses system settings)
    correct_interest = loan.application.loan_product.calculate_interest(loan.principal_amount, months)
    
    # Calculate correct processing fee (using product method which uses system settings)
    correct_processing_fee = loan.application.loan_product.calculate_processing_fee(loan.principal_amount, months)
    
    # Calculate correct total
    correct_total = loan.principal_amount + correct_interest + correct_processing_fee
    
    print(f"\nCORRECT VALUES:")
    print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
    print(f"  Interest:        KES {correct_interest:>12,.2f}  (was {loan.interest_amount:,.2f})")
    print(f"  Processing Fee:  KES {correct_processing_fee:>12,.2f}  (was {loan.processing_fee:,.2f})")
    print(f"  Total:           KES {correct_total:>12,.2f}  (was {loan.total_amount:,.2f})")
    
    print(f"\nDIFFERENCES:")
    print(f"  Interest:        +KES {correct_interest - loan.interest_amount:>12,.2f}")
    print(f"  Processing Fee:  +KES {correct_processing_fee - loan.processing_fee:>12,.2f}")
    print(f"  Total:           +KES {correct_total - loan.total_amount:>12,.2f}")
    
    # Ask for confirmation (but auto-confirm in production)
    print(f"\n{'='*80}")
    print(f"APPLYING FIX...")
    print(f"{'='*80}\n")
    
    # Update the loan
    loan.interest_amount = correct_interest
    loan.processing_fee = correct_processing_fee
    loan.total_amount = correct_total
    loan.save()
    
    print(f"✅ Loan {loan.loan_number} has been fixed!")
    
    # Also fix the application
    app = loan.application
    print(f"\nFixing application {app.application_number}...")
    
    app.interest_amount = correct_interest
    app.processing_fee_amount = correct_processing_fee
    app.total_amount = correct_total
    app.save()
    
    print(f"✅ Application {app.application_number} has been fixed!")
    
    # Verify the fix
    loan.refresh_from_db()
    print(f"\nVERIFICATION:")
    print(f"  Principal:       KES {loan.principal_amount:>12,.2f}")
    print(f"  Interest:        KES {loan.interest_amount:>12,.2f}")
    print(f"  Processing Fee:  KES {loan.processing_fee:>12,.2f}")
    print(f"  Total:           KES {loan.total_amount:>12,.2f}")
    
    # Check calculation
    verify_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
    if abs(verify_total - loan.total_amount) < Decimal('0.01'):
        print(f"\n✅ Verification passed! Total = Principal + Interest + Processing Fee")
    else:
        print(f"\n❌ Verification failed! Total mismatch: {verify_total:,.2f} vs {loan.total_amount:,.2f}")
    
    print(f"\n{'='*80}")
    print(f"FIX COMPLETE!")
    print(f"{'='*80}\n")
    
except Loan.DoesNotExist:
    print(f"❌ Loan LOAN-000113 not found")
    sys.exit(1)
except Exception as e:
    print(f"\n❌ ERROR: {str(e)}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
