#!/usr/bin/env python3
"""
Safely identify and delete duplicate repayments - PRODUCTION VERSION
Uses direct MySQL connection (no Django required)

DUPLICATE DETECTION LOGIC:
--------------------------
Two repayments are considered duplicates if they have:
1. Same loan_id
2. Same amount
3. Same payment_method
4. Payment dates within 5 seconds of each other

SAFETY MEASURES:
----------------
1. 5-second countdown with Ctrl+C abort
2. Groups duplicates and keeps the FIRST one (oldest by created_at or id)
3. Shows detailed preview before deletion
4. Deletes associated receipts first (FK constraints)
5. Recalculates loan _amount_paid_cache after deletion
6. Uses transactions (rollback on error)
"""
import pymysql
import sys
from datetime import datetime, timedelta
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',
    'cursorclass': pymysql.cursors.DictCursor
}

def find_duplicate_repayments(cursor):
    """Find groups of duplicate repayments"""
    print("\n" + "="*80)
    print("SEARCHING FOR DUPLICATE REPAYMENTS")
    print("="*80)
    
    # Get all repayments ordered by loan, payment date
    cursor.execute("""
        SELECT 
            id, loan_id, amount, payment_method, payment_date, 
            receipt_number, created_at
        FROM repayments
        ORDER BY loan_id, payment_date, id
    """)
    
    all_repayments = cursor.fetchall()
    
    duplicate_groups = []
    processed_ids = set()
    
    for repayment in all_repayments:
        if repayment['id'] in processed_ids:
            continue
        
        # Find potential duplicates for this repayment
        # Same loan, same amount, same method, payment date within 5 seconds
        time_window_start = repayment['payment_date'] - timedelta(seconds=5)
        time_window_end = repayment['payment_date'] + timedelta(seconds=5)
        
        cursor.execute("""
            SELECT id, loan_id, amount, payment_method, payment_date, 
                   receipt_number, created_at
            FROM repayments
            WHERE loan_id = %s
              AND amount = %s
              AND payment_method = %s
              AND payment_date >= %s
              AND payment_date <= %s
            ORDER BY created_at, id
        """, (
            repayment['loan_id'],
            repayment['amount'],
            repayment['payment_method'],
            time_window_start,
            time_window_end
        ))
        
        duplicates = cursor.fetchall()
        
        # If we found more than 1, it's a duplicate group
        if len(duplicates) > 1:
            duplicate_ids = [dup['id'] for dup in duplicates]
            
            # Only add if we haven't processed this group yet
            if not any(dup_id in processed_ids for dup_id in duplicate_ids):
                duplicate_groups.append(duplicates)
                processed_ids.update(duplicate_ids)
    
    return duplicate_groups

def get_loan_info(cursor, loan_id):
    """Get loan and borrower information"""
    cursor.execute("""
        SELECT l.loan_number, u.first_name, u.last_name
        FROM loans l
        JOIN users u ON l.borrower_id = u.id
        WHERE l.id = %s
    """, (loan_id,))
    return cursor.fetchone()

def preview_duplicates(cursor, duplicate_groups):
    """Show what would be deleted"""
    if not duplicate_groups:
        print("\n✓ No duplicate repayments found!")
        return False
    
    print(f"\n📊 Found {len(duplicate_groups)} duplicate groups:")
    print("="*80)
    
    total_to_delete = 0
    
    for idx, group in enumerate(duplicate_groups, 1):
        first = group[0]
        loan_info = get_loan_info(cursor, first['loan_id'])
        
        print(f"\nGroup {idx}:")
        print(f"  Loan: {loan_info['loan_number']}")
        print(f"  Borrower: {loan_info['first_name']} {loan_info['last_name']}")
        print(f"  Amount: KES {first['amount']:,.2f}")
        print(f"  Payment Method: {first['payment_method']}")
        print(f"  Count: {len(group)} duplicates")
        print(f"  Action: Keep FIRST (ID: {group[0]['id']}), Delete {len(group)-1} others")
        
        print(f"\n  Details:")
        for rep in group:
            keep_or_delete = "KEEP ✓" if rep == group[0] else "DELETE ✗"
            payment_date_str = rep['payment_date'].strftime('%Y-%m-%d %H:%M:%S')
            print(f"    {keep_or_delete} - ID: {rep['id']}, Receipt: {rep['receipt_number']}, "
                  f"Date: {payment_date_str}")
        
        total_to_delete += len(group) - 1
    
    print("\n" + "="*80)
    print(f"SUMMARY: {total_to_delete} duplicate repayments will be deleted")
    print(f"         {len(duplicate_groups)} repayments will be kept (one per group)")
    print("="*80)
    
    return True

