"""
Diagnose why loan 25112026-000015 is auto-marked as 'paid'
"""
import pymysql

DB_CONFIG = {
    'host': 'localhost',
    'database': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB'
}

conn = pymysql.connect(**DB_CONFIG)
cursor = conn.cursor(pymysql.cursors.DictCursor)

print("=" * 100)
print("DIAGNOSING AUTO-PAID STATUS BUG")
print("=" * 100)

cursor.execute("""
    SELECT loan_number, status, principal_amount, total_amount, amount_paid,
           outstanding_balance, is_rolled_over,
           (amount_paid >= principal_amount) as would_mark_paid,
           (total_amount - amount_paid) as calculated_outstanding
    FROM loans
    WHERE loan_number = '25112026-000015'
""")

loan = cursor.fetchone()

if loan:
    print(f"\nLoan: {loan['loan_number']}")
    print(f"Status: '{loan['status']}'")
    print(f"Is Rolled Over: {loan['is_rolled_over']}")
    print(f"\n{'=' * 100}")
    print("AMOUNTS:")
    print(f"{'=' * 100}")
    print(f"Principal Amount: KES {loan['principal_amount']:,.2f}")
    print(f"Total Amount: KES {loan['total_amount']:,.2f}")
    print(f"Amount Paid: KES {loan['amount_paid']:,.2f}")
    print(f"Outstanding Balance (DB): {loan['outstanding_balance']}")
    print(f"Calculated Outstanding: KES {loan['calculated_outstanding']:,.2f}")
    
    print(f"\n{'=' * 100}")
    print("AUTO-PAID LOGIC CHECK:")
    print(f"{'=' * 100}")
    print(f"\nCode in models.py line 1170:")
    print(f"  if self.amount_paid >= self.principal_amount:")
    print(f"      self.status = 'paid'")
    
    print(f"\nActual values:")
    print(f"  amount_paid ({loan['amount_paid']:,.2f}) >= principal_amount ({loan['principal_amount']:,.2f})?")
    print(f"  {loan['amount_paid']} >= {loan['principal_amount']} = {loan['would_mark_paid']}")
    
    if loan['would_mark_paid']:
        print(f"\n  ✅ YES - This WOULD auto-mark as 'paid'")
        print(f"\n  🐛 BUG CONFIRMED!")
        print(f"     The loan has amount_paid >= principal_amount")
        print(f"     But calculated outstanding is {loan['calculated_outstanding']:,.2f}")
        print(f"     The loan is NOT actually fully paid!")
    else:
        print(f"\n  ❌ NO - Would NOT auto-mark as 'paid'")
        print(f"     But the status IS 'paid' - must have been set manually or by different logic")
    
    print(f"\n{'=' * 100}")
    print("ROOT CAUSE ANALYSIS:")
    print(f"{'=' * 100}")
    
    if loan['amount_paid'] >= loan['principal_amount'] and loan['calculated_outstanding'] > 0:
        print(f"\n🐛 BUG IDENTIFIED:")
        print(f"   The auto-paid logic compares amount_paid to principal_amount")
        print(f"   But for rolled-over loans, this is WRONG because:")
        print(f"   1. Principal amount is the NEW rolled-over principal")
        print(f"   2. Amount paid includes payments from BEFORE the rollover")
        print(f"   3. If old payments >= new principal, it marks as paid incorrectly")
        
        print(f"\n💡 SOLUTION:")
        print(f"   The auto-paid logic should check:")
        print(f"   if self.amount_paid >= self.total_amount:  # Not principal_amount!")
        print(f"       self.status = 'paid'")
        
        print(f"\n   OR better yet:")
        print(f"   if self.outstanding_amount <= 0:")
        print(f"       self.status = 'paid'")
    
else:
    print("\n❌ Loan not found")

cursor.close()
conn.close()

print(f"\n{'=' * 100}\n")
