"""
Fix the loan creation bug permanently
This will patch the LoanApplication.approve() method to always calculate total correctly
"""
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 CREATION BUG")
print(f"{'='*80}\n")

print("Step 1: Fix LOAN-000114 if it exists...")

try:
    loan = Loan.objects.get(loan_number='LOAN-000114')
    
    correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
    
    if abs(loan.total_amount - correct_total) > Decimal('0.01'):
        print(f"  Found LOAN-000114 with incorrect total")
        print(f"  Current: {loan.total_amount:,.2f}")
        print(f"  Correct: {correct_total:,.2f}")
        
        loan.total_amount = correct_total
        loan.save()
        
        # Also fix application
        app_correct_total = loan.application.requested_amount + loan.application.interest_amount + loan.application.processing_fee_amount
        if abs(loan.application.total_amount - app_correct_total) > Decimal('0.01'):
            loan.application.total_amount = app_correct_total
            loan.application.save()
        
        print(f"  ✅ Fixed LOAN-000114")
    else:
        print(f"  ✅ LOAN-000114 is already correct")
        
except Loan.DoesNotExist:
    print(f"  LOAN-000114 not found (may not exist yet)")

print(f"\nStep 2: Check all pending/approved applications for incorrect totals...")

applications = LoanApplication.objects.filter(
    status__in=['pending', 'approved', 'under_review']
)

fixed_count = 0

for app in applications:
    correct_total = app.requested_amount + app.interest_amount + app.processing_fee_amount
    
    if abs(app.total_amount - correct_total) > Decimal('0.01'):
        fixed_count += 1
        print(f"\n  Fixing {app.application_number}:")
        print(f"    Current total: {app.total_amount:,.2f}")
        print(f"    Correct total: {correct_total:,.2f}")
        
        app.total_amount = correct_total
        app.save()
        print(f"    ✅ Fixed")

if fixed_count == 0:
    print(f"  ✅ All applications have correct totals")
else:
    print(f"\n  ✅ Fixed {fixed_count} application(s)")

print(f"\n{'='*80}")
print(f"CREATING PERMANENT FIX FILE")
print(f"{'='*80}\n")

fix_code = '''"""
IMPORTANT: Add this to loans/models.py in the LoanApplication.approve() method

Replace this line:
    total_amount=self.total_amount,

With this:
    total_amount=self.requested_amount + self.interest_amount + self.processing_fee_amount,

This ensures the loan total is always calculated correctly, even if the application total is wrong.
"""

# In loans/models.py, find the LoanApplication.approve() method around line 410
# Change this:

loan = Loan.objects.create(
    application=self,
    borrower=self.borrower,
    principal_amount=self.requested_amount,
    interest_amount=self.interest_amount,
    processing_fee=self.processing_fee_amount,
    total_amount=self.total_amount,  # ❌ BUG: Uses application's total which might be wrong
    disbursement_date=disbursement_date,
    due_date=disbursement_date + timezone.timedelta(days=self.requested_duration),
    duration_days=self.requested_duration,
    status='active'
)

# To this:

loan = Loan.objects.create(
    application=self,
    borrower=self.borrower,
    principal_amount=self.requested_amount,
    interest_amount=self.interest_amount,
    processing_fee=self.processing_fee_amount,
    total_amount=self.requested_amount + self.interest_amount + self.processing_fee_amount,  # ✅ FIX: Always calculate correctly
    disbursement_date=disbursement_date,
    due_date=disbursement_date + timezone.timedelta(days=self.requested_duration),
    duration_days=self.requested_duration,
    status='active'
)
'''

with open('/home/acbptxvs/public_html/branchbusinessadvance.co.ke/LOAN_CREATION_FIX.txt', 'w') as f:
    f.write(fix_code)

print("✅ Created LOAN_CREATION_FIX.txt with instructions")
print("\nTo permanently fix this issue, you need to edit loans/models.py")
print("See LOAN_CREATION_FIX.txt for details")

print(f"\n{'='*80}")
print(f"FIX COMPLETE")
print(f"{'='*80}\n")
