"""
Diagnose Loan Calculation Issues

This script checks for loans where the stored amounts don't match
what they should be based on the duration and rates.
"""

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan
from decimal import Decimal

def diagnose_loans():
    """Check all loans for calculation discrepancies"""
    
    print("=" * 80)
    print("LOAN CALCULATION DIAGNOSTICS")
    print("=" * 80)
    print()
    
    all_loans = Loan.active_objects.select_related('application__loan_product').all()
    print(f"📊 Checking {all_loans.count()} loans...")
    print()
    
    issues_found = 0
    
    for loan in all_loans:
        try:
            # Get the loan product
            product = loan.application.loan_product
            
            # Calculate what the amounts SHOULD be
            months = max(1, loan.duration_days / 30)
            
            # Expected interest
            expected_interest = product.calculate_interest(loan.principal_amount, months)
            
            # Expected processing fee
            expected_processing_fee = product.calculate_processing_fee(loan.principal_amount, months)
            
            # Expected total
            expected_total = loan.principal_amount + expected_interest + expected_processing_fee
            
            # Check for discrepancies
            interest_diff = abs(loan.interest_amount - expected_interest)
            processing_diff = abs(loan.processing_fee - expected_processing_fee)
            total_diff = abs(loan.total_amount - expected_total)
            
            # If any difference is more than 1 KES (accounting for rounding)
            if interest_diff > 1 or processing_diff > 1 or total_diff > 1:
                issues_found += 1
                
                print(f"⚠️  ISSUE FOUND: Loan {loan.loan_number}")
                print(f"   Borrower: {loan.borrower.get_full_name()}")
                print(f"   Product: {product.name}")
                print(f"   Duration: {loan.duration_days} days ({months:.2f} months)")
                print(f"   Principal: KES {loan.principal_amount:,.2f}")
                print()
                
                if interest_diff > 1:
                    print(f"   ❌ Interest Mismatch:")
                    print(f"      Stored:   KES {loan.interest_amount:,.2f}")
                    print(f"      Expected: KES {expected_interest:,.2f}")
                    print(f"      Diff:     KES {interest_diff:,.2f}")
                    print()
                
                if processing_diff > 1:
                    print(f"   ❌ Processing Fee Mismatch:")
                    print(f"      Stored:   KES {loan.processing_fee:,.2f}")
                    print(f"      Expected: KES {expected_processing_fee:,.2f}")
                    print(f"      Diff:     KES {processing_diff:,.2f}")
                    print()
                
                if total_diff > 1:
                    print(f"   ❌ Total Amount Mismatch:")
                    print(f"      Stored:   KES {loan.total_amount:,.2f}")
                    print(f"      Expected: KES {expected_total:,.2f}")
                    print(f"      Diff:     KES {total_diff:,.2f}")
                    print()
                
                # Try to figure out what calculation was used
                # Check if it matches 1-month calculation
                one_month_interest = product.calculate_interest(loan.principal_amount, 1)
                one_month_processing = product.calculate_processing_fee(loan.principal_amount, 1)
                one_month_total = loan.principal_amount + one_month_interest + one_month_processing
                
                if abs(loan.total_amount - one_month_total) < 1:
                    print(f"   💡 DIAGNOSIS: Loan appears to be calculated for 1 month instead of {months:.2f} months")
                    print(f"      1-month total would be: KES {one_month_total:,.2f}")
                    print()
                
                print("-" * 80)
                print()
        
        except Exception as e:
            print(f"❌ Error checking loan {loan.loan_number}: {str(e)}")
            print()
    
    print("=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Total loans checked: {all_loans.count()}")
    print(f"Issues found: {issues_found}")
    print(f"Loans OK: {all_loans.count() - issues_found}")
    print()
    
    if issues_found > 0:
        print("⚠️  Some loans have calculation discrepancies!")
        print("   This could be due to:")
        print("   1. Loans created with wrong duration calculation")
        print("   2. Loans edited with incorrect formulas")
        print("   3. Manual adjustments by admins")
        print()
        print("   To fix these loans, you can:")
        print("   - Edit each loan manually to correct the amounts")
        print("   - Run a fix script to recalculate all amounts")
    else:
        print("✅ All loans have correct calculations!")
    
    print("=" * 80)

if __name__ == '__main__':
    diagnose_loans()
