#!/usr/bin/env python3
"""
Delete specific test users and all their loans from PRODUCTION database
CAUTION: This is irreversible!
"""
import pymysql
import sys

# PRODUCTION DATABASE CREDENTIALS
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'database': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB',
    'charset': 'utf8mb4'
}

# Users to delete (first name last name - case insensitive)
USERS_TO_DELETE = [
    ('Joshua', 'Kariuki'),
    ('Margaret', 'Kangiri'),
    ('Faith', 'Kibuchi'),
    ('Josphine', 'Mwangi'),
    ('Rose', 'Njuguna'),
    ('James', 'Irungu'),
]

def main():
    print("\n" + "="*80)
    print("DELETE SPECIFIC USERS AND THEIR LOANS - PRODUCTION")
    print("="*80)
    print("\n⚠️  WARNING: This will permanently delete:")
    print("   - Joshua Kariuki")
    print("   - Margaret Kangiri")
    print("   - Faith Kibuchi")
    print("   - Josphine Mwangi")
    print("   - Rose Njuguna")
    print("   - James Irungu")
    print("   - ALL their loans, applications, repayments, and related data")
    print("\n" + "="*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:
            # First, discover the correct table names
            print("\n2. Discovering table structure...")
            cursor.execute("SHOW TABLES")
            tables = [table[0] for table in cursor.fetchall()]
            
            # Find the users table
            user_table = None
            for table in tables:
                if 'user' in table.lower() and 'custom' in table.lower():
                    user_table = table
                    break
            
            if not user_table:
                # Try other common patterns
                for table in tables:
                    if table.lower() in ['users', 'customuser', 'auth_user']:
                        user_table = table
                        break
            
            if not user_table:
                print(f"✗ Could not find users table!")
                print(f"Available tables: {', '.join(tables[:10])}...")
                return 1
            
            print(f"  ✓ Found users table: {user_table}")
            
            # Find users by name
            print("\n3. Finding users to delete...")
            user_ids = []
            found_users = []
            
            for first_name, last_name in USERS_TO_DELETE:
                cursor.execute(f"""
                    SELECT id, username, first_name, last_name, email, phone_number
                    FROM {user_table}
                    WHERE LOWER(first_name) LIKE LOWER(%s)
                    AND LOWER(last_name) LIKE LOWER(%s)
                    AND role = 'borrower'
                """, (f'%{first_name}%', f'%{last_name}%'))
                
                users = cursor.fetchall()
                for user in users:
                    user_id, username, fname, lname, email, phone = user
                    user_ids.append(user_id)
                    found_users.append({
                        'id': user_id,
                        'name': f"{fname} {lname}",
                        'email': email,
                        'phone': phone
                    })
                    print(f"  ✓ Found: {fname} {lname} ({email}, {phone})")
            
            if not user_ids:
                print("\n✗ No users found matching the criteria!")
                return 0
            
            print(f"\n  Total users found: {len(user_ids)}")
            
            # Get statistics before deletion
            print("\n4. Collecting statistics...")
            
            # Count loans
            cursor.execute("""
                SELECT COUNT(*) FROM loans WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            loan_count = cursor.fetchone()[0]
            
            # Count applications
            cursor.execute("""
                SELECT COUNT(*) FROM loan_applications WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            app_count = cursor.fetchone()[0]
            
            # Count repayments
            cursor.execute("""
                SELECT COUNT(*) FROM repayments 
                WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
            """, (tuple(user_ids),))
            repay_count = cursor.fetchone()[0]
            
            # Count rollover requests
            cursor.execute("""
                SELECT COUNT(*) FROM rollover_requests WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            rollover_count = cursor.fetchone()[0]
            
            print(f"  Loans: {loan_count}")
            print(f"  Applications: {app_count}")
            print(f"  Repayments: {repay_count}")
            print(f"  Rollover Requests: {rollover_count}")
            
            # Start deletion process
            print("\n5. Starting deletion process...")
            
            # Delete in correct order to respect foreign key constraints
            
            # 5.1 Delete mpesa_transactions (references repayments)
            print(f"\n  5.1 Deleting M-Pesa transactions...")
            cursor.execute("""
                DELETE FROM mpesa_transactions 
                WHERE repayment_id IN (
                    SELECT id FROM repayments 
                    WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
                )
            """, (tuple(user_ids),))
            deleted_mpesa = cursor.rowcount
            print(f"      ✓ Deleted {deleted_mpesa} M-Pesa transactions")
            
            # 5.2 Delete repayments
            print(f"\n  5.2 Deleting repayments...")
            cursor.execute("""
                DELETE FROM repayments 
                WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
            """, (tuple(user_ids),))
            deleted_repay = cursor.rowcount
            print(f"      ✓ Deleted {deleted_repay} repayments")
            
            # 5.3 Delete penalties (if table exists)
            print(f"\n  5.3 Deleting penalties...")
            try:
                cursor.execute("""
                    DELETE FROM penalties 
                    WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
                """, (tuple(user_ids),))
                deleted_penalties = cursor.rowcount
                print(f"      ✓ Deleted {deleted_penalties} penalties")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_penalties = 0
                    print(f"      ⊘ Penalties table doesn't exist (skipped)")
                else:
                    raise
            
            # 5.4 Delete rollover requests
            print(f"\n  5.4 Deleting rollover requests...")
            cursor.execute("""
                DELETE FROM rollover_requests WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            deleted_rollover = cursor.rowcount
            print(f"      ✓ Deleted {deleted_rollover} rollover requests")
            
            # 5.5 Delete general ledger entries (if table exists)
            print(f"\n  5.5 Deleting general ledger entries...")
            try:
                cursor.execute("""
                    DELETE FROM accounting_general_ledger 
                    WHERE journal_entry_id IN (
                        SELECT id FROM accounting_journal_entries 
                        WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
                    )
                """, (tuple(user_ids),))
                deleted_ledger = cursor.rowcount
                print(f"      ✓ Deleted {deleted_ledger} general ledger entries")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_ledger = 0
                    print(f"      ⊘ General ledger table doesn't exist (skipped)")
                else:
                    raise
            
            # 5.6 Delete journal entry lines (if table exists)
            print(f"\n  5.6 Deleting journal entry lines...")
            try:
                cursor.execute("""
                    DELETE FROM accounting_journal_entry_lines 
                    WHERE journal_entry_id IN (
                        SELECT id FROM accounting_journal_entries 
                        WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
                    )
                """, (tuple(user_ids),))
                deleted_lines = cursor.rowcount
                print(f"      ✓ Deleted {deleted_lines} journal entry lines")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_lines = 0
                    print(f"      ⊘ Journal entry lines table doesn't exist (skipped)")
                else:
                    raise
            
            # 5.7 Delete accounting journal entries (if table exists)
            print(f"\n  5.7 Deleting accounting journal entries...")
            try:
                cursor.execute("""
                    DELETE FROM accounting_journal_entries 
                    WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id IN %s)
                """, (tuple(user_ids),))
                deleted_journal = cursor.rowcount
                print(f"      ✓ Deleted {deleted_journal} journal entries")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_journal = 0
                    print(f"      ⊘ Accounting journal entries table doesn't exist (skipped)")
                else:
                    raise
            
            # 5.8 Delete loans
            print(f"\n  5.8 Deleting loans...")
            cursor.execute("""
                DELETE FROM loans WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            deleted_loans = cursor.rowcount
            print(f"      ✓ Deleted {deleted_loans} loans")
            
            # 5.9 Delete loan applications
            print(f"\n  5.9 Deleting loan applications...")
            cursor.execute("""
                DELETE FROM loan_applications WHERE borrower_id IN %s
            """, (tuple(user_ids),))
            deleted_apps = cursor.rowcount
            print(f"      ✓ Deleted {deleted_apps} applications")
            
            # 5.10 Delete collateral records (if table exists)
            print(f"\n  5.10 Deleting collateral records...")
            try:
                # First check the actual column name in collateral table
                cursor.execute("DESCRIBE collateral")
                collateral_columns = [col[0] for col in cursor.fetchall()]
                
                # Determine the correct foreign key column name
                fk_column = None
                for col in collateral_columns:
                    if 'application' in col.lower() or 'loan' in col.lower():
                        fk_column = col
                        break
                
                if fk_column:
                    cursor.execute(f"""
                        DELETE FROM collateral 
                        WHERE {fk_column} IN (
                            SELECT id FROM loan_applications WHERE borrower_id IN %s
                        )
                    """, (tuple(user_ids),))
                    deleted_collateral = cursor.rowcount
                    print(f"      ✓ Deleted {deleted_collateral} collateral records (using {fk_column})")
                else:
                    # No clear FK column found, skip
                    deleted_collateral = 0
                    print(f"      ⊘ Could not determine collateral FK column (skipped)")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_collateral = 0
                    print(f"      ⊘ Collateral table doesn't exist (skipped)")
                else:
                    raise
            except Exception as e:
                # Any other error with collateral, just skip it
                deleted_collateral = 0
                print(f"      ⊘ Collateral deletion error (skipped): {str(e)[:50]}")
            
            # 5.11 Delete guarantors (if table exists)
            print(f"\n  5.11 Deleting guarantor records...")
            try:
                cursor.execute("""
                    DELETE FROM guarantors WHERE borrower_id IN %s
                """, (tuple(user_ids),))
                deleted_guarantors = cursor.rowcount
                print(f"      ✓ Deleted {deleted_guarantors} guarantor records")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):  # Table doesn't exist
                    deleted_guarantors = 0
                    print(f"      ⊘ Guarantors table doesn't exist (skipped)")
                else:
                    raise
            except Exception as e:
                # Any other error with guarantors, just skip it
                deleted_guarantors = 0
                print(f"      ⊘ Guarantors deletion error (skipped): {str(e)[:50]}")
            
            # 5.12 Delete user sessions
            print(f"\n  5.12 Deleting user sessions...")
            cursor.execute("""
                DELETE FROM django_session 
                WHERE session_data LIKE %s
            """, (f'%{user_ids[0]}%',))
            deleted_sessions = cursor.rowcount
            print(f"      ✓ Deleted {deleted_sessions} sessions")
            
            # 5.13 Finally, delete the users themselves
            print(f"\n  5.13 Deleting users...")
            cursor.execute(f"""
                DELETE FROM {user_table} WHERE id IN %s
            """, (tuple(user_ids),))
            deleted_users = cursor.rowcount
            print(f"      ✓ Deleted {deleted_users} users")
            
            # Commit all changes
            connection.commit()
            
            print("\n" + "="*80)
            print("✓✓✓ DELETION COMPLETED SUCCESSFULLY! ✓✓✓")
            print("="*80)
            
            print("\n📊 Deletion Summary:")
            print(f"  Users deleted: {deleted_users}")
            print(f"  Loans deleted: {deleted_loans}")
            print(f"  Applications deleted: {deleted_apps}")
            print(f"  Repayments deleted: {deleted_repay}")
            print(f"  M-Pesa transactions deleted: {deleted_mpesa}")
            print(f"  Rollover requests deleted: {deleted_rollover}")
            print(f"  General ledger entries deleted: {deleted_ledger}")
            print(f"  Journal entry lines deleted: {deleted_lines}")
            print(f"  Journal entries deleted: {deleted_journal}")
            print(f"  Penalties deleted: {deleted_penalties}")
            print(f"  Collateral deleted: {deleted_collateral}")
            print(f"  Guarantors deleted: {deleted_guarantors}")
            print(f"  Sessions deleted: {deleted_sessions}")
            
            print("\n✅ The following users have been permanently deleted:")
            for user in found_users:
                print(f"  - {user['name']} ({user['email']}, {user['phone']})")
            
            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 DELETE privileges")
        return 1
        
    except Exception as e:
        print(f"\n✗ ERROR: {e}")
        import traceback
        traceback.print_exc()
        if connection:
            connection.rollback()
            print("\n⚠️  Transaction rolled back - no data was deleted")
        return 1
        
    finally:
        if connection:
            connection.close()
            print("Database connection closed.")

if __name__ == '__main__':
    print("\n⚠️  FINAL WARNING ⚠️")
    print("This script will permanently delete users and all their data.")
    print("This action CANNOT be undone!")
    print("\nPress Ctrl+C now to cancel, or wait 5 seconds to proceed...")
    
    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.")
        sys.exit(0)
    
    sys.exit(main())
