"""
Delete specific loans in PRODUCTION database:
- Loan 24112026-000048 (Rose Njeri Njuguna)
- Loan 25112026-000004 (test user)

Includes all related data: repayments, receipts, rollover requests, 
penalties, journal entries, mpesa transactions, etc.
"""
import pymysql
from datetime import datetime

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

LOAN_NUMBERS = [
    '24112026-000048',  # Rose Njeri Njuguna
    '25112026-000004',  # test user
]

def delete_loans():
    """Delete specified loans and all related data"""
    
    print("=" * 100)
    print("DELETING LOANS IN PRODUCTION DATABASE")
    print("=" * 100)
    print(f"\n⚠️  Deleting the following loans:")
    for loan_num in LOAN_NUMBERS:
        print(f"  - {loan_num}")
    print()
    
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    try:
        total_deleted = {
            'loans': 0,
            'repayments': 0,
            'receipts': 0,
            'rollover_requests': 0,
            'penalties': 0,
            'journal_entries': 0,
            'journal_entry_lines': 0,
            'mpesa_transactions': 0,
            'applications': 0,
        }
        
        for loan_number in LOAN_NUMBERS:
            print(f"\n{'=' * 100}")
            print(f"Processing Loan: {loan_number}")
            print(f"{'=' * 100}")
            
            # Get loan ID and details
            cursor.execute("""
                SELECT l.id, l.loan_number, l.principal_amount, l.total_amount,
                       b.fname, b.lname, b.phone
                FROM loans l
                LEFT JOIN borrowers b ON l.borrower_id = b.id
                WHERE l.loan_number = %s
            """, (loan_number,))
            
            loan = cursor.fetchone()
            
            if not loan:
                print(f"⚠️  Loan {loan_number} not found")
                continue
            
            loan_id = loan['id']
            borrower_name = f"{loan['fname']} {loan['lname']}" if loan['fname'] else "Unknown"
            
            print(f"\n✓ Found loan: {loan_number}")
            print(f"  Borrower: {borrower_name} ({loan['phone']})")
            print(f"  Principal: KES {loan['principal_amount']:,.2f}")
            print(f"  Total: KES {loan['total_amount']:,.2f}")
            
            # 0. Delete general_ledger entries (must come before journal_entry_lines)
            cursor.execute("""
                DELETE gl FROM accounting_general_ledger gl
                INNER JOIN accounting_journal_entry_lines jel ON gl.journal_entry_line_id = jel.id
                INNER JOIN accounting_journal_entries je ON jel.journal_entry_id = je.id
                WHERE je.loan_id = %s
            """, (loan_id,))
            deleted = cursor.rowcount
            total_deleted['general_ledger'] = total_deleted.get('general_ledger', 0) + deleted
            print(f"  🗑️  Deleted {deleted} general ledger entries")
            
            # 1. Delete journal_entry_lines (must come before journal_entries)
            cursor.execute("""
                DELETE jel FROM accounting_journal_entry_lines jel
                INNER JOIN accounting_journal_entries je ON jel.journal_entry_id = je.id
                WHERE je.loan_id = %s
            """, (loan_id,))
            deleted = cursor.rowcount
            total_deleted['journal_entry_lines'] += deleted
            print(f"  🗑️  Deleted {deleted} journal entry lines")
            
            # 2. Delete journal_entries
            cursor.execute("DELETE FROM accounting_journal_entries WHERE loan_id = %s", (loan_id,))
            deleted = cursor.rowcount
            total_deleted['journal_entries'] += deleted
            print(f"  🗑️  Deleted {deleted} journal entries")
            
            # 3. Delete mpesa_transactions linked to repayments
            cursor.execute("""
                DELETE mt FROM mpesa_transactions mt
                INNER JOIN repayments r ON mt.repayment_id = r.id
                WHERE r.loan_id = %s
            """, (loan_id,))
            deleted = cursor.rowcount
            total_deleted['mpesa_transactions'] += deleted
            print(f"  🗑️  Deleted {deleted} mpesa transactions")
            
            # 4. Delete receipts
            cursor.execute("DELETE FROM receipts WHERE loan_id = %s", (loan_id,))
            deleted = cursor.rowcount
            total_deleted['receipts'] += deleted
            print(f"  🗑️  Deleted {deleted} receipts")
            
            # 5. Delete repayments
            cursor.execute("DELETE FROM repayments WHERE loan_id = %s", (loan_id,))
            deleted = cursor.rowcount
            total_deleted['repayments'] += deleted
            print(f"  🗑️  Deleted {deleted} repayments")
            
            # 6. Delete rollover_requests
            cursor.execute("DELETE FROM rollover_requests WHERE loan_id = %s", (loan_id,))
            deleted = cursor.rowcount
            total_deleted['rollover_requests'] += deleted
            print(f"  🗑️  Deleted {deleted} rollover requests")
            
            # 7. Delete penalties (if table exists)
            try:
                cursor.execute("DELETE FROM penalties WHERE loan_id = %s", (loan_id,))
                deleted = cursor.rowcount
                total_deleted['penalties'] += deleted
                print(f"  🗑️  Deleted {deleted} penalties")
            except pymysql.err.ProgrammingError as e:
                if e.args[0] == 1146:  # Table doesn't exist
                    print(f"  ⚠️  Penalties table doesn't exist - skipped")
                else:
                    raise
            
            # 8. Check for child loans (rollover chain)
            cursor.execute("""
                SELECT id, loan_number FROM loans 
                WHERE original_loan_id = %s
            """, (loan_id,))
            child_loans = cursor.fetchall()
            
            if child_loans:
                print(f"\n  ⚠️  Found {len(child_loans)} child loans (rollover chain)")
                for child in child_loans:
                    print(f"    - {child['loan_number']}")
                    # Recursively delete child loans
                    # Set their original_loan_id to NULL first to avoid FK constraint
                    cursor.execute("""
                        UPDATE loans SET original_loan_id = NULL 
                        WHERE id = %s
                    """, (child['id'],))
            
            # 9. Get application_id before deleting loan
            cursor.execute("SELECT application_id FROM loans WHERE id = %s", (loan_id,))
            app_result = cursor.fetchone()
            application_id = app_result['application_id'] if app_result else None
            
            # 10. Delete the loan itself
            cursor.execute("DELETE FROM loans WHERE id = %s", (loan_id,))
            deleted = cursor.rowcount
            total_deleted['loans'] += deleted
            print(f"  🗑️  Deleted {deleted} loan")
            
            # 11. Delete loan application if exists
            if application_id:
                cursor.execute("DELETE FROM loan_applications WHERE id = %s", (application_id,))
                deleted = cursor.rowcount
                total_deleted['applications'] += deleted
                print(f"  🗑️  Deleted {deleted} loan application")
        
        # Show summary
        print(f"\n{'=' * 100}")
        print("DELETION SUMMARY")
        print(f"{'=' * 100}")
        for key, count in total_deleted.items():
            if count > 0:
                print(f"  ✓ {key.replace('_', ' ').title()}: {count}")
        
        # Commit changes
        conn.commit()
        print(f"\n✅ All deletions committed successfully!")
        print(f"{'=' * 100}")
    
    except Exception as e:
        conn.rollback()
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        cursor.close()
        conn.close()
        print(f"\n{'=' * 100}\n")

if __name__ == '__main__':
    delete_loans()
