#!/usr/bin/env python3
"""
Direct MySQL migration for PRODUCTION SERVER
Connects directly to production database and adds original interest/fee tracking
"""
import pymysql
import sys

# 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("PRODUCTION SERVER MIGRATION - ORIGINAL INTEREST & FEE TRACKING")
    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 to production database: {DB_CONFIG['db']}")
        
        with connection.cursor() as cursor:
            # Add original_interest_amount column
            print("\n2. Adding original_interest_amount column...")
            try:
                cursor.execute("""
                    ALTER TABLE loans 
                    ADD COLUMN original_interest_amount DECIMAL(12, 2) NULL
                    COMMENT 'Original interest amount - never changes after creation'
                """)
                connection.commit()
                print("✓ original_interest_amount column added")
            except pymysql.err.OperationalError as e:
                if 'Duplicate column name' in str(e):
                    print("✓ original_interest_amount column already exists")
                else:
                    raise
            
            # Add original_processing_fee column
            print("\n3. Adding original_processing_fee column...")
            try:
                cursor.execute("""
                    ALTER TABLE loans 
                    ADD COLUMN original_processing_fee DECIMAL(12, 2) NULL
                    COMMENT 'Original processing fee - never changes after creation'
                """)
                connection.commit()
                print("✓ original_processing_fee column added")
            except pymysql.err.OperationalError as e:
                if 'Duplicate column name' in str(e):
                    print("✓ original_processing_fee column already exists")
                else:
                    raise
            
            # Populate original_interest_amount
            print("\n4. Populating original_interest_amount...")
            cursor.execute("""
                UPDATE loans 
                SET original_interest_amount = interest_amount 
                WHERE original_interest_amount IS NULL
            """)
            rows_updated = cursor.rowcount
            connection.commit()
            print(f"✓ Updated {rows_updated} loans with original_interest_amount")
            
            # Populate original_processing_fee
            print("\n5. Populating original_processing_fee...")
            cursor.execute("""
                UPDATE loans 
                SET original_processing_fee = processing_fee 
                WHERE original_processing_fee IS NULL
            """)
            rows_updated = cursor.rowcount
            connection.commit()
            print(f"✓ Updated {rows_updated} loans with original_processing_fee")
            
            # Verify rolled-over loans
            print("\n6. Verifying rolled-over loans...")
            cursor.execute("""
                SELECT 
                    loan_number,
                    principal_amount,
                    original_disbursed_amount,
                    interest_amount,
                    original_interest_amount,
                    processing_fee,
                    original_processing_fee
                FROM loans 
                WHERE is_rolled_over = 1
                LIMIT 3
            """)
            rolled_loans = cursor.fetchall()
            
            if rolled_loans:
                print(f"✓ Found rolled-over loans. Sample:")
                for loan in rolled_loans:
                    print(f"\n  Loan: {loan[0]}")
                    print(f"    Current Principal: KES {loan[1]:,.2f}")
                    print(f"    Original Disbursed: KES {loan[2]:,.2f}" if loan[2] else "    Original Disbursed: Not set")
                    print(f"    Current Interest: KES {loan[3]:,.2f}")
                    print(f"    Original Interest: KES {loan[4]:,.2f}" if loan[4] else "    Original Interest: Not set")
                    print(f"    Current Fee: KES {loan[5]:,.2f}")
                    print(f"    Original Fee: KES {loan[6]:,.2f}" if loan[6] else "    Original Fee: Not set")
            
            # Check Faith's loan
            print("\n7. Checking Faith's loan (19112026-000001)...")
            cursor.execute("""
                SELECT 
                    loan_number,
                    principal_amount,
                    original_disbursed_amount,
                    interest_amount,
                    original_interest_amount,
                    processing_fee,
                    original_processing_fee,
                    disbursement_date
                FROM loans 
                WHERE loan_number = '19112026-000001'
            """)
            faith_loan = cursor.fetchone()
            
            if faith_loan:
                print(f"✓ Faith's loan found:")
                print(f"    Loan Number: {faith_loan[0]}")
                print(f"    Disbursement Date: {faith_loan[7]}")
                print(f"    Current Principal: KES {faith_loan[1]:,.2f}")
                print(f"    Original Disbursed: KES {faith_loan[2]:,.2f}" if faith_loan[2] else "    Original Disbursed: Not set")
                print(f"    Current Interest: KES {faith_loan[3]:,.2f}")
                print(f"    Original Interest: KES {faith_loan[4]:,.2f}" if faith_loan[4] else "    Original Interest: Not set")
                print(f"    Current Fee: KES {faith_loan[5]:,.2f}")
                print(f"    Original Fee: KES {faith_loan[6]:,.2f}" if faith_loan[6] else "    Original Fee: Not set")
            else:
                print("  ⚠️  Faith's loan not found")
            
            # Summary
            print("\n8. Migration Summary...")
            cursor.execute("""
                SELECT 
                    COUNT(*) as total_loans,
                    SUM(CASE WHEN original_disbursed_amount IS NOT NULL THEN 1 ELSE 0 END) as has_original_principal,
                    SUM(CASE WHEN original_interest_amount IS NOT NULL THEN 1 ELSE 0 END) as has_original_interest,
                    SUM(CASE WHEN original_processing_fee IS NOT NULL THEN 1 ELSE 0 END) as has_original_fee,
                    SUM(CASE WHEN is_rolled_over = 1 THEN 1 ELSE 0 END) as rolled_over_loans
                FROM loans
            """)
            summary = cursor.fetchone()
            
            print(f"\n  Total Loans: {summary[0]}")
            print(f"  Loans with original_disbursed_amount: {summary[1]}")
            print(f"  Loans with original_interest_amount: {summary[2]}")
            print(f"  Loans with original_processing_fee: {summary[3]}")
            print(f"  Rolled-over Loans: {summary[4]}")
            
        print("\n" + "="*80)
        print("✓✓✓ PRODUCTION MIGRATION COMPLETED SUCCESSFULLY! ✓✓✓")
        print("="*80)
        print("\n✅ Disbursement report will now show ORIGINAL interest & fees!")
        print("✅ All rolled-over loans are now tracked correctly!")
        print("\nCheck: https://grazuri.uzuriapps.xyz/reports/disbursed-loans/")
        print("="*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 ALTER and 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("\nDatabase connection closed.")

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