def delete_duplicates(cursor, connection, duplicate_groups):
    """Delete duplicate repayments (keeping the first in each group)"""
    if not duplicate_groups:
        return
    
    print("\n⚠️  DELETION IN PROGRESS")
    print("="*80)
    
    total_deleted = 0
    total_receipts_deleted = 0
    affected_loans = set()
    
    for idx, group in enumerate(duplicate_groups, 1):
        # Keep the first (oldest by created_at/id), delete the rest
        to_keep = group[0]['id']
        to_delete = group[1:]
        
        print(f"\nProcessing Group {idx}...")
        
        for rep in to_delete:
            try:
                rep_id = rep['id']
                loan_id = rep['loan_id']
                affected_loans.add(loan_id)
                
                # Delete associated receipts first
                cursor.execute("""
                    DELETE FROM receipts WHERE repayment_id = %s
                """, (rep_id,))
                receipts_deleted = cursor.rowcount
                total_receipts_deleted += receipts_deleted
                
                # Delete the repayment
                cursor.execute("""
                    DELETE FROM repayments WHERE id = %s
                """, (rep_id,))
                total_deleted += 1
                
                print(f"  ✓ Deleted repayment ID {rep_id} (and {receipts_deleted} receipt(s))")
                
            except Exception as e:
                print(f"  ✗ Error deleting repayment ID {rep_id}: {e}")
                raise
    
    # Recalculate _amount_paid_cache for affected loans
    print(f"\n📊 Recalculating totals for {len(affected_loans)} affected loans...")
    for loan_id in affected_loans:
        try:
            # Calculate total paid from remaining repayments
            cursor.execute("""
                SELECT COALESCE(SUM(amount), 0) as total_paid
                FROM repayments
                WHERE loan_id = %s
            """, (loan_id,))
            result = cursor.fetchone()
            total_paid = result['total_paid']
            
            # Update loan's _amount_paid_cache
            cursor.execute("""
                UPDATE loans
                SET _amount_paid_cache = %s
                WHERE id = %s
            """, (total_paid, loan_id))
            
            # Get loan number for display
            cursor.execute("""
                SELECT loan_number FROM loans WHERE id = %s
            """, (loan_id,))
            loan_info = cursor.fetchone()
            
            print(f"  ✓ Updated loan {loan_info['loan_number']}: KES {total_paid:,.2f} paid")
            
        except Exception as e:
            print(f"  ✗ Error updating loan {loan_id}: {e}")
            raise
    
    print("\n" + "="*80)
    print(f"✓ DELETION COMPLETE")
    print(f"  Repayments deleted: {total_deleted}")
    print(f"  Receipts deleted: {total_receipts_deleted}")
    print(f"  Loans updated: {len(affected_loans)}")
    print("="*80)

def main():
    print("\n" + "="*80)
    print("DUPLICATE REPAYMENT CLEANUP TOOL - PRODUCTION")
    print("="*80)
    
    connection = None
    try:
        # Connect to production MySQL
        print("\n1. Connecting to production database...")
        connection = pymysql.connect(**DB_CONFIG)
        print(f"✓ Connected to: {DB_CONFIG['database']}")
        
        with connection.cursor() as cursor:
            # Step 1: Find duplicates
            duplicate_groups = find_duplicate_repayments(cursor)
            
            if not duplicate_groups:
                print("\n✅ No duplicates found - database is clean!")
                return 0
            
            # Step 2: Preview what would be deleted
            has_duplicates = preview_duplicates(cursor, duplicate_groups)
            
            if not has_duplicates:
                return 0
            
            # Step 3: 5-second countdown with Ctrl+C option
            print("\n" + "="*80)
            print("⚠️  FINAL WARNING ⚠️")
            print("="*80)
            print("This will permanently delete duplicate repayments.")
            print("Press Ctrl+C now to cancel, or wait 5 seconds to proceed...\n")
            
            import time
            try:
                for i in range(5, 0, -1):
                    print(f"  {i}...", end='', flush=True)
                    time.sleep(1)
                print("\n")
            except KeyboardInterrupt:
                print("\n\n✗ Cancelled by user. No data was deleted.")
                return 0
            
            # Step 4: Proceed with deletion
            print("🚀 Starting deletion...")
            
            # Use transaction
            connection.begin()
            try:
                delete_duplicates(cursor, connection, duplicate_groups)
                connection.commit()
                print("\n✅ All changes committed to database!")
                return 0
            except Exception as e:
                connection.rollback()
                print(f"\n✗ ERROR: Deletion failed and was rolled back: {e}")
                import traceback
                traceback.print_exc()
                return 1
                
    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 DELETE 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())
