#!/usr/bin/env python
"""
Delete All Loans for Manual Re-entry
=====================================

This script deletes ALL loans and loan-related data to allow admin to manually
re-enter loans from the beginning.

WHAT GETS DELETED:
- All loans
- All loan applications
- All repayments
- All loan disbursements
- All loan fees
- All loan guarantors
- All loan statuses
- All rollover requests
- All M-Pesa transactions linked to loans
- All receipts
- All loan statements
- All SMS logs
- All SasaPay transactions
- All unconfirmed payments
- All accounting journal entries related to loans

WHAT STAYS INTACT:
- All users/clients (borrowers)
- All expenses
- All loan products
- All branches
- System settings
- Chart of accounts
- Non-loan accounting entries

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

Usage:
    python delete_all_loans_for_manual_entry.py

"""

import os
import sys
from datetime import datetime

# Load environment variables from .env file BEFORE Django setup
try:
    from dotenv import load_dotenv
    # Get the directory where this script is located
    script_dir = os.path.dirname(os.path.abspath(__file__))
    env_path = os.path.join(script_dir, '.env')
    load_dotenv(env_path)
    print(f"✅ Loaded environment variables from: {env_path}")
except ImportError:
    print("⚠️  Warning: python-dotenv not installed")
    print("   Trying to continue with system environment variables...")
except Exception as e:
    print(f"⚠️  Warning: Could not load .env file: {e}")
    print("   Trying to continue with system environment variables...")

import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection, transaction
from django.contrib.auth import get_user_model

User = get_user_model()

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


def print_header():
    """Print script header"""
    print("="*80)
    print(" DELETE ALL LOANS FOR MANUAL RE-ENTRY")
    print(" " + "="*78)
    print(" This script will permanently delete ALL loan data")
    print("="*80)


