#!/usr/bin/env python3
"""
Fix Josephine's loan - update interest to 970 (rollover interest, not original)
"""
import pymysql
import sys
from decimal import Decimal

# PRODUCTION DATABASE CREDENTIALS
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'db': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB',
    'charset': 'utf8mb4'
}

def main():
    print("\n" + "="*80)
    print("FIX JOSEPHINE'S LOAN INTEREST - PRODUCTION")
    print("="*80)
    
    connection = None
    try:
        print("\n1. Connecting to production database...")
        connection = pymysql.connect(**DB_CONFIG)
        print(f"✓ Connected successfully")
        
        with connection.cursor() as cursor:
            # Get Josephine's loan current state
            print("\n2. Checking Josephine's loan (20112026-000001)...")
            cursor.execute("""
                SELECT 
                    id,
                    loan_number,
                    principal_amount,
                    interest_amount,
                    total_amount,
                    original_interest_amount
                FROM loans 
                WHERE loan_number = '20112026-000001'
            """)
            loan = cursor.fetchone()
            
            if not loan:
                print("✗ Loan not found!")
                return 1
            
            loan_id, loan_num, principal, interest, total, orig_interest = loan
            principal = Decimal(str(principal))
            interest = Decimal(str(interest))
            total = Decimal(str(total))
            orig_interest = Decimal(str(orig_interest)) if orig_interest else None
            
            print(f"\n  Current state:")
            print(f"    Principal: KES {principal:,.2f}")
            print(f"    Interest: KES {interest:,.2f}")
            print(f"    Total: KES {total:,.2f}")
            print(f"    Original Interest: KES {orig_interest:,.2f}" if orig_interest else "    Original Interest: Not set")
            
            # Get the rollover interest from rollover_requests
            print("\n3. Getting rollover interest amount...")
            cursor.execute("""
                SELECT requested_interest_rate
                FROM rollover_requests
                WHERE loan_id = %s
                AND status = 'approved'
                ORDER BY requested_at DESC
                LIMIT 1
            """, (loan_id,))
            
            rollover = cursor.fetchone()
            if rollover and rollover[0]:
                rollover_interest = Decimal(str(rollover[0]))
                print(f"  ✓ Found rollover interest: KES {rollover_interest:,.2f}")
            else:
                print("  ⚠️  No rollover interest found, using calculated: 970")
                rollover_interest = Decimal('970.00')
            
            # Calculate correct total
            correct_total = principal + rollover_interest
            
            print(f"\n4. Correcting values...")
            print(f"    New Interest: KES {rollover_interest:,.2f}")
            print(f"    New Total: KES {correct_total:,.2f}")
            
            # Update the loan
            cursor.execute("""
                UPDATE loans
                SET 
                    interest_amount = %s,
                    total_amount = %s
                WHERE id = %s
            """, (rollover_interest, correct_total, loan_id))
            
            connection.commit()
            
            print(f"    ✓ Updated successfully!")
            
            # Verify
            print(f"\n5. Verifying...")
            cursor.execute("""
                SELECT principal_amount, interest_amount, total_amount
                FROM loans WHERE id = %s
            """, (loan_id,))
            
            new_principal, new_interest, new_total = cursor.fetchone()
            new_principal = Decimal(str(new_principal))
            new_interest = Decimal(str(new_interest))
            new_total = Decimal(str(new_total))
            
            print(f"    Principal: KES {new_principal:,.2f}")
            print(f"    Interest: KES {new_interest:,.2f}")
            print(f"    Total: KES {new_total:,.2f}")
            
            if new_interest == rollover_interest and new_total == correct_total:
                print(f"\n  ✓✓✓ SUCCESS! Josephine's loan is now correct!")
            else:
                print(f"\n  ✗ Verification failed!")
                return 1
            
        print("\n" + "="*80)
        print("✓✓✓ COMPLETED! ✓✓✓")
        print("="*80)
        print(f"\nJosephine's loan now shows:")
        print(f"  Principal: KES 9,700")
        print(f"  Interest: KES 970 (rollover interest)")
        print(f"  Total: KES 10,670")
        print("="*80 + "\n")
        
        return 0
        
    except Exception as e:
        print(f"\n✗ ERROR: {e}")
        import traceback
        traceback.print_exc()
        return 1
        
    finally:
        if connection:
            connection.close()
            print("Database connection closed.")

if __name__ == '__main__':
    sys.exit(main())
