#!/usr/bin/env python3
"""
Delete specific test loans by loan number 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'
}

# Loan numbers to delete
LOAN_NUMBERS_TO_DELETE = [
    '20112026-000002',  # test user - Log Book Loan - KES 55,000
    '16112026-000005',  # Stanley Nduati - Biashara Loan - KES 83,850
    '16112026-000006',  # test user - Log Book Loan - KES 51,000
]

def main():
    print("\n" + "="*80)
    print("DELETE SPECIFIC TEST LOANS - PRODUCTION")
    print("="*80)
    print("\n⚠️  WARNING: This will permanently delete the following loans:")
    print("   - 20112026-000002 (test user - Log Book Loan - KES 55,000)")
    print("   - 16112026-000005 (Stanley Nduati - Biashara Loan - KES 83,850)")
    print("   - 16112026-000006 (test user - Log Book Loan - KES 51,000)")
    print("   - ALL related repayments, accounting entries, and rollover requests")
    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 loans by loan number
            print("\n2. Finding loans to delete...")
            loan_ids = []
            found_loans = []
            
            for loan_number in LOAN_NUMBERS_TO_DELETE:
                cursor.execute("""
                    SELECT l.id, l.loan_number, l.total_amount, 
                           u.first_name, u.last_name, u.phone_number
                    FROM loans l
                    JOIN users u ON l.borrower_id = u.id
                    WHERE l.loan_number = %s
                """, (loan_number,))
                
                loan = cursor.fetchone()
                if loan:
                    loan_id, ln, total_amount, fname, lname, phone = loan
                    loan_ids.append(loan_id)
                    found_loans.append({
                        'id': loan_id,
                        'number': ln,
                        'amount': total_amount,
                        'borrower': f"{fname} {lname}",
                        'phone': phone
                    })
                    print(f"  ✓ Found: {ln} - {fname} {lname} ({phone}) - KES {total_amount:,.2f}")
                else:
                    print(f"  ✗ Not found: {loan_number}")
            
            if not loan_ids:
                print("\n✗ No loans found matching the criteria!")
                return 0
            
            print(f"\n  Total loans found: {len(loan_ids)}")
            
            # Get statistics before deletion
            print("\n3. Collecting statistics...")
            
            # Count repayments
            cursor.execute("""
                SELECT COUNT(*) FROM repayments WHERE loan_id IN %s
            """, (tuple(loan_ids),))
            repay_count = cursor.fetchone()[0]
            
            # Count M-Pesa transactions
            cursor.execute("""
                SELECT COUNT(*) FROM mpesa_transactions 
                WHERE repayment_id IN (SELECT id FROM repayments WHERE loan_id IN %s)
            """, (tuple(loan_ids),))
            mpesa_count = cursor.fetchone()[0]
            
            # Count rollover requests
            cursor.execute("""
                SELECT COUNT(*) FROM rollover_requests WHERE loan_id IN %s
            """, (tuple(loan_ids),))
            rollover_count = cursor.fetchone()[0]
            
            # Count journal entries
            cursor.execute("""
                SELECT COUNT(*) FROM accounting_journal_entries WHERE loan_id IN %s
            """, (tuple(loan_ids),))
            journal_count = cursor.fetchone()[0]
            
            print(f"  Repayments: {repay_count}")
            print(f"  M-Pesa Transactions: {mpesa_count}")
            print(f"  Rollover Requests: {rollover_count}")
            print(f"  Journal Entries: {journal_count}")
            
            # Start deletion process
            print("\n4. Starting deletion process...")
            
            # 4.1 Delete M-Pesa transactions (references repayments)
            print(f"\n  4.1 Deleting M-Pesa transactions...")
            cursor.execute("""
                DELETE FROM mpesa_transactions 
                WHERE repayment_id IN (SELECT id FROM repayments WHERE loan_id IN %s)
            """, (tuple(loan_ids),))
            deleted_mpesa = cursor.rowcount
            print(f"      ✓ Deleted {deleted_mpesa} M-Pesa transactions")
            
            # 4.2 Delete repayments
            print(f"\n  4.2 Deleting repayments...")
            cursor.execute("""
                DELETE FROM repayments WHERE loan_id IN %s
            """, (tuple(loan_ids),))
            deleted_repay = cursor.rowcount
            print(f"      ✓ Deleted {deleted_repay} repayments")
            
            # 4.3 Delete penalties (if any)
            print(f"\n  4.3 Deleting penalties...")
            try:
                cursor.execute("""
                    DELETE FROM penalties WHERE loan_id IN %s
                """, (tuple(loan_ids),))
                deleted_penalties = cursor.rowcount
                print(f"      ✓ Deleted {deleted_penalties} penalties")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):
                    deleted_penalties = 0
                    print(f"      ⊘ Penalties table doesn't exist (skipped)")
                else:
                    raise
            
            # 4.4 Delete general ledger entries
            print(f"\n  4.4 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 %s
                    )
                """, (tuple(loan_ids),))
                deleted_ledger = cursor.rowcount
                print(f"      ✓ Deleted {deleted_ledger} general ledger entries")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):
                    deleted_ledger = 0
                    print(f"      ⊘ General ledger table doesn't exist (skipped)")
                else:
                    raise
            
            # 4.5 Delete journal entry lines
            print(f"\n  4.5 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 %s
                    )
                """, (tuple(loan_ids),))
                deleted_lines = cursor.rowcount
                print(f"      ✓ Deleted {deleted_lines} journal entry lines")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):
                    deleted_lines = 0
                    print(f"      ⊘ Journal entry lines table doesn't exist (skipped)")
                else:
                    raise
            
            # 4.6 Delete accounting journal entries
            print(f"\n  4.6 Deleting accounting journal entries...")
            try:
                cursor.execute("""
                    DELETE FROM accounting_journal_entries WHERE loan_id IN %s
                """, (tuple(loan_ids),))
                deleted_journal = cursor.rowcount
                print(f"      ✓ Deleted {deleted_journal} journal entries")
            except pymysql.err.ProgrammingError as e:
                if '1146' in str(e):
                    deleted_journal = 0
                    print(f"      ⊘ Journal entries table doesn't exist (skipped)")
                else:
                    raise
            
            # 4.7 Delete rollover requests where these loans are referenced
            print(f"\n  4.7 Deleting rollover requests...")
            cursor.execute("""
                DELETE FROM rollover_requests WHERE loan_id IN %s
            """, (tuple(loan_ids),))
            deleted_rollover = cursor.rowcount
            print(f"      ✓ Deleted {deleted_rollover} rollover requests")
            
            # 4.8 Recursively find and delete ALL descendant loans (rollover chains)
            print(f"\n  4.8 Finding all descendant loans (rollover chains)...")
            
            # Use a recursive approach to find all descendants
            all_descendants = []
            current_level = list(loan_ids)
            level = 1
            
            while current_level:
                cursor.execute("""
                    SELECT id, loan_number FROM loans WHERE original_loan_id IN %s
                """, (tuple(current_level),))
                next_level_loans = cursor.fetchall()
                
                if not next_level_loans:
                    break
                
                next_level_ids = [loan[0] for loan in next_level_loans]
                next_level_numbers = [loan[1] for loan in next_level_loans]
                
                print(f"      Level {level}: Found {len(next_level_loans)} loans: {', '.join(next_level_numbers)}")
                all_descendants.extend(next_level_loans)
                current_level = next_level_ids
                level += 1
            
            # Now delete all descendants from bottom to top (reverse order)
            deleted_child_loans = 0
            if all_descendants:
                # Reverse so we delete the deepest children first
                all_descendants.reverse()
                
                for descendant_id, descendant_number in all_descendants:
                    print(f"\n      Deleting descendant loan: {descendant_number}")
                    
                    # Delete M-Pesa transactions
                    cursor.execute("""
                        DELETE FROM mpesa_transactions 
                        WHERE repayment_id IN (SELECT id FROM repayments WHERE loan_id = %s)
                    """, (descendant_id,))
                    
                    # Delete repayments
                    cursor.execute("""
                        DELETE FROM repayments WHERE loan_id = %s
                    """, (descendant_id,))
                    
                    # Delete general ledger
                    try:
                        cursor.execute("""
                            DELETE FROM accounting_general_ledger 
                            WHERE journal_entry_id IN (
                                SELECT id FROM accounting_journal_entries WHERE loan_id = %s
                            )
                        """, (descendant_id,))
                    except pymysql.err.ProgrammingError:
                        pass
                    
                    # Delete 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 = %s
                            )
                        """, (descendant_id,))
                    except pymysql.err.ProgrammingError:
                        pass
                    
                    # Delete journal entries
                    try:
                        cursor.execute("""
                            DELETE FROM accounting_journal_entries WHERE loan_id = %s
                        """, (descendant_id,))
                    except pymysql.err.ProgrammingError:
                        pass
                    
                    # Delete rollover requests
                    cursor.execute("""
                        DELETE FROM rollover_requests WHERE loan_id = %s
                    """, (descendant_id,))
                    
                    # Delete the loan itself
                    cursor.execute("""
                        DELETE FROM loans WHERE id = %s
                    """, (descendant_id,))
                    deleted_child_loans += 1
                
                print(f"\n      ✓ Deleted {deleted_child_loans} descendant loans in total")
            else:
                print(f"      ⊘ No descendant loans found")
            
            # 4.9 Finally, delete the original target loans
            print(f"\n  4.9 Deleting original target loans...")
            cursor.execute("""
                DELETE FROM loans WHERE id IN %s
            """, (tuple(loan_ids),))
            deleted_loans = cursor.rowcount
            print(f"      ✓ Deleted {deleted_loans} loans")
            
            # Commit all changes
            connection.commit()
            
            print("\n" + "="*80)
            print("✓✓✓ DELETION COMPLETED SUCCESSFULLY! ✓✓✓")
            print("="*80)
            
            print("\n📊 Deletion Summary:")
            print(f"  Loans deleted: {deleted_loans}")
            print(f"  Child loans deleted: {deleted_child_loans}")
            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("\n✅ The following loans have been permanently deleted:")
            for loan in found_loans:
                print(f"  - {loan['number']} - {loan['borrower']} ({loan['phone']}) - KES {loan['amount']:,.2f}")
            
            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 loans and all their related 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())