def print_warning():
    """Print critical warning"""
    print("\n" + "="*80)
    print(" ⚠️  CRITICAL WARNING ⚠️")
    print("="*80)
    print("\nThis script will DELETE ALL LOANS AND LOAN-RELATED DATA!")
    print("\nWhat will be DELETED:")
    print("  ❌ All loans")
    print("  ❌ All loan applications")
    print("  ❌ All repayments")
    print("  ❌ All loan disbursements")
    print("  ❌ All loan fees")
    print("  ❌ All rollover requests")
    print("  ❌ All M-Pesa transactions")
    print("  ❌ All receipts")
    print("  ❌ All loan statements")
    print("  ❌ All SMS logs")
    print("  ❌ All SasaPay transactions")
    print("  ❌ All accounting entries for loans")
    print("\nWhat will be PRESERVED:")
    print("  ✅ All clients/users")
    print("  ✅ All expenses")
    print("  ✅ All loan products")
    print("  ✅ All branches")
    print("  ✅ System settings")
    print("  ✅ Chart of accounts")
    print("\n⚠️  THIS CANNOT BE UNDONE! ⚠️")
    print("\n✅ MAKE SURE YOU HAVE A DATABASE BACKUP!")
    print("\nBackup command:")
    print("  mysqldump -u user -p database > backup_before_delete_$(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_table_count(cursor, table_name, where_clause=""):
    """
    Get count of rows in a table, handling cases where table doesn't exist.
    
    Args:
        cursor: Database cursor
        table_name: Name of the table
        where_clause: Optional WHERE clause (without the WHERE keyword)
    
    Returns:
        Tuple of (count, error_message) where error_message is None if successful
    """
    try:
        sql = f"SELECT COUNT(*) FROM {table_name}"
        if where_clause:
            sql += f" WHERE {where_clause}"
        
        cursor.execute(sql)
        result = cursor.fetchone()
        return (result[0], None)
    except Exception as e:
        return (0, str(e))


def show_current_counts():
    """Show current data counts before deletion"""
    print("\n" + "="*80)
    print(" CURRENT DATABASE COUNTS")
    print("="*80)
    
    with connection.cursor() as cursor:
        tables = [
            ('loans', 'Loans', ''),
            ('loan_applications', 'Loan Applications', ''),
            ('repayments', 'Repayments', ''),
            ('loan_disbursements', 'Loan Disbursements', ''),
            ('loan_fees', 'Loan Fees', ''),
            ('loan_guarantors', 'Loan Guarantors', ''),
            ('loan_statuses', 'Loan Statuses', ''),
            ('rollover_requests', 'Rollover Requests', ''),
            ('mpesa_transactions', 'M-Pesa Transactions', ''),
            ('receipts', 'Receipts', ''),
            ('loan_statements', 'Loan Statements', ''),
            ('sms_logs', 'SMS Logs', ''),
            ('sasapay_transactions', 'SasaPay Transactions', ''),
            ('unconfirmed_payments', 'Unconfirmed Payments', ''),
        ]
        
        for table, label, where in tables:
            count, error = get_table_count(cursor, table, where)
            if error:
                print(f"  ⚠️  {label:<40} (Error: {error})")
            else:
                print(f"  ❌ {label:<40} {count:>7,}")
        
        # Show what will be preserved
        count, _ = get_table_count(cursor, 'users', '')
        print(f"  ✅ {'Users/Clients (WILL BE PRESERVED)':<40} {count:>7,}")
        
        count, _ = get_table_count(cursor, 'expenses', '')
        print(f"  ✅ {'Expenses (WILL BE PRESERVED)':<40} {count:>7,}")


def delete_table_data(cursor, table_name, description, where_clause=""):
    """
    Delete data from a table, handling cases where table doesn't exist.
    
    Args:
        cursor: Database cursor
        table_name: Name of the table to delete from
        description: Human-readable description for logging
        where_clause: Optional WHERE clause (without the WHERE keyword)
    
    Returns:
        Number of rows deleted, or 0 if 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_loan_data():
    """
    Delete all loan-related data from the database.
    Uses transactions to ensure all-or-nothing deletion.
    """
    print("\n" + "="*80)
    print(" DELETING ALL LOAN DATA")
    print("="*80)
    
    deleted_counts = {}
    
    try:
        with transaction.atomic():
            with connection.cursor() as cursor:
                
                # Disable foreign key checks temporarily for easier deletion
                print("\n🔓 Disabling foreign key checks...")
                cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
                
                # Delete in reverse dependency order
                
                # 1. Accounting entries related to loans
                print("\n1️⃣  Deleting accounting journal entries...")
                deleted_counts['accounting_entries'] = delete_table_data(
                    cursor, 
                    'accounting_journalentry',
                    'accounting entries',
                    """description LIKE '%loan%' 
                       OR description LIKE '%disbursement%'
                       OR description LIKE '%repayment%'
                       OR reference_type IN ('loan', 'repayment', 'disbursement')"""
                )
                
                # 2. SMS Logs
                print("\n2️⃣  Deleting SMS logs...")
                deleted_counts['sms_logs'] = delete_table_data(
                    cursor, 'sms_logs', 'SMS logs'
                )
                
                # 3. Receipts
                print("\n3️⃣  Deleting receipts...")
                deleted_counts['receipts'] = delete_table_data(
                    cursor, 'receipts', 'receipts'
                )
                
                # 4. Loan Statements
                print("\n4️⃣  Deleting loan statements...")
                deleted_counts['loan_statements'] = delete_table_data(
                    cursor, 'loan_statements', 'loan statements'
                )
                
                # 5. Unconfirmed Payments
                print("\n5️⃣  Deleting unconfirmed payments...")
                deleted_counts['unconfirmed_payments'] = delete_table_data(
                    cursor, 'unconfirmed_payments', 'unconfirmed payments'
                )
                
                # 6. SasaPay Transactions
                print("\n6️⃣  Deleting SasaPay transactions...")
                deleted_counts['sasapay_transactions'] = delete_table_data(
                    cursor, 'sasapay_transactions', 'SasaPay transactions'
                )
                
                # 7. M-Pesa Transactions
                print("\n7️⃣  Deleting M-Pesa transactions...")
                deleted_counts['mpesa_transactions'] = delete_table_data(
                    cursor, 'mpesa_transactions', 'M-Pesa transactions'
                )
                
                # 8. Loan Statuses
                print("\n8️⃣  Deleting loan statuses...")
                deleted_counts['loan_statuses'] = delete_table_data(
                    cursor, 'loan_statuses', 'loan statuses'
                )
                
                # 9. Loan Guarantors
                print("\n9️⃣  Deleting loan guarantors...")
                deleted_counts['loan_guarantors'] = delete_table_data(
                    cursor, 'loan_guarantors', 'loan guarantors'
                )
                
                # 10. Loan Fees
                print("\n🔟 Deleting loan fees...")
                deleted_counts['loan_fees'] = delete_table_data(
                    cursor, 'loan_fees', 'loan fees'
                )
                
                # 11. Loan Disbursements
                print("\n1️⃣1️⃣  Deleting loan disbursements...")
                deleted_counts['loan_disbursements'] = delete_table_data(
                    cursor, 'loan_disbursements', 'loan disbursements'
                )
                
                # 12. Repayments
                print("\n1️⃣2️⃣  Deleting repayments...")
                deleted_counts['repayments'] = delete_table_data(
                    cursor, 'repayments', 'repayments'
                )
                
                # 13. Rollover Requests
                print("\n1️⃣3️⃣  Deleting rollover requests...")
                deleted_counts['rollover_requests'] = delete_table_data(
                    cursor, 'rollover_requests', 'rollover requests'
                )
                
                # 14. Loans
                print("\n1️⃣4️⃣  Deleting loans...")
                deleted_counts['loans'] = delete_table_data(
                    cursor, 'loans', 'loans'
                )
                
                # 15. Loan Applications
                print("\n1️⃣5️⃣  Deleting loan applications...")
                deleted_counts['loan_applications'] = delete_table_data(
                    cursor, 'loan_applications', 'loan applications'
                )
                
                # Re-enable foreign key checks
                print("\n🔒 Re-enabling foreign key checks...")
                cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
        
        return deleted_counts
        
    except Exception as e:
        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(" WHAT TO DO NEXT")
    print("="*80)
    print("\n1. Verify the data was deleted:")
    print("   - Check the system to confirm all loans are gone")
    print("   - Verify clients/users are still present")
    print("   - Check that expenses are intact")
    print("\n2. Manually re-enter the loans:")
    print("   - Use the admin interface to add loans")
    print("   - Enter correct loan details")
    print("   - Verify loan numbers follow the new format: DDMMYYYY-NNNNNN")
    print("\n3. Monitor the system:")
    print("   - Check repayment processing")
    print("   - Verify SMS notifications work")
    print("   - Test rollover functionality")


def main():
    """Main execution function"""
    try:
        print_header()
        print_warning()
        
        # Check confirmation
        if not check_confirmation():
            return False
        
        # Show current counts
        show_current_counts()
        
        # Final warning with countdown
        print("\n" + "="*80)
        print(" FINAL WARNING")
        print("="*80)
        print("\nThe script will now DELETE ALL LOAN DATA in 3 seconds...")
        print("Press Ctrl+C NOW to cancel!")
        
        import time
        for i in range(3, 0, -1):
            print(f"  Deleting in {i}...")
            time.sleep(1)
        
        # Delete all loan data
        deleted_counts = delete_all_loan_data()
        
        # 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.")
        return False
    except Exception as e:
        print(f"\n❌ Script failed with error: {e}")
        import traceback
        traceback.print_exc()
        return False


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