"""
Fix rolled-over loans that have wrong status
- Find loans with status='paid' but have outstanding balance
- Update status back to 'active' 
- Calculate and set outstanding_balance
"""
import pymysql
from decimal import Decimal

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

def fix_loan_statuses():
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    print("=" * 100)
    print("FIXING ROLLED-OVER LOANS WITH WRONG STATUS")
    print("=" * 100)
    
    # Find loans that are marked as 'paid' but have outstanding balance
    cursor.execute("""
        SELECT loan_number, status, is_rolled_over, 
               principal_amount, interest_amount, total_amount, amount_paid,
               outstanding_balance,
               (total_amount - amount_paid) as calculated_outstanding
        FROM loans
        WHERE (status = 'paid' OR status = 'rolled_over')
        AND (total_amount - amount_paid) > 0
        AND is_deleted = 0
        ORDER BY loan_number
    """)
    
    problem_loans = cursor.fetchall()
    
    print(f"\n✓ Found {len(problem_loans)} loans with incorrect status")
    
    if not problem_loans:
        print("\n✅ No loans need fixing!")
        cursor.close()
        conn.close()
        return
    
    print(f"\n{'Loan Number':<20} {'Status':<15} {'Total':<15} {'Paid':<15} {'Outstanding':<15}")
    print("-" * 90)
    
    for loan in problem_loans:
        print(f"{loan['loan_number']:<20} {loan['status']:<15} "
              f"KES {loan['total_amount']:>10,.2f}  KES {loan['amount_paid']:>10,.2f}  "
              f"KES {loan['calculated_outstanding']:>10,.2f}")
    
    print(f"\n{'=' * 100}")
    print("APPLYING FIXES")
    print(f"{'=' * 100}")
    
    fixed_count = 0
    
    for loan in problem_loans:
        loan_number = loan['loan_number']
        calculated_outstanding = loan['calculated_outstanding']
        
        # Update status to 'active' and set outstanding_balance
        cursor.execute("""
            UPDATE loans 
            SET status = 'active',
                outstanding_balance = %s
            WHERE loan_number = %s
        """, (calculated_outstanding, loan_number))
        
        fixed_count += 1
        print(f"\n✓ Fixed {loan_number}:")
        print(f"  - Status: '{loan['status']}' → 'active'")
        print(f"  - Outstanding: NULL → KES {calculated_outstanding:,.2f}")
    
    conn.commit()
    
    print(f"\n{'=' * 100}")
    print(f"✅ FIXED {fixed_count} LOANS!")
    print(f"{'=' * 100}")
    print(f"\nAll rolled-over loans now have:")
    print(f"  • status = 'active' (can be rolled over again)")
    print(f"  • outstanding_balance = calculated value")
    print(f"\nRollover buttons should now appear for all active rolled-over loans.")
    
    cursor.close()
    conn.close()
    
    print(f"\n{'=' * 100}\n")

if __name__ == '__main__':
    fix_loan_statuses()
