"""
Fix ALL rolled-over loans to use correct interest from their last renewal.

This script:
1. Finds all rolled-over loans
2. For each loan, gets the last approved rollover's interest amount
3. Updates the loan's interest_amount and total_amount to match

Run: python3 fix_all_rollover_interest.py
"""
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
)

print("=" * 100)
print("  FIX ALL ROLLED-OVER LOANS — Update interest_amount from last renewal")
print("=" * 100)
print()

try:
    with conn.cursor() as cur:
        # Get all rolled-over loans
        cur.execute("""
            SELECT id, loan_number, principal_amount, interest_amount, total_amount
            FROM loans
            WHERE is_rolled_over = 1 AND is_deleted = 0
            ORDER BY loan_number
        """)
        loans = cur.fetchall()
        
        print(f"Found {len(loans)} rolled-over loan(s)\n")
        
        fixed_count = 0
        skipped_count = 0
        
        for loan_id, loan_num, principal, old_interest, old_total in loans:
            # Get the last approved rollover's interest
            cur.execute("""
                SELECT requested_interest_rate, reviewed_at
                FROM rollover_requests
                WHERE loan_id = %s AND status = 'approved'
                ORDER BY reviewed_at DESC
                LIMIT 1
            """, [loan_id])
            
            rollover = cur.fetchone()
            
            if rollover and rollover[0] is not None:
                new_interest = float(rollover[0])
                reviewed_at = rollover[1]
                new_total = float(principal) + new_interest
                
                # Check if update needed
                if abs(float(old_interest) - new_interest) > 0.01 or abs(float(old_total) - new_total) > 0.01:
                    print(f"Loan {loan_num}:")
                    print(f"  Principal:       {float(principal):>12,.2f}")
                    print(f"  OLD interest:    {float(old_interest):>12,.2f}")
                    print(f"  NEW interest:    {new_interest:>12,.2f}  (from rollover {reviewed_at})")
                    print(f"  OLD total:       {float(old_total):>12,.2f}")
                    print(f"  NEW total:       {new_total:>12,.2f}")
                    
                    # Update
                    cur.execute("""
                        UPDATE loans
                        SET interest_amount = %s,
                            total_amount = principal_amount + %s
                        WHERE id = %s
                    """, [new_interest, new_interest, loan_id])
                    
                    print(f"  ✓ Updated\n")
                    fixed_count += 1
                else:
                    print(f"Loan {loan_num}: Already correct (interest={float(old_interest):,.2f}, total={float(old_total):,.2f})")
                    skipped_count += 1
            else:
                print(f"Loan {loan_num}: No approved rollover with interest found — SKIPPED")
                skipped_count += 1
        
        print()
        print("=" * 100)
        print(f"Summary:")
        print(f"  Total rolled-over loans:  {len(loans)}")
        print(f"  Fixed:                    {fixed_count}")
        print(f"  Already correct/skipped:  {skipped_count}")
        print("=" * 100)
        
        if fixed_count > 0:
            confirm = input(f"\nCommit these {fixed_count} updates? (yes/no): ").strip().lower()
            if confirm == 'yes':
                conn.commit()
                print("✓ All updates committed successfully")
            else:
                conn.rollback()
                print("✗ Rolled back — no changes made")
        else:
            print("\nNo updates needed — all loans already correct")
            
except Exception as e:
    conn.rollback()
    print(f"\n✗ ERROR: {e}")
    import traceback
    traceback.print_exc()
finally:
    conn.close()
