#!/usr/bin/env python3
"""
Fix total_amount for all rolled-over loans in PRODUCTION
Rolled-over loans should have total_amount = principal + interest
"""
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 ROLLED-OVER LOAN TOTAL AMOUNTS - PRODUCTION")
    print("="*80)
    print(f"\nConnecting to: {DB_CONFIG['db']}@{DB_CONFIG['host']}")
    
    connection = None
    try:
        # Connect to production MySQL
        print("\n1. Connecting to production database...")
        connection = pymysql.connect(
            host=DB_CONFIG['host'],
            port=DB_CONFIG['port'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password'],
            database=DB_CONFIG['db'],
            charset=DB_CONFIG['charset']
        )
        print(f"✓ Connected successfully")
        
        with connection.cursor() as cursor:
            # Find all rolled-over loans with incorrect total_amount
            print("\n2. Finding rolled-over loans with incorrect totals...")
            cursor.execute("""
                SELECT 
                    id,
                    loan_number,
                    principal_amount,
                    interest_amount,
                    total_amount,
                    status,
                    is_rolled_over
                FROM loans 
                WHERE is_rolled_over = 1
                ORDER BY loan_number
            """)
            rolled_loans = cursor.fetchall()
            
            print(f"✓ Found {len(rolled_loans)} rolled-over loans")
            
            if not rolled_loans:
                print("\n✅ No rolled-over loans found. Nothing to fix.")
                return 0
            
            # Check each loan and fix if needed
            print("\n3. Checking and fixing loan totals...")
            fixed_count = 0
            
            for loan in rolled_loans:
                loan_id, loan_number, principal, interest, total, status, is_rolled = loan
                
                # Convert to Decimal for precise calculation
                principal = Decimal(str(principal))
                interest = Decimal(str(interest)) if interest else Decimal('0')
                total = Decimal(str(total)) if total else Decimal('0')
                expected_total = principal + interest
                
                if total != expected_total:
                    print(f"\n  Loan {loan_number} (ID: {loan_id}):")
                    print(f"    Principal: KES {principal:,.2f}")
                    print(f"    Interest: KES {interest:,.2f}")
                    print(f"    Current Total: KES {total:,.2f}")
                    print(f"    Expected Total: KES {expected_total:,.2f}")
                    print(f"    Difference: KES {expected_total - total:,.2f}")
                    
                    # Fix the total
                    cursor.execute("""
                        UPDATE loans 
                        SET total_amount = %s
                        WHERE id = %s
                    """, (expected_total, loan_id))
                    
                    print(f"    ✓ Fixed!")
                    fixed_count += 1
                else:
                    print(f"  ✓ Loan {loan_number}: Total already correct (KES {total:,.2f})")
            
            # Commit all changes
            connection.commit()
            
            print("\n" + "="*80)
            print(f"✓✓✓ COMPLETED! ✓✓✓")
            print("="*80)
            print(f"\n📊 Summary:")
            print(f"  Total rolled-over loans: {len(rolled_loans)}")
            print(f"  Loans fixed: {fixed_count}")
            print(f"  Already correct: {len(rolled_loans) - fixed_count}")
            
            # Show some examples
            print(f"\n📋 Verification - checking a few examples:")
            cursor.execute("""
                SELECT 
                    loan_number,
                    principal_amount,
                    interest_amount,
                    total_amount
                FROM loans 
                WHERE is_rolled_over = 1
                ORDER BY loan_number
                LIMIT 3
            """)
            examples = cursor.fetchall()
            
            for loan_number, principal, interest, total in examples:
                principal = Decimal(str(principal))
                interest = Decimal(str(interest)) if interest else Decimal('0')
                total = Decimal(str(total)) if total else Decimal('0')
                expected = principal + interest
                status_icon = "✓" if total == expected else "✗"
                print(f"  {status_icon} {loan_number}: Total = {total:,.2f}, Expected = {expected:,.2f}")
            
            print("\n" + "="*80 + "\n")
            
        return 0
        
    except pymysql.err.OperationalError as e:
        print(f"\n✗ Database connection error: {e}")
        print("\nPlease check:")
        print("  - Database server is accessible")
        print("  - Credentials are correct")
        print("  - User has UPDATE privileges")
        return 1
        
    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())
