"""
Delete loan 25112026-000015 (Benjamin Maina Mwangi) and all related data
Non-interactive - runs automatically
"""
import pymysql

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

LOAN_NUMBER = '25112026-000015'

def delete_loan():
    """Delete loan and all related data"""
    
    print("=" * 100)
    print(f"DELETING LOAN {LOAN_NUMBER} IN PRODUCTION DATABASE")
    print("=" * 100)
    
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    try:
        total_deleted = {
            'general_ledger': 0,
            'journal_entry_lines': 0,
            'journal_entries': 0,
            'mpesa_transactions': 0,
            'receipts': 0,
            'repayments': 0,
            'rollover_requests': 0,
            'loans': 0,
            'applications': 0,
        }
        
        # 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"\n⚠️  Loan {LOAN_NUMBER} not found")
            cursor.close()
            conn.close()
            return
        
        loan_id = loan['id']
        borrower_name = f"{loan['fname']} {loan['lname']}" if loan['fname'] else "Unknown"
        
        print(f"\n✓ Found loan: {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}")
        print()
        
        # 0. Delete general_ledger entries
        try:
            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'] += deleted
            print(f"  🗑️  Deleted {deleted} general ledger entries")
        except Exception as e:
            print(f"  ⚠️  Skipped general ledger: {e}")
        
        # 1. Delete journal_entry_lines
        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
        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. 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']}")
                cursor.execute("""
                    UPDATE loans SET original_loan_id = NULL 
                    WHERE id = %s
                """, (child['id'],))
        
        # 8. 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
        
        # 9. 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")
        
        # 10. 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_loan()
