"""
Fix loan 18112026-000012 to use the correct interest from the last renewal
"""
import pymysql

DB_HOST = "localhost"
DB_PORT = 3306
DB_NAME = "xygbfpsg_loans"
DB_USER = "xygbfpsg_graz"
DB_PASSWORD = "j.ez-xy6##y.rllB"

conn = pymysql.connect(
    host=DB_HOST, port=DB_PORT, db=DB_NAME,
    user=DB_USER, password=DB_PASSWORD, charset="utf8mb4",
    autocommit=False
)

try:
    with conn.cursor() as cur:
        # Get the last approved rollover's interest amount
        cur.execute("""
            SELECT requested_interest_rate
            FROM rollover_requests
            WHERE loan_id = (SELECT id FROM loans WHERE loan_number = '18112026-000012')
              AND status = 'approved'
            ORDER BY reviewed_at DESC
            LIMIT 1
        """)
        row = cur.fetchone()
        
        if row:
            new_interest = float(row[0])
            print(f"Last approved rollover interest: {new_interest:,.2f}")
            
            # Update the loan
            cur.execute("""
                UPDATE loans
                SET interest_amount = %s,
                    total_amount = principal_amount + %s
                WHERE loan_number = '18112026-000012'
            """, [new_interest, new_interest])
            
            print(f"Updated loan 18112026-000012:")
            print(f"  interest_amount → {new_interest:,.2f}")
            print(f"  total_amount → 93,000 + {new_interest:,.2f} = {93000 + new_interest:,.2f}")
            
            conn.commit()
            print("✓ Committed")
        else:
            print("No approved rollover found")
            
except Exception as e:
    conn.rollback()
    print(f"Error: {e}")
    import traceback
    traceback.print_exc()
finally:
    conn.close()
