"""
Verify that the rollover report totals are calculating correctly
Specifically checking loan 25112026-000006 and others from the report
"""
import pymysql
from decimal import Decimal

# Production database connection
DB_CONFIG = {
    'host': 'localhost',
    'database': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB'
}

def verify_rollover_totals():
    """Verify rollover report calculations"""
    
    print("=" * 100)
    print("VERIFYING PRODUCTION ROLLOVER REPORT TOTALS")
    print("=" * 100)
    
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    try:
        # Get all approved rollover requests with their loan data
        query = """
        SELECT 
            rr.id as rollover_id,
            l.loan_number,
            l.principal_amount as current_principal,
            l.amount_paid,
            l.outstanding_balance as outstanding_amount,
            l.is_deleted,
            rr.requested_amount as new_principal,
            rr.requested_interest_rate as interest_added,
            rr.reviewed_at,
            rr.status,
            b.fname as first_name,
            b.lname as last_name
        FROM rollover_requests rr
        JOIN loans l ON rr.loan_id = l.id
        JOIN borrowers b ON l.borrower_id = b.id
        WHERE rr.status = 'approved'
        AND l.is_deleted = 0
        ORDER BY rr.reviewed_at DESC
        """
        
        cursor.execute(query)
        rollovers = cursor.fetchall()
        
        print(f"\n📊 Found {len(rollovers)} approved rollover entries")
        print(f"{'=' * 100}\n")
        
        # Calculate totals
        total_new_principal = Decimal('0')
        total_interest = Decimal('0')
        total_total_owed = Decimal('0')
        total_paid = Decimal('0')
        total_outstanding = Decimal('0')
        
        # Group by loan to find the specific one
        from collections import defaultdict
        loans_data = defaultdict(list)
        
        print(f"{'#':<4} {'Loan Number':<20} {'Borrower':<25} {'New Principal':<15} {'Interest':<12} {'Total Owed':<15} {'Paid':<15} {'Outstanding':<15}")
        print("-" * 140)
        
        for idx, rr in enumerate(rollovers, 1):
            new_principal = Decimal(str(rr['new_principal']))
            interest = Decimal(str(rr['interest_added'] or 0))
            total_owed = new_principal + interest
            paid = Decimal(str(rr['amount_paid']))
            outstanding = Decimal(str(rr['outstanding_amount']))
            
            borrower_name = f"{rr['first_name']} {rr['last_name']}"
            
            # Store for specific loan check
            loans_data[rr['loan_number']].append({
                'new_principal': new_principal,
                'interest': interest,
                'total_owed': total_owed,
                'paid': paid,
                'outstanding': outstanding,
                'reviewed_at': rr['reviewed_at']
            })
            
            print(f"{idx:<4} {rr['loan_number']:<20} {borrower_name[:24]:<25} "
                  f"KES {new_principal:>10,.0f}  KES {interest:>8,.0f}  "
                  f"KES {total_owed:>10,.0f}  KES {paid:>10,.0f}  "
                  f"KES {outstanding:>10,.0f}")
            
            total_new_principal += new_principal
            total_interest += interest
            total_total_owed += total_owed
            total_paid += paid
            total_outstanding += outstanding
        
        print("-" * 140)
        print(f"{'TOTALS':<49} KES {total_new_principal:>10,.0f}  KES {total_interest:>8,.0f}  "
              f"KES {total_total_owed:>10,.0f}  KES {total_paid:>10,.0f}  "
              f"KES {total_outstanding:>10,.0f}")
        
        # Check specific loan 25112026-000006
        print(f"\n{'=' * 100}")
        print("CHECKING SPECIFIC LOAN: 25112026-000006")
        print(f"{'=' * 100}")
        
        if '25112026-000006' in loans_data:
            loan_entries = loans_data['25112026-000006']
            print(f"\n✓ Found {len(loan_entries)} rollover entries for 25112026-000006")
            
            for idx, entry in enumerate(loan_entries, 1):
                print(f"\nRollover #{idx}:")
                print(f"  New Principal: KES {entry['new_principal']:,.2f}")
                print(f"  Interest Added: KES {entry['interest']:,.2f}")
                print(f"  Total Owed: KES {entry['total_owed']:,.2f}")
                print(f"  Amount Paid: KES {entry['paid']:,.2f}")
                print(f"  Outstanding: KES {entry['outstanding']:,.2f}")
                print(f"  Reviewed: {entry['reviewed_at']}")
                
                # Verify calculation
                calculated_total = entry['new_principal'] + entry['interest']
                if calculated_total == entry['total_owed']:
                    print(f"  ✅ Math checks out: {entry['new_principal']:,.2f} + {entry['interest']:,.2f} = {entry['total_owed']:,.2f}")
                else:
                    print(f"  ⚠️  Math ERROR: {entry['new_principal']:,.2f} + {entry['interest']:,.2f} ≠ {entry['total_owed']:,.2f}")
        else:
            print("\n⚠️  Loan 25112026-000006 NOT FOUND in rollover report")
            print("   This could mean:")
            print("   1. The loan hasn't been rolled over yet")
            print("   2. The rollover request isn't approved")
            print("   3. The loan is marked as deleted")
            
            # Check if the loan exists
            cursor.execute("""
                SELECT loan_number, is_rolled_over, is_deleted, principal_amount
                FROM loans 
                WHERE loan_number = '25112026-000006'
            """)
            loan = cursor.fetchone()
            
            if loan:
                print(f"\n   Loan exists in database:")
                print(f"   - Is Rolled Over: {loan['is_rolled_over']}")
                print(f"   - Is Deleted: {loan['is_deleted']}")
                print(f"   - Principal: KES {loan['principal_amount']:,.2f}")
                
                # Check rollover requests
                cursor.execute("""
                    SELECT COUNT(*) as count, status
                    FROM rollover_requests rr
                    JOIN loans l ON rr.loan_id = l.id
                    WHERE l.loan_number = '25112026-000006'
                    GROUP BY status
                """)
                rr_status = cursor.fetchall()
                
                if rr_status:
                    print(f"\n   Rollover requests:")
                    for status_row in rr_status:
                        print(f"   - {status_row['status']}: {status_row['count']}")
                else:
                    print(f"\n   ✗ No rollover requests found for this loan")
        
        # Verify the totals from the HTML match our calculation
        print(f"\n{'=' * 100}")
        print("COMPARING WITH REPORTED HTML TOTALS")
        print(f"{'=' * 100}")
        
        # From the HTML provided by user:
        # Totals (11 rollovers): KES 783,130 + KES 56,874 = KES 840,004 | KES 345,505 | KES 417,474
        
        html_total_principal = Decimal('783130')
        html_total_interest = Decimal('56874')
        html_total_balance = Decimal('840004')
        html_total_paid = Decimal('345505')
        html_total_outstanding = Decimal('417474')
        
        print(f"\nHTML Report Shows:")
        print(f"  11 rollovers")
        print(f"  Total Principal: KES {html_total_principal:,.2f}")
        print(f"  Total Interest: KES {html_total_interest:,.2f}")
        print(f"  Total Balance: KES {html_total_balance:,.2f}")
        print(f"  Total Paid: KES {html_total_paid:,.2f}")
        print(f"  Total Outstanding: KES {html_total_outstanding:,.2f}")
        
        print(f"\nDatabase Shows:")
        print(f"  {len(rollovers)} rollovers")
        print(f"  Total Principal: KES {total_new_principal:,.2f}")
        print(f"  Total Interest: KES {total_interest:,.2f}")
        print(f"  Total Balance: KES {total_total_owed:,.2f}")
        print(f"  Total Paid: KES {total_paid:,.2f}")
        print(f"  Total Outstanding: KES {total_outstanding:,.2f}")
        
        print(f"\n{'=' * 100}")
        
        # Check if numbers match
        if len(rollovers) == 11:
            print("✅ Rollover count matches (11)")
        else:
            print(f"⚠️  Rollover count mismatch: HTML shows 11, DB shows {len(rollovers)}")
        
        # Verify math in HTML totals
        html_calculated_balance = html_total_principal + html_total_interest
        if html_calculated_balance == html_total_balance:
            print(f"✅ HTML totals add up: {html_total_principal:,.0f} + {html_total_interest:,.0f} = {html_total_balance:,.0f}")
        else:
            print(f"⚠️  HTML totals DON'T add up: {html_total_principal:,.0f} + {html_total_interest:,.0f} = {html_calculated_balance:,.0f} (not {html_total_balance:,.0f})")
        
    finally:
        cursor.close()
        conn.close()
    
    print(f"\n{'=' * 100}\n")

if __name__ == '__main__':
    verify_rollover_totals()
