#!/usr/bin/env python3
"""
Delete Teresiah Wambui Karanja and all her loans, repayments, and related data.
CAUTION: This is irreversible!
"""
import pymysql
import sys
import time

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

# User to delete
USER_TO_DELETE = {
    'first_name': 'Teresiah',
    'last_name': 'Karanja',
    'phone': '+254722909678',
    'email': 'teresiah@gmail.com'
}

def main():
    print("\n" + "="*80)
    print("DELETE USER AND ALL RELATED DATA - PRODUCTION")
    print("="*80)
    print("\n⚠️  WARNING: This will permanently delete:")
    print(f"   - User: Teresiah Wambui Karanja")
    print(f"   - Phone: +254722909678")
    print(f"   - Email: teresiah@gmail.com")
    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:
            # Find the user
            print("\n2. Finding user...")
            cursor.execute("""
                SELECT id, username, first_name, last_name, email, phone_number
                FROM users
                WHERE first_name LIKE %s
                AND last_name LIKE %s
                AND phone_number = %s
                AND role = 'borrower'
            """, (
                f"%{USER_TO_DELETE['first_name']}%",
                f"%{USER_TO_DELETE['last_name']}%",
                USER_TO_DELETE['phone']
            ))
            
            user = cursor.fetchone()
            
            if not user:
                print(f"✗ User not found!")
                return 0
            
            user_id = user[0]
            username = user[1]
            full_name = f"{user[2]} {user[3]}"
            email = user[4]
            phone = user[5]
            
            print(f"✓ Found user:")
            print(f"  ID: {user_id}")
            print(f"  Name: {full_name}")
            print(f"  Email: {email}")
            print(f"  Phone: {phone}")
            
            # Get statistics
            print("\n3. Collecting statistics...")
            
            # Count loans
            cursor.execute("""
                SELECT COUNT(*) FROM loans WHERE borrower_id = %s
            """, (user_id,))
            loan_count = cursor.fetchone()[0]
            
            # Count applications
            cursor.execute("""
                SELECT COUNT(*) FROM loan_applications WHERE borrower_id = %s
            """, (user_id,))
            app_count = cursor.fetchone()[0]
            
            # Count repayments
            cursor.execute("""
                SELECT COUNT(*) FROM repayments 
                WHERE loan_id IN (SELECT id FROM loans WHERE borrower_id = %s)
            """, (user_id,))
            repay_count = cursor.fetchone()[0]
            
            # Count rollover requests
            cursor.execute("""
                SELECT COUNT(*) FROM rollover_requests WHERE borrower_id = %s
            """, (user_id,))
            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}")
            
            # Get loan IDs for deletion
            cursor.execute("""
                SELECT id FROM loans WHERE borrower_id = %s
            """, (user_id,))
            loan_ids = [row[0] for row in cursor.fetchall()]
            
            if not loan_ids:
                print("\n  No loans found for this user")
                loan_ids = [None]  # Dummy value to avoid SQL errors
            
            # 5-second countdown
            print("\n" + "="*80)
            print("⚠️  FINAL WARNING ⚠️")
            print("="*80)
            print("Press Ctrl+C now to cancel, or wait 5 seconds to proceed...\n")
            
            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
            
            # Start deletion
            print("🚀 Starting deletion...")
            print("="*80)
            
            # Begin transaction
            connection.begin()
            
            try:
                # Delete in correct order to respect foreign key constraints
                
                # 1. Delete M-Pesa transactions
                print("\n  1. Deleting M-Pesa transactions...")
                if loan_ids[0]:
                    cursor.execute("""
                        DELETE FROM mpesa_transactions 
                        WHERE repayment_id IN (
                            SELECT id FROM repayments WHERE loan_id IN %s
                        )
                    """, (tuple(loan_ids),))
                    print(f"      ✓ Deleted {cursor.rowcount} M-Pesa transactions")
                
                # 2. Delete repayments
                print("\n  2. Deleting repayments...")
                if loan_ids[0]:
                    cursor.execute("""
                        DELETE FROM repayments WHERE loan_id IN %s
                    """, (tuple(loan_ids),))
                    print(f"      ✓ Deleted {cursor.rowcount} repayments")
                
                # 3. Delete receipts
                print("\n  3. Deleting receipts...")
                if loan_ids[0]:
                    cursor.execute("""
                        DELETE FROM receipts WHERE loan_id IN %s
                    """, (tuple(loan_ids),))
                    print(f"      ✓ Deleted {cursor.rowcount} receipts")
                
                # 4. Delete penalties (if table exists)
                print("\n  4. Deleting penalties...")
                try:
                    if loan_ids[0]:
                        cursor.execute("""
                            DELETE FROM penalties WHERE loan_id IN %s
                        """, (tuple(loan_ids),))
                        print(f"      ✓ Deleted {cursor.rowcount} penalties")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ Penalties table doesn't exist (skipped)")
                    else:
                        raise
                
                # 5. Delete rollover requests
                print("\n  5. Deleting rollover requests...")
                cursor.execute("""
                    DELETE FROM rollover_requests WHERE borrower_id = %s
                """, (user_id,))
                print(f"      ✓ Deleted {cursor.rowcount} rollover requests")
                
                # 6. Delete general ledger entries
                print("\n  6. Deleting general ledger entries...")
                try:
                    if loan_ids[0]:
                        cursor.execute("""
                            DELETE FROM accounting_general_ledger 
                            WHERE journal_entry_id IN (
                                SELECT id FROM accounting_journal_entries 
                                WHERE loan_id IN %s
                            )
                        """, (tuple(loan_ids),))
                        print(f"      ✓ Deleted {cursor.rowcount} general ledger entries")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ General ledger table doesn't exist (skipped)")
                    else:
                        raise
                
                # 7. Delete journal entry lines
                print("\n  7. Deleting journal entry lines...")
                try:
                    if loan_ids[0]:
                        cursor.execute("""
                            DELETE FROM accounting_journal_entry_lines 
                            WHERE journal_entry_id IN (
                                SELECT id FROM accounting_journal_entries 
                                WHERE loan_id IN %s
                            )
                        """, (tuple(loan_ids),))
                        print(f"      ✓ Deleted {cursor.rowcount} journal entry lines")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ Journal entry lines table doesn't exist (skipped)")
                    else:
                        raise
                
                # 8. Delete accounting journal entries
                print("\n  8. Deleting accounting journal entries...")
                try:
                    if loan_ids[0]:
                        cursor.execute("""
                            DELETE FROM accounting_journal_entries 
                            WHERE loan_id IN %s
                        """, (tuple(loan_ids),))
                        print(f"      ✓ Deleted {cursor.rowcount} journal entries")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ Accounting journal entries table doesn't exist (skipped)")
                    else:
                        raise
                
                # 9. Delete loans
                print("\n  9. Deleting loans...")
                if loan_ids[0]:
                    cursor.execute("""
                        DELETE FROM loans WHERE borrower_id = %s
                    """, (user_id,))
                    print(f"      ✓ Deleted {cursor.rowcount} loans")
                
                # 10. Delete loan applications
                print("\n  10. Deleting loan applications...")
                cursor.execute("""
                    DELETE FROM loan_applications WHERE borrower_id = %s
                """, (user_id,))
                print(f"      ✓ Deleted {cursor.rowcount} applications")
                
                # 11. Delete collateral (if table exists)
                print("\n  11. Deleting collateral records...")
                try:
                    # Collateral is linked to loan_applications, not directly to borrower
                    cursor.execute("""
                        DELETE FROM collateral 
                        WHERE loan_application_id IN (
                            SELECT id FROM loan_applications WHERE borrower_id = %s
                        )
                    """, (user_id,))
                    print(f"      ✓ Deleted {cursor.rowcount} collateral records")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ Collateral table doesn't exist (skipped)")
                    else:
                        raise
                except pymysql.err.OperationalError as e:
                    # Handle case where column names might be different
                    print(f"      ⊘ Collateral deletion skipped: {str(e)[:80]}")
                
                # 12. Delete guarantors (if table exists)
                print("\n  12. Deleting guarantor records...")
                try:
                    # Try deleting by borrower_id or loan_id depending on table structure
                    cursor.execute("""
                        DELETE FROM guarantors WHERE borrower_id = %s
                    """, (user_id,))
                    print(f"      ✓ Deleted {cursor.rowcount} guarantor records")
                except pymysql.err.ProgrammingError as e:
                    if '1146' in str(e):
                        print(f"      ⊘ Guarantors table doesn't exist (skipped)")
                    else:
                        raise
                except pymysql.err.OperationalError as e:
                    # Try alternative approach if column doesn't exist
                    try:
                        if loan_ids[0]:
                            cursor.execute("""
                                DELETE FROM guarantors WHERE loan_id IN %s
                            """, (tuple(loan_ids),))
                            print(f"      ✓ Deleted {cursor.rowcount} guarantor records (by loan_id)")
                    except:
                        print(f"      ⊘ Guarantors deletion skipped: {str(e)[:80]}")
                
                # 13. Delete user sessions
                print("\n  13. Deleting user sessions...")
                cursor.execute("""
                    DELETE FROM django_session 
                    WHERE session_data LIKE %s
                """, (f'%{user_id}%',))
                print(f"      ✓ Deleted {cursor.rowcount} sessions")
                
                # 14. Finally, delete the user
                print("\n  14. Deleting user...")
                cursor.execute("""
                    DELETE FROM users WHERE id = %s
                """, (user_id,))
                print(f"      ✓ Deleted user")
                
                # Commit all changes
                connection.commit()
                
                print("\n" + "="*80)
                print("✓✓✓ DELETION COMPLETED SUCCESSFULLY! ✓✓✓")
                print("="*80)
                
                print(f"\n✅ User {full_name} and all related data permanently deleted")
                print("\n" + "="*80 + "\n")
                
                return 0
                
            except Exception as e:
                connection.rollback()
                print(f"\n✗ ERROR: {e}")
                print("\n⚠️  Transaction rolled back - no data was deleted")
                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("Database connection closed.")

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