#!/usr/bin/env python
"""
Delete All Borrowers - Direct Database Connection
==================================================

This script deletes ONLY borrower users from the database.
Admin and staff users are PRESERVED.

⚠️  WARNING: This is separate from the loan deletion script!

WHAT GETS DELETED:
- All borrower users (is_staff=0 AND is_superuser=0)
- Authentication tokens for deleted borrowers
- User sessions for deleted borrowers (skipped, will expire naturally)
- User permissions for deleted borrowers
- User group memberships for deleted borrowers

WHAT GETS PRESERVED:
- ✅ All admin users (is_superuser=1)
- ✅ All staff users (is_staff=1)
- ✅ Admin authentication and sessions
- ✅ Staff authentication and sessions

This script does NOT delete:
- Loans (use delete_all_loans_direct.py for that)
- Expenses
- Products
- Branches
- System settings

WARNING: THIS CANNOT BE UNDONE!
Make sure you have a database backup before running this script.

Usage:
    python delete_all_borrowers.py

"""

import pymysql
import sys
from datetime import datetime
import time

# Database connection details
DB = dict(
    host='localhost',
    port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

# Hardcoded confirmation - change this to run the script
CONFIRMATION_CODE = "DELETE_ALL_BORROWERS_2026"
ENTERED_CODE = "DELETE_ALL_BORROWERS_2026"  # ← Match this to confirm


def print_header():
    """Print script header"""
    print("="*80)
    print(" DELETE ALL BORROWERS (PRESERVE ADMIN/STAFF)")
    print(" " + "="*78)
    print(" This script will delete borrower users only")
    print("="*80)


def print_warning():
    """Print critical warning"""
    print("\n" + "="*80)
    print(" ⚠️  CRITICAL WARNING ⚠️")
    print("="*80)
    print("\n🔴 This script will DELETE ONLY BORROWER USERS!")
    print("\nWhat will be DELETED:")
    print("  ❌ All borrower users (user_type = 'borrower')")
    print("  ❌ Borrower authentication tokens")
    print("  ❌ Borrower user sessions")
    print("  ❌ Borrower user permissions")
    print("  ❌ Borrower user group memberships")
    print("\nWhat will be PRESERVED:")
    print("  ✅ All admin users")
    print("  ✅ All staff users")
    print("  ✅ Admin/staff authentication")
    print("  ✅ Admin/staff sessions")
    print("  ✅ You will retain access to the system")
    print("\n⚠️  THIS CANNOT BE UNDONE! ⚠️")
    print("\n✅ MAKE SURE YOU HAVE A DATABASE BACKUP!")
    print("\nBackup command:")
    print(f"  mysqldump -u {DB['user']} -p {DB['database']} > backup_before_delete_borrowers_$(date +%Y%m%d_%H%M%S).sql")


def check_confirmation():
    """Check hardcoded confirmation code"""
    print("\n" + "="*80)
    print(" CONFIRMATION CHECK")
    print("="*80)
    
    if ENTERED_CODE == CONFIRMATION_CODE:
        print("✅ Confirmation code verified")
        return True
    else:
        print("❌ ERROR: Confirmation code does not match!")
        print(f"   Expected: '{CONFIRMATION_CODE}'")
        print(f"   Got:      '{ENTERED_CODE}'")
        print("\nTo run this script, edit the ENTERED_CODE variable to match CONFIRMATION_CODE")
        return False


def get_connection():
    """Create database connection"""
    try:
        connection = pymysql.connect(**DB)
        return connection
    except Exception as e:
        print(f"❌ Failed to connect to database: {e}")
        sys.exit(1)


def get_table_count(cursor, table_name, where_clause=""):
    """Get count of rows in a table"""
    try:
        sql = f"SELECT COUNT(*) as count FROM {table_name}"
        if where_clause:
            sql += f" WHERE {where_clause}"
        
        cursor.execute(sql)
        result = cursor.fetchone()
        return (result['count'], None)
    except Exception as e:
        return (0, str(e))


def show_current_counts(connection):
    """Show current data counts before deletion"""
    print("\n" + "="*80)
    print(" CURRENT DATABASE COUNTS")
    print("="*80)
    
    with connection.cursor() as cursor:
        # Total users
        count, _ = get_table_count(cursor, 'users', '')
        print(f"  📊 Total Users                               {count:>7,}")
        
        # Break down by user type
        try:
            # Check by is_staff and is_superuser
            cursor.execute("""
                SELECT 
                    CASE 
                        WHEN is_superuser = 1 THEN 'Superuser/Admin'
                        WHEN is_staff = 1 THEN 'Staff'
                        ELSE 'Borrower'
                    END as user_type,
                    COUNT(*) as count 
                FROM users 
                GROUP BY user_type
            """)
            user_types = cursor.fetchall()
            for row in user_types:
                user_type = row['user_type']
                count = row['count']
                if user_type == 'Borrower':
                    print(f"     ❌ {user_type:<35} {count:>7,}  ← WILL BE DELETED")
                else:
                    print(f"     ✅ {user_type:<35} {count:>7,}  ← WILL BE KEPT")
        except:
            pass
        
        # Borrowers only (what will be deleted)
        count, _ = get_table_count(cursor, 'users', "is_staff = 0 AND is_superuser = 0")
        print(f"\n  ❌ BORROWERS TO DELETE                       {count:>7,}")
        
        # Admin/Staff (what will be preserved)
        count, _ = get_table_count(cursor, 'users', "is_staff = 1 OR is_superuser = 1")
        print(f"  ✅ ADMIN/STAFF TO KEEP                       {count:>7,}")
        
        # Other user-related tables
        count, _ = get_table_count(cursor, 'authtoken_token', '')
        print(f"\n  📊 Total Authentication Tokens               {count:>7,}")
        
        count, _ = get_table_count(cursor, 'django_session', '')
        print(f"  📊 Total User Sessions                       {count:>7,}")


def delete_table_data(cursor, table_name, description, where_clause=""):
    """Delete data from a table, handling cases where table doesn't exist"""
    try:
        sql = f"DELETE FROM {table_name}"
        if where_clause:
            sql += f" WHERE {where_clause}"
        
        cursor.execute(sql)
        count = cursor.rowcount
        print(f"   ✅ Deleted {count:,} {description}")
        return count
    except Exception as e:
        if "doesn't exist" in str(e) or "1146" in str(e):
            print(f"   ⚠️  Table '{table_name}' doesn't exist - skipping")
            return 0
        else:
            print(f"   ❌ Error deleting from '{table_name}': {e}")
            raise


def delete_all_users(connection):
    """Delete all borrower users and related data from the database (preserve admin/staff)"""
    print("\n" + "="*80)
    print(" DELETING BORROWER USERS ONLY")
    print("="*80)
    
    deleted_counts = {}
    
    try:
        with connection.cursor() as cursor:
            
            # First, get the IDs of borrower users to delete
            # Borrowers are users where is_staff=0 AND is_superuser=0
            print("\n🔍 Finding borrower user IDs...")
            cursor.execute("SELECT id FROM users WHERE is_staff = 0 AND is_superuser = 0")
            borrower_ids = [row['id'] for row in cursor.fetchall()]
            
            if not borrower_ids:
                print("   ℹ️  No borrowers found to delete")
                return deleted_counts
            
            print(f"   Found {len(borrower_ids)} borrowers to delete")
            
            # Create placeholders for SQL IN clause
            id_placeholders = ','.join(['%s'] * len(borrower_ids))
            
            # Disable foreign key checks temporarily
            print("\n🔓 Disabling foreign key checks...")
            cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
            
            # Delete in dependency order - only for borrower users
            
            # 1. Authentication tokens for borrowers only
            print("\n1️⃣  Deleting borrower authentication tokens...")
            try:
                sql = f"DELETE FROM authtoken_token WHERE user_id IN ({id_placeholders})"
                cursor.execute(sql, borrower_ids)
                deleted_counts['auth_tokens'] = cursor.rowcount
                print(f"   ✅ Deleted {cursor.rowcount:,} authentication tokens")
            except Exception as e:
                if "doesn't exist" in str(e) or "1146" in str(e):
                    print(f"   ⚠️  Table 'authtoken_token' doesn't exist - skipping")
                    deleted_counts['auth_tokens'] = 0
                else:
                    raise
            
            # 2. User sessions - harder to filter, so we skip this
            print("\n2️⃣  Skipping user sessions (will expire naturally)...")
            deleted_counts['sessions'] = 0
            
            # 3. User permissions for borrowers only
            print("\n3️⃣  Deleting borrower user permissions...")
            try:
                sql = f"DELETE FROM users_user_user_permissions WHERE user_id IN ({id_placeholders})"
                cursor.execute(sql, borrower_ids)
                deleted_counts['user_permissions'] = cursor.rowcount
                print(f"   ✅ Deleted {cursor.rowcount:,} user permissions")
            except Exception as e:
                if "doesn't exist" in str(e) or "1146" in str(e):
                    print(f"   ⚠️  Table 'users_user_user_permissions' doesn't exist - skipping")
                    deleted_counts['user_permissions'] = 0
                else:
                    raise
            
            # 4. User groups for borrowers only
            print("\n4️⃣  Deleting borrower user group memberships...")
            try:
                sql = f"DELETE FROM users_user_groups WHERE user_id IN ({id_placeholders})"
                cursor.execute(sql, borrower_ids)
                deleted_counts['user_groups'] = cursor.rowcount
                print(f"   ✅ Deleted {cursor.rowcount:,} user group memberships")
            except Exception as e:
                if "doesn't exist" in str(e) or "1146" in str(e):
                    print(f"   ⚠️  Table 'users_user_groups' doesn't exist - skipping")
                    deleted_counts['user_groups'] = 0
                else:
                    raise
            
            # 5. Borrower users (main table) - ONLY borrowers (non-staff, non-superuser)
            print("\n5️⃣  Deleting borrower users...")
            cursor.execute("DELETE FROM users WHERE is_staff = 0 AND is_superuser = 0")
            deleted_counts['users'] = cursor.rowcount
            print(f"   ✅ Deleted {cursor.rowcount:,} borrower users")
            
            # Re-enable foreign key checks
            print("\n🔒 Re-enabling foreign key checks...")
            cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
            
            # Commit the transaction
            connection.commit()
        
        return deleted_counts
        
    except Exception as e:
        connection.rollback()
        print(f"\n❌ Error during deletion: {e}")
        import traceback
        traceback.print_exc()
        raise


def show_summary(deleted_counts):
    """Show deletion summary"""
    print("\n" + "="*80)
    print(" DELETION COMPLETE")
    print("="*80)
    
    total = sum(deleted_counts.values())
    
    print(f"\n✅ Successfully deleted {total:,} total records")
    print("\nBreakdown:")
    for key, count in deleted_counts.items():
        print(f"  - {key.replace('_', ' ').title():<30} {count:>7,}")
    
    print("\n" + "="*80)
    print(" ✅ ADMIN/STAFF USERS PRESERVED")
    print("="*80)
    print("\nYou should still be able to log in with your admin credentials.")
    print("\nNext steps:")
    print("  1. Verify you can log in: https://grazuri.uzuriapps.xyz/accounts/login/")
    print("  2. Check that borrowers are gone: https://grazuri.uzuriapps.xyz/clients/")
    print("  3. Start adding new borrowers manually if needed")


def main():
    """Main execution function"""
    connection = None
    
    try:
        print_header()
        print_warning()
        
        # Check confirmation
        if not check_confirmation():
            return False
        
        # Connect to database
        print("\n🔌 Connecting to database...")
        connection = get_connection()
        print(f"✅ Connected to database: {DB['database']}@{DB['host']}")
        
        # Show current counts
        show_current_counts(connection)
        
        # Final warning with countdown
        print("\n" + "="*80)
        print(" FINAL WARNING")
        print("="*80)
        print("\n🔴 The script will now DELETE BORROWER USERS in 3 seconds...")
        print("⚠️  Admin and staff users will be PRESERVED")
        print("\nPress Ctrl+C NOW to cancel!")
        
        for i in range(3, 0, -1):
            print(f"  Deleting in {i}...")
            time.sleep(1)
        
        # Delete all users
        deleted_counts = delete_all_users(connection)
        
        # Show summary
        show_summary(deleted_counts)
        
        print("\n✅ Script completed successfully!")
        return True
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Script cancelled by user")
        print("No data was deleted.")
        if connection:
            connection.rollback()
        return False
    except Exception as e:
        print(f"\n❌ Script failed with error: {e}")
        import traceback
        traceback.print_exc()
        if connection:
            connection.rollback()
        return False
    finally:
        if connection:
            connection.close()
            print("\n🔌 Database connection closed")


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